Object Oriented concept-JAVA-Module-1-PPT.pptx

ASHWINIGOWDA46 67 views 233 slides Jul 23, 2024
Slide 1
Slide 1 of 318
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206
Slide 207
207
Slide 208
208
Slide 209
209
Slide 210
210
Slide 211
211
Slide 212
212
Slide 213
213
Slide 214
214
Slide 215
215
Slide 216
216
Slide 217
217
Slide 218
218
Slide 219
219
Slide 220
220
Slide 221
221
Slide 222
222
Slide 223
223
Slide 224
224
Slide 225
225
Slide 226
226
Slide 227
227
Slide 228
228
Slide 229
229
Slide 230
230
Slide 231
231
Slide 232
232
Slide 233
233
Slide 234
234
Slide 235
235
Slide 236
236
Slide 237
237
Slide 238
238
Slide 239
239
Slide 240
240
Slide 241
241
Slide 242
242
Slide 243
243
Slide 244
244
Slide 245
245
Slide 246
246
Slide 247
247
Slide 248
248
Slide 249
249
Slide 250
250
Slide 251
251
Slide 252
252
Slide 253
253
Slide 254
254
Slide 255
255
Slide 256
256
Slide 257
257
Slide 258
258
Slide 259
259
Slide 260
260
Slide 261
261
Slide 262
262
Slide 263
263
Slide 264
264
Slide 265
265
Slide 266
266
Slide 267
267
Slide 268
268
Slide 269
269
Slide 270
270
Slide 271
271
Slide 272
272
Slide 273
273
Slide 274
274
Slide 275
275
Slide 276
276
Slide 277
277
Slide 278
278
Slide 279
279
Slide 280
280
Slide 281
281
Slide 282
282
Slide 283
283
Slide 284
284
Slide 285
285
Slide 286
286
Slide 287
287
Slide 288
288
Slide 289
289
Slide 290
290
Slide 291
291
Slide 292
292
Slide 293
293
Slide 294
294
Slide 295
295
Slide 296
296
Slide 297
297
Slide 298
298
Slide 299
299
Slide 300
300
Slide 301
301
Slide 302
302
Slide 303
303
Slide 304
304
Slide 305
305
Slide 306
306
Slide 307
307
Slide 308
308
Slide 309
309
Slide 310
310
Slide 311
311
Slide 312
312
Slide 313
313
Slide 314
314
Slide 315
315
Slide 316
316
Slide 317
317
Slide 318
318

About This Presentation

Java basic concepts related to engineering 3rd sem syllabus


Slide Content

Java™: The Complete Reference UNIT – 1 & Chapter - 1

Syllabus The History and Evolution of Java: Java’s Lineage, The Creation of java, how java changed the internet, Java’s magic: The byte code, Servlets: java on the server side, java Buzzwords, Evolution of java. An Overview of Java: Object Oriented Programming, Two control statements, Using blocks of codes, Lexical issues, The java class Libraries. Data Types, Arrays and Variables: Primitive Types, Integers, Floating- point Types, Characters, Booleans, literals, variables, Type conversion and casting, Automatic Type Promotion in Expressions, Arrays, strings, Pointers.

Java’s Lineage Java is related to C++, which is a direct descendant of C. Much of the character of Java is inherited from these two languages. From C, Java derives its syntax. Many of Java’s object- oriented features were influenced by C++.

The Birth of Modern Programming: C The C language shook the computer world. When a computer language is designed, trade- offs are often made, such as the following: Ease- of- use versus power Safety versus efficiency Rigidity versus extensibility Invented and first implemented by Dennis Ritchie on a DEC PDP- 11 running the UNIX operating system, C was the result of a development process that started with an older language called BCPL, developed by Martin Richards. BCPL influenced a language called B, invented by Ken Thompson, which led to the development of C in the 1970s. C was formally standardized in December 1989, when the American National Standards Institute (ANSI) standard for C was adopted. C is a language designed by and for programmers.

C++: The Next Step C is a successful and useful language, you might ask why a need for something else existed. The answer is complexity . To solve this problem, a new way to program was invented, called object- oriented programming ( OOP ). C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called the new language “C with Classes.” However, in 1983, the name was changed to C++. C++ extends C by adding object- oriented features.

The Stage Is Set for Java By the end of the 1980s and the early 1990s, object- oriented programming using C++ took hold. Within a few years, the World Wide Web and the Internet would reach critical mass. This event would precipitate another revolution in programming.

The Creation of Java Java was conceived by James Gosling , Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “ Oak ,” but was renamed “Java” in 1995. Primary motivation was the need for a platform- independent (that is, architecture- neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. The problem is that compilers are expensive and time- consuming to create. Solution, a portable, platform- independent language

The Creation of Java The second force was, of course, the World Wide Web . The emergence of the World Wide Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs. The Internet ultimately led to Java’s large- scale success. Java is simply the “Internet version of C++.” Java was to Internet programming what C was to system programming: a revolutionary force that changed the world .

The C# Connection C#. Created by Microsoft to support the .NET Framework. C# is closely related to Java. For example, both share the same general syntax, support distributed programming, and utilize the same object model.

How Java Changed the Internet Java innovated a new type of networked program called the applet that changed the way the online world thought about content. Java also addressed some of the thorniest issues associated with the Internet: portability and security .

Java Applets An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Java- compatible web browser. Applets are intended to be small programs . They are typically used to display data provided by the server, handle user input, or provide simple functions, such as a loan calculator, that execute locally, rather than on the server. In essence, the applet allows some functionality to be moved from the server to the client . The creation of the applet changed Internet programming because it expanded the universe of objects that can move about freely in cyberspace.

Java Applets Two very broad categories of objects that are transmitted between the server and the client: passive information and e- mail, you are viewing passive data. dynamic, active programs. the applet is a dynamic, self- executing program. As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability . Obviously, a program that downloads and executes automatically on the client computer must be prevented from doing harm . It must also be able to run in a variety of different environments and under different operating systems . As you will see, Java solved these problems in an effective and elegant way.

Security Every time you download a “normal” program, a risk, because the code you are downloading might contain a virus, Trojan horse, or other harmful code. For example, a virus program might gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer’s local file system. Java enabled applets, to be downloaded and executed on the client computer safely. Java achieved this protection by confining an applet to the Java execution environment and not allowing it access to other parts of the computer. The ability to download applets with confidence that no harm will be done and that no security will be breached is considered by many to be the single most innovative aspect of Java.

Portability Portability is a major aspect of the Internet because there are many different types of computers and operating systems connected to it. If a Java program were to be run on virtually any computer connected to the Internet, there needed to be some way to enable that program to execute on different systems. For example, applet must be able to be downloaded and executed by the wide variety of CPUs, operating systems, and browsers connected to the Internet. It is not practical to have different versions of the applet for different computers. The same code must work on all computers. Therefore, some means of generating portable executable code was needed.

Java’s Magic: The Bytecode The key that allows Java to solve both the security and the portability, the output of a Java compiler is not executable code. Rather, it is bytecode . Bytecode is a highly optimized set of instructions designed to be executed by the Java run- time system, which is called the Java Virtual Machine ( JVM ). In essence, the original JVM was designed as an interpreter for bytecode.

Java’s Magic: The Bytecode Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform. Once the run- time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform , all understand the same Java bytecode. The execution of bytecode by the JVM is the easiest way to create truly portable programs. The Java program is executed by the JVM helps to make it secure . Because the JVM is in control, it can contain the program and prevent it from generating side effects outside of the system.

Java’s Magic: The Bytecode In general, when a program is compiled to an intermediate form and then interpreted by a virtual machine, it runs slower than it would run if compiled to executable code. However, with Java, the differential between the two is not so great. Because bytecode has been highly optimized, the use of bytecode enables the JVM to execute programs much faster than you might expect. Java was designed as an interpreted language , there is nothing about Java that prevents on- the- fly compilation of bytecode into native code in order to boost performance. • Sun began supplying its HotSpot technology.

HotSpot HotSpot provides a Just- In- Time ( JIT ) compiler for bytecode. When a JIT compiler is part of the JVM , selected portions of bytecode are compiled into executable code in real time, on a piece- by- piece , demand basis. It is important to understand that it is not practical to compile an entire Java program into executable code all at once, because Java performs various run- time checks that can be done only at run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore, not all sequences of bytecode are compiled— only those that will benefit from compilation. The remaining code is simply interpreted. However, the just- in- time approach still yields a significant performance boost . Even when dynamic compilation is applied to bytecode, the portability and safety features still apply, because the JVM is still in charge of the execution environment.

Servlets: Java on the Server Side As useful as applets can be, they are just one half of the client/server equation. At Serverside, servlet . A servlet is a small program that executes on the server. Just as applets dynamically extend the functionality of a web browser , servlets dynamically extend the functionality of a web server . Thus, with the advent of the servlet, Java spanned both sides of the client/server connection. Servlets are used to create dynamically generated content that is then served to the client. For example , an online store might use a servlet to look up the price for an item in a database. Dynamically generated content is available through mechanisms such as CGI (Common Gateway Interface). Because servlets (like all Java programs) are compiled into bytecode and executed by the JVM, they are highly portable. Thus, the same servlet can be used in a variety of different server environments. The only requirements are that the server support the JVM and a servlet container.

JVM A Virtual Machine is a software implementation of a physical machine. Java was developed with the concept of WORA ( Write Once Run Anywhere ) , which runs on a VM . The compiler compiles the Java file into a Java .class file, then that .class file is input into the JVM, which loads and executes the class file.

myprog.c myprog.exe OS/Hardware machine code C source code gcc Platform Dependent JVM myprog.class bytecode Java source code myprog.java javac OS/Hardware Platform Independent

The Java Buzzwords The key considerations were summed up by the Java team in the following list of buzzwords: Simple Secure Portable Object- oriented Robust Multithreaded Architecture- neutral Interpreted High performance Distributed Dynamic

The Java Buzzwords : Simple Based on popular languages called C and C++ C: old, pretty bare bones language C++: newer, more complicated language Start from C and add some of C++’s more useful features “ Java omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefits ” (Gosling)

The Java Buzzwords : Secure

The Java Buzzwords : Portable

The Java Buzzwords : Object Oriented The object- oriented paradigm problems and their solutions are packaged in terms of classes the information in a class is the data the functionality in a class is the method a class provides the framework for building objects Object- oriented programming (OOP) allows pieces of programs to be used in other contexts more easily

The Java Buzzwords : Robust program must execute reliably in a variety of systems. Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. A robust program may not do exactly what it is supposed to do, but it should not bring down other unrelated programs down with it Reliability early (compile time) checking dynamic (runtime) checking eliminating situations that are error prone. Example: Two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run- time errors).

The Java Buzzwords : Multithread Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. A thread is a part of the program that can operate independently of its other parts Multi- threaded programs can do multiple things at once example: download a file from the web while still looking at other web pages Question: What is the problem with multiple agents working at the same time? synchronization

The Java Buzzwords : Architecture- Neutral Goal was “write once; run anywhere, any time, forever.” One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow— even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction.

The Java Buzzwords : Interpreted and High Performance Java enables the creation of cross- platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. Most previous attempts at cross- platform solutions have done so at the expense of performance. The Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just- in- time compiler (JIT). Java run- time systems that provide this feature lose none of the benefits of the platform- independent code.

The Java Buzzwords: Distributed Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. Java also supports Remote Method Invocation ( RMI ). This feature enables a program to invoke methods across a network.

The Java Buzzwords: Dynamic Java programs carry with them substantial amounts of run- time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of bytecode may be dynamically updated on a running system.

The Evolution of Java JDK 1.02 (1995) JDK 1.1 (1996) Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998) Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000) Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002) Java Standard Edition (J2SE) J2SE can be used to develop client- side standalone applications or applets. Java Enterprise Edition (J2EE) J2EE can be used to develop server- side applications such as Java servlets and Java ServerPages. Java Micro Edition (J2ME). J2ME can be used to develop applications for mobile devices such as cell phones.

Types of Java Programs Standalone applications (J2SE) AWT (Abstract Window Toolkit) and swing are used to create stand alone application. Web applications (JSP) Applet, Servlet, jsp, jsf which are used to create web applications. Enterprise applications (J2EE) designed for corporate sides such as banking business systems Mobile applications (J2ME) – Mobile application is developed for run the mobile phones and tablets.

Java IDE Tools Forte by Sun MicroSystems Borland JBuilder Microsoft Visual J++ WebGain Café IBM Visual Age for Java ECLIPSE

Java™: The Complete Reference UNIT – 1 & Chapter - 2

What you learn in Previous Class

T o d a y ’ s Agenda OOP Concepts First Java Program About main()

Object- Oriented Programming Two Paradigms – All computer programs consist of two elements: code and data . Furthermore, a program can be conceptually organized around its code or around its data. That is, some programs are written around “ what is happening ” and others are written around “ who is being affected .” These are the two paradigms that govern how a program is constructed.

Object- Oriented Programming process- oriented model The process- oriented model can be thought of as code acting on data. C employ this model. object- oriented programming Object- oriented programming organizes a program around its data (that is, objects ) and a set of well- defined interfaces to that data. An object- oriented program can be characterized as data controlling access to code .

Abstraction An essential element of object- oriented programming is abstraction. Humans manage complexity through abstraction. Example, people do not think of a car as a set of tens of thousands of individual parts. Instead, they are free to utilize the object as a whole. A powerful way to manage abstraction is through the use of hierarchical classifications . This allows you to layer the semantics of complex systems, breaking them into more manageable pieces.

Abstraction Hierarchical abstractions of complex systems can also be applied to computer programs. The data from a traditional process- oriented program can be transformed by abstraction into its component objects. A sequence of process steps can become a collection of messages between these objects. Thus, each of these objects describes its own unique behavior . You can treat these objects as concrete entities that respond to messages telling them to do something. This is the essence of object- oriented programming. Object- oriented programming is a powerful and natural paradigm for creating programs that survive the inevitable changes accompanying the life cycle of any major software project, including conception, growth, and aging.

The Three OOP Principles Encapsulation Inheritance Polymorphism

Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. To relate this to the real world, You can’t affect the transmission by using the turn signal or windshield wipers, for example.

Encapsulation In Java, the basis of encapsulation is the class . A class defines the structure and behavior (data and code) that will be shared by a set of objects . Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out by a mold in the shape of the class. For this reason, objects are sometimes referred to as instances of a class . Thus, a class is a logical construct ; an object has physical reality .

Encapsulation When you create a class, you will specify the code and data that constitute that class. Collectively, these elements are called members of the class . Specifically, the data defined by the class are referred to as member variables or instance variables . The code that operates on that data is referred to as member methods or just methods . Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked private or public .

class { //member data int x; int y; //member method public void getxy() { //code } public void putxy() { //code } }

FIGURE 2- 1 Encapsulation: public methods can be used to protect private data

Inheritance Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification . Inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

FIGURE 2- 2 Labrador inherits the encapsulation of all its superclasses

Grand Parent Parent Child

Inheritance Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then any subclass will have the same attributes plus any that it adds as part of its specialization. This is a key concept that lets object- oriented programs grow in complexity linearly rather than geometrically. A new subclass inherits all of the attributes of all of its ancestors. It does not have unpredictable interactions with the majority of the rest of the code in the system.

Polymorphism Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. Ex:- Consider a stack (which is a last- in, first- out list). The concept of polymorphism is often expressed by the phrase “ one interface, multiple methods .” This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface. Example: a dog’s sense of smell is polymorphic.

Polymorphism, Encapsulation, and Inheritance Work Together When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scalable programs than does the process- oriented model. A well- designed hierarchy of classes is the basis for reusing the code in which you have invested time and effort developing and testing. Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. Polymorphism allows you to create clean, sensible, readable, and resilient code.

A First Simple Program Enter the program and save as Example.java Compile the Program c:\myjava\javac Example.java Run the Program c:\myjava\javac Example RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

Comments The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. Java supports three styles of comments. multiline comment ( /* single- line comment ( // documentation comment ( /** */ ) ) */ ) – This type of comment is used to produce an HTML file that documents your program.

public static void main(String args[]) The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java Virtual Machine before any objects are made. The keyword void simply tells the compiler that main() does not return a value. In main( ), there is only one parameter, String args[ ] declares a parameter named args, which is an array of instances of the class String.

System.out.println(); println( ) displays the string which is passed to it. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. All statements in Java end with a semicolon . A variable is a named memory location that may be assigned a value by your program. The value of a variable may be changed during the execution of the program.

class Example2 { public static void main(String args[]) { int num; num = 100; // this declares a variable called num // this assigns num the value 100 System.out.println("This is num: " + num); num = num * 2; System.out.print("The value of num * 2 is "); System.out.println(num); } } type var- name; type specifies the type of variable being declared, and var- name is the name of the variable.

Using Blocks of Code Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between opening and closing curly braces . Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. if(x < y) { x = y; y = 0; } // begin a block // end of block

/* Demonstrate a block of code. */ } Output: This is x: This is y: 20 This is x: 1 This is y: 18 This is x: 2 This is y: 16 class BlockTest { public static void main(String args[]) { int x, y; y = 20; // the target of this loop is a block for(x = 0; x<10; x++) { System.out.println("This is x: " + x); System.out.println("This is y: " + y); y = y - 2; } } This is x: 3 This is y: 14 This is x: 4 This is y: 12 This is x: 5 This is y: 10 This is x: 6 This is y: 8 This is x: 7 This is y: 6 This is x: 8 This is y: 4 This is x: 9 This is y: 2

Lexical Issues Java programs are a collection of whitespace, identifiers, literals, comments, operators, separators, and keywords . Whitespace Java is a free- form language. This means that you do not need to follow any special indentation rules. In Java, whitespace is a space, tab, or newline. Identifiers Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar- sign characters. They must not begin with a number. Java is case- sensitive.

Lexical Issues Literals A constant value in Java is created by using a literal representation of it. Comments Three types of comments defined by Java.

Lexical Issues Separators In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon.

Lexical Issues The Java Keywords There are 50 keywords currently defined in the Java language These keywords cannot be used as names for a variable, class, or method. In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java.

The Java Class Libraries println( ) and print( ), these methods are members of the System class.

End of today session: Student can be able to understand OOP concepts Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 3

Java Is a Strongly Typed Language Java is a strongly typed language. First , every variable has a type, every expression has a type, and every type is strictly defined. Second , all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.

Data Types in Java Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. Non- primitive data types: The non- primitive data types include Classes, Interfaces, and Arrays. Integers: This group includes byte, short, int, and long, which are for whole- valued signed numbers. Floating- point numbers: This group includes float and double, which represent numbers with fractional precision. Characters :This group includes char, which represents symbols in a character set, like letters and numbers. Boolean: This group includes boolean, which is a special type for representing true/false values.

Data Type Default Value Default size Example Range boolean false 1 bit Boolean one = false true and false char '\u0000' 2 byte char ch = 'A' '\u0000' (or 0) to '\uffff' (or 65,535) (or) to 65,536 byte 1 byte byte a = 10 - 128 to 127 Short 2 byte short s = 10000 –32,768 to 32,767 int 4 byte int a = 100000 –2,147,483,648 to 2,147,483,647 long 0L 8 byte long a = 100000L –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 0.0f 4 byte float f1 = 234.5f 1.4e–045 to 3.4e+038 double 0.0d 8 byte double d1 = 12.3 4.9e–324 to 1.8e+308 char uses 2 byte in java and \u0000, java uses Unicode system not ASCII code system.

// Compute the area of a circle. class Area { public static void main(String args[]) { double pi, r, a; r = 10.8; // radius of circle pi = 3.1416; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); } } // Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } output: ch1 and ch2: X Y

// char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; // increment ch1 System.out.println("ch1 is now " + ch1); } } Output: ch1 contains X ch1 is now Y

Exercises Addition of two numbers. Convert Fahrenheit to Celsius. Area of circle Simple Interest. int x = 10 ; int y = 9 ; System . out . println ( x > y ); // returns true, because 10 is higher than 9

Integer Literals Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number. There are two other bases which can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal values are denoted in Java by a leading zero . Ex: 05 Normal decimal numbers cannot have a leading zero. Hexadecimal constant with a leading zero- x, ( 0x or 0X). Ex: 0x5 The range of a hexadecimal digit is to 15, so A through F (or a through f ). For binary , leading 0b or 0B Ex: 0b1000001; (‘A’)

public class Test { public static void main(String args[]) { char c = 0b1000001; // Binary System.out.println(c); c=0101; //Octal System.out.println(c); c=0x41; //Hexadecimal System.out.println(c); } }

Floating- Point Literals Floating- point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation . Standard notation consists of a whole number component followed by a decimal point followed by a fractional component (ex, 2.0, 3.14159, and 0.6667). Scientific notation uses a standard- notation, floating- point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05,and 2e+100.

Floating- Point Literals Floating- point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. Ex: 3.4f explicitly specify a double literal by appending a D or d . Ex: 2.5d

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false . The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1 , nor does the false literal equal 0.

Character Literals Characters in Java are indices into the Unicode character set. They are 16- bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. A literal character is represented inside a pair of single quotes . Ex: ‘a’, ‘ z ’ , and ‘@’. For characters that are impossible to enter directly, escape sequences , ‘\’’ for the single- quote character and ‘\n’ for the newline character.

Character Literals There is also a mechanism for directly entering the value of a character in octal or hexadecimal. For octal notation , use the backslash followed by the three- digit number. For example, ‘\141’ is the letter ‘a’. For hexadecimal , enter a backslash- u ( \u), then exactly four hexadecimal digits. For example, ‘\u0061’ is the ISO- Latin- 1 ‘a’ because the top byte is zero. ‘\ua432’ is a Japanese Katakana character.

TABLE 3- 1 Character Escape Sequences

public class EscapeExample { public static void main(String args[]) { String str = new String ("My name is \'abcd\'"); System.out.println(str); str = "My Lab is \"JAVA LAB\""; System.out.println(str); str = "My work files are in D:\\Work Projects\\java"; System.out.println(str); str = "First Line \nSecond Line"; System.out.println(str); str = "Ravindra\b\b" + "College"; System.out.println(str); str = "Ravindra \rCollege"; System.out.println(str); str = "Ravindra \fCollege"; System.out.println(str); } }

String Literals String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes . One important thing to note about Java strings is that they must begin and end on the same line . There is no line- continuation escape sequence as there is in some other languages. Ex: “Hello World” “two\nlines” “\”This is in quotes\”“

Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier , a type , and an optional initializer . In addition, all variables have a scope , which defines their visibility , and a lifetime . Declaring a Variable In Java, all variables must be declared before they can be used. syntax type identifier [ = value][, identifier [= value] ...] ; The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the variable. Initialize the variable by specifying an equal sign and a value

Variables To declare more than one variable of the specified type, use a comma separated list . int a, b, c; int d = 3, e, f = 5; byte z = 22; // declares three ints, a, b, and c. // declares three more ints, initializing // d and f. // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. // Demonstrate dynamic initialization. class DynInit { public static void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); } }

The Scope and Lifetime of Variables A block defines a scope . A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects. In Java, the two major scopes are those defined by a class and those defined by a method. The scope defined by a method begins with its opening curly brace. As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Scopes can be nested . Objects declared within the inner scope will not be visible outside it.

// Demonstrate block scope. class Scope { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x); } }

// Demonstrate lifetime of a variable. class LifeTime { public static void main(String args[]) { int x; for(x = 0; x < 3; x++) { int y = - 1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints - 1 y = 100; System.out.println("y is now: " + y); } } } Output: y is: - 1 y is now: 100 y is: - 1 y is now: 100 y is: - 1 y is now: 100 // This program will not compile class ScopeErr { public static void main(String args[]) { int b = 1; { // creates a new scope int b = 2; // Compile- time error – b already defined ! } } }

Type Conversion and Casting If the two types are compatible, then Java will perform the conversion automatically . Ex: assign an int value to a long variable no automatic conversion defined from double to byte. Conversion between incompatible types, use a cast , which performs an explicit conversion between incompatible types.

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Java’s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: The two types are compatible . The destination type is larger than the source type. Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.

Casting Incompatible Types To create a conversion between two incompatible types , you must use a cast . A cast is simply an explicit type conversion . Syntax: ( target- type) value Assign an int value to a byte variable, byte is smaller than an int, This kind of conversion is sometimes called a narrowing conversion A different type of conversion will occur when a floating- point value is assigned to an integer type: truncation .

// Demonstrate casts. class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } } OUTPUT: Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67

Automatic Type Promotion in Expressions In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand . byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when evaluating an expression.

Automatic Type Promotion in Expressions byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte! The operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. byte b = 50; b = (byte) (b * 2); which yields the correct value of 100.

The Type Promotion Rules Java defines several type promotion rules that apply to expressions. They are as follows: First , all byte, short, and char values are promoted to int . Then, if one operand is a long , the whole expression is promoted to long . If one operand is a float , the entire expression is promoted to float . If any of the operands is double , the result is double .

class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); } } OUTPUT: 238.14 + 515 - 126.3616 result = 626.7784146484375

End of today session: Student can be able to understand Data type concepts along with programs RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 3

Scanner class The Scanner class in Java is used for taking input from the user. The Scanner class can take input of all the data types. Scanner splits the input after every whitespace. This class is present in java.util.Scanner package.

Scanner class There are two constructors of the Scanner class that are used. One is the InputStream object and other takes a FileReader object. Syntax: Scanner in = new Scanner(System.in); //InputStream Scanner inFile = new Scanner(new FileReader(“File_Object”)); If file is not found “FileNotFoundException” is thrown.

Scanner class Methods public String nextLine() :- Moves the scanner to the next line and returns the skipped input. public String next() :- Returns the token before delimiter public byte nextByte() :- Scans next token as byte value public short nextShort() :- Scans next token as short value public int nextInt() :- Scans next token as integer value public long nextLong() :- Scans next token as long value public float nextFloat() :- Scans next token as float value public double nextDouble() :- Scans next token as double value void close :- Scanner is closed

Arrays An array is a group of like- typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index . Arrays offer a convenient means of grouping related information. If you are familiar with C/C++, be careful . Arrays in Java work differently than they do in those languages. Normally, an array is a collection of similar type of elements which have a contiguous memory location .

One- Dimensional Arrays A one- dimensional array is, essentially, a list of like- typed variables. type var- name[ ]; (or) dataType[] arr; (or) dataType []arr; Here, type declares the base type of the array int month_days[];

myarray = new int[10];

One- Dimensional Arrays int month_days[]; This declaration establishes the fact that month_days is an array variable, no array actually exists. In fact, the value of month_days is set to null , which represents an array with no value . To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to month_days. new is a special operator that allocates memory. array- var = new type[size]; month_days = new int[12];

int month_days[]; month_days = new int[12]; After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in the array will be initialized to zero . Obtaining an array is a two- step process . First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated .

Once you have allocated an array, you can access a specific element in the array by specifying its index within square brackets . All array indexes start at zero . month_days[1] = 28;

class Testarray{ public static void main(String args[]){ int a[]= new int [5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for ( int i=0;i<a.length;i++) //length is the of array System.out.println(a[i]); } }

Arrays can be initialized when they are declared. The process is much the same as that used to initialize the simple types. An array initializer is a list of comma- separated expressions surrounded by curly braces . The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new. int a[]={1,2,3,4,5};

For- each Loop for Java Array We can also print the Java array using for- each loop . The Java for- each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop. for (data_type variable : array){ //body of the loop }

public class PrintArray { public static void main(String [] args){ String[] array = { "hi", "hello", "java"}; for(String str : array) { System.out.println(str); } } }

//Print month name along with no of days class MonthArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; String month_names[] = {"Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; for(int i=0;i<12;i++) { System.out.println(month_names[i] + " is having " + month_days[i] + " days."); } } }

Home Task Print array elements Print array elements in reverse order Print odd elements Merge two arrays into third array Copy even elements to even array and odd elements to odd array from the original array. Sort array elements

Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays . To declare a multidimensional array variable, specify each additional index using another set of square brackets. int twoD[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twoD. Syntax: dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];

// Demonstrate a two- dimensional array. class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }

Jagged Array in Java Creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of arrays with different number of columns .

// Manually allocate differing size second dimensions. class TwoDAgain { public static void main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<i+1; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } } This program generates the following output: 1 2 3 4 5 6 7 8 9

It is possible to initialize multidimensional arrays . To do so, simply enclose each dimension’s initializer within its own set of curly braces. int arr[][]={ {1,2,3}, {2,4,5}, {4,4,5} };

class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for ( int i=0;i<3;i++){ for ( int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }} Output: 1 2 3 2 4 5 4 4 5

// Demonstrate a three- dimensional array. class ThreeDMatrix { public static void main(String args[]) { int threeD[][][] = new int[3][4][5]; int i, j, k; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<5; k++) threeD[i][j][k] = i * j * k; for(i=0; i<3; i++) { for(j=0; j<4; j++) { for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + " "); System.out.println(); } System.out.println(); } } } output: 1 2 3 4 2 4 6 8 3 6 9 12 2 4 6 8 4 8 12 16 6 12 18 24

Alternative Array Declaration Syntax There is a second form used to declare an array: type[ ] var- name; int a1[] = new int[3]; int[] a2 = new int[3]; char twod1[][] = new char[3][4]; char[][] twod2 = new char[3][4]; int[] nums, nums2, nums3; // create three arrays

String Java’s string type, called String , is not a simple type. Nor is it simply an array of characters. Rather, String defines an object. The String type is used to declare string variables. Also declare arrays of strings. A quoted string constant can be assigned to a String variable. A variable of type String can be assigned to another variable of type String. String str = "this is a test"; System.out.println(str);

class StrDemo { public static void main(String args[]) { String str1 = new String(); str1 = "Hello World"; System.out.println(str1); String str2 = "Bye Bye"; System.out.println(str1+str2); } }

Pointers Java does not support or allow pointers. Java cannot allow pointers, because doing so would allow Java programs to breach the firewall between the Java execution environment and the host computer. (Remember, a pointer can be given any address in memory— even addresses that might be outside the Java run- time system.) Java is designed in such a way that as long as you stay within the confines of the execution environment, you will never need to use a pointer, nor would there be any benefit in using one.

End of today session: Students can be able to implement programs. Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 4

What you learn in Previous Class

T od a y ’ s Agenda Operators: Arithmetic Operators, The Bitwise Operators, Relational Operators, Boolean Logic operators, The assignment operator, The ? Operator, Operator Precedence, Using Parentheses.

Operators Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations.

Arithmetic Operators The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.

// Demonstrate the basic arithmetic operators. class BasicMath { public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; int e = - d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); // arithmetic using doubles System.out.println("\nFloating Point Arithmetic"); double da = 1 + 1; double db = da * 3; double dc = db / 4; double dd = dc - a; double de = - dd; System.out.println("da = " + da); System.out.println("db = " + db); System.out.println("dc = " + dc); System.out.println("dd = " + dd); System.out.println("de = " + de); } }

The Modulus Operator (%) Arithmetic Compound Assignment Operators (+=) Increment and Decrement (++, -- ) public class IncOp { public static void main(String args[]) { int x=1; int r = -- x + x++ + ++x + x- - ; System.out.println(x + " " + r); } }

//Guess the output public class Test { public static void main(String[] args) { int a = 10; int b = ++(++a); System.out.println(b); } } //final variable public class Test { public static void main(String[] args) { final int a = 10; int b = ++a; System.out.println(b); } }

// Can not be applied boolean data type public class Test { public static void main(String[] args) { boolean b = false; b++; System.out.println(b); } }

The Bitwise Operators Java defines several bitwise operators that can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands.

The Bitwise Operators The byte value for 42 in binary is 00101010, where each position represents a power of two, starting with 2 at the rightmost bit. All of the integer types (except char) are signed integers. This means that they can represent negative values as well as positive ones. Java uses an encoding known as two’s complement, which means that negative numbers are represented by inverting (changing 1’s to 0’s and vice versa) all of the bits in a value, then adding 1 to the result. Example, –42 is represented by inverting all of the bits in 42, or 00101010, which yields 11010101, then adding 1, which results in 11010110, or –42.

Bitwise OR (|) – This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 0111 = 7 (In decimal) Bitwise AND (&) – This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise AND Operation of 5 and 7 0101 & 0111 0101 = 5 (In decimal)

Bitwise XOR (^) – This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise XOR Operation of 5 and 7 0101 ^ 0111 0010 = 2 (In decimal) Bitwise Complement (~) – This operator is unary operator, denoted by ‘~’. It returns the one’s compliment representation of the input value, i.e, with all bits inversed, means it makes every to 1, and every 1 to 0. For example, a = 5 = 0101 (In Binary) Bitwise Compliment Operation of 5 ~ 0101 1010 = 10 (In decimal)

public class Bitoperators { public static void main(String[] args) { int a = 5; int b = 7; // bitwise and System.out.println("a&b = " + (a & b)); // bitwise or System.out.println("a|b = " + (a | b)); // bitwise xor System.out.println("a^b = " + (a ^ b)); // bitwise not ~0101=1010 // will give 2's complement of 1010 = - 6 System.out.println("~a = " + ~a); // assignment a=a&b a &= b; System.out.println("a= " + a); } } Output : a&b = 5 a|b = 7 a^b = 2 ~a = - 6 a= 5

Shift Operators These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. Syntax number shift_op number_of_shift; Signed Right shift operator (>>) Unsigned Right shift operator (>>>) Left shift operator (<<)

log2base2 Visit log2base2 site for animations

public class Shiftoperators { public static void main(String[] args) { int a = 5; int b = - 10; // left shift operator // 0000 0101<<2 =0001 0100 // similar to 5*(2^2) (20) System.out.println("a<<2 = " + (a << 2)); // right shift operator // 0000 0101 >> 2 =0000 0001 // similar to 5/(2^2) (1) System.out.println("b>>2 = " + (b >> 2)); // unsigned right shift operator System.out.println("b>>>2 = " + (b >>> 2)); } } Output : a<<2 = 20 b>>2 = - 3 b>>>2 = 1073741821

Relational Operators The outcome of these operations is a boolean value.

Boolean Logical Operators

Short- Circuit Logical Operators Java provides two interesting Boolean operators, These are secondary versions of the Boolean AND and OR operators, and are known as short- circuit logical operators. The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right- hand operand when the outcome of the expression can be determined by the left operand alone. This is very useful when the right- hand operand depends on the value of the left one in order to function properly.

Short- Circuit Logical Operators if (denom != && num / denom > 10) Since the short- circuit form of AND (&&) is used, there is no risk of causing a run- time exception when denom is zero. If this line of code were written using the single & version of AND, both sides would be evaluated, causing a run- time exception when denom is zero.

import java.io.*; import java.util.Scanner; public class AndopEx { public static void main(String[] args) { int x, y; int sum=0; Scanner sobj = new Scanner(System.in); System.out.println("Enter x & y vals: ") x = sobj.nextInt(); y = sobj.nextInt(); ; if(x>0 && ++y>0) sum = x+y; System.out.println("x=" + x + " and y=" + y + "\nx+y=" + sum); } }

The Assignment Operator var = expression ; int x, y, z; x = y = z = 100; // set x, y, and z to 100 This fragment sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right- hand expression . Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x. Using a “ chain of assignment ” is an easy way to set a group of variables to a common value.

The ? Operator Java includes a special ternary (three- way) operator that can replace certain types of if- then- else statements. This operator is the ? . expression1 ? expression2 : expression3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same type , which can’t be void. k = i < ? - i : i; // get absolute value of i

public class TernaryEx { public static void main(String[] args) { int A = 10 ; int B = 20 ; String result = A> B ? "A is greater" : "B is greater" ; System.out.println(result); } } For three variables: String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest“ ;

Operator Precedence

End of today session: Student can be able to apply operators in java programs RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 5 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

Previous Class

T o d a y ’ s Agenda Java conditions enum

Java’s Selection Statements if if- else if- else- if ladder nested if switch RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

Java’s program control statements can be put into the following categories: Selection Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). jump Jump statements allow your program to execute in a nonlinear fashion.

Control Statements The if Statement : The Java if statement tests the condition. It executes the if block if condition is true. if( condition) { // statement; } if(num < 100) System.out.println(“less than 100");

//Java Program to demonstrate the use of if statement. public class IfExample { public static void main(String[] args) { //defining an 'age' variable int age=20; //checking the age if (age>18){ System.out.print(“Eligible for voting"); } } }

if - else The Java if- else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. Syntax : if (condition){ //code if condition is true } else { //code if condition is false }

//It is a program of odd and even number. public class IfElseExample { public static void main(String[] args) { int number=13; //Check if the number is divisible by 2 or not if (number%2==0){ System.out.println("even number"); } else { System.out.println("odd number"); } } }

// A year is leap, if it is divisible by 4 and 400. But, not by 100. public class LeapYearEx { public static void main(String[] args) { int year=2020; if (((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)) { System.out.println("LEAP YEAR"); } else { System.out.println("COMMON YEAR"); } } }

if- else- if ladder The if- else- if ladder statement executes one condition from multiple statements. Syntax: if (condition1){ //code to be executed if condition1 is true } else if (condition2){ //code to be executed if condition2 is true } else if (condition3){ //code to be executed if condition3 is true } ... else { //code to be executed if all the conditions are false }

//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+. public class IfElseIfExample { public static void main(String[] args) { int marks=65; if (marks<35){ System.out.println("fail"); } else if (marks>=35 && marks<60){ System.out.println("D grade"); } else if (marks>=60 && marks<70){ System.out.println("C grade"); } else if (marks>=70 && marks<80){ System.out.println("B grade"); } else if (marks>=80 && marks<90){ System.out.println("A grade"); } else if (marks>=90 && marks<100){ System.out.println("A+ grade"); } else { System.out.println("Invalid!"); } } }

//Find out given no is +ve or –ve or zero public class PositiveNegativeExample { public static void main(String[] args) { int number=- 13; if (number>0){ System.out.println("POSITIVE"); } else if (number<0){ System.out.println("NEGATIVE"); } else { System.out.println("ZERO"); } } }

Nested if The nested if statement represents the if block within another if block . Here, the inner if block condition executes only when outer if block condition is true. Syntax: if (condition){ //code to be executed if (condition){ //code to be executed } }

//Java Program to demonstrate the use of Nested If Statement. public class JavaNestedIfExample { public static void main(String[] args) { int age=20; int weight=80; //applying condition on age and weight if (age>=18){ if (weight>50){ System.out.println("You are eligible to donate blood"); } else { System.out.println("You are not eligible to donate blood"); } } else { System.out.println("Age must be greater than 18"); } } }

Switch Statement The Java switch statement executes one statement from multiple conditions. It is like if- else- if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. There can be one or N number of case values for a switch expression. The case value must be of switch expression type only. The case value must be literal or constant . It doesn't allow variables . The case values must be unique . In case of duplicate value, it renders compile- time error. Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found , it executes the next case. The case value can have a default label which is optional.

switch (expression){ case value1: //code to be executed; break ; //optional case value2: //code to be executed; break ; //optional ...... default : code to be executed if all cases are not matched; }

public class SwitchExample { public static void main(String[] args) { int number=2; //Switch expression switch (number){ //Case statements case 1: System.out.println(“ONE"); break ; case 2: System.out.println(“TWO"); break ; case 3: System.out.println(“THREE"); break ; //Default case statement default :System.out.println("Not in 1, 2 or 3"); } } }

//Name of the month public class SwitchMonthExample { public static void main(String[] args) { //Specifying month number int month=7; String monthString=""; //Switch statement switch (month){ //case statements within the switch block case 1: monthString="1 - January"; break ; case 2: monthString="2 - February"; break ; case 3: monthString="3 - March"; break ; case 4: monthString="4 - April"; break ; case 5: monthString="5 - May"; break ; case 6: monthString="6 - June"; break ; case 7: monthString="7 - July"; break ; case 8: monthString="8 - August"; break ; case 9: monthString="9 - September"; break ; case 10: monthString="10 - October"; break ; case 11: monthString="11 - November"; break ; case 12: monthString="12 - December"; break ; default :System.out.println("Invalid Month!"); } //Printing month of the given number System.out.println(monthString); } }

switch w/o break It executes all statements after the first match, if a break statement is not present . //without break statement public class SwitchExample2 { public static void main(String[] args) { int num=2; //switch expression with int value switch (num){ //switch cases without break statements case 1: System.out.println(“1"); case 2: System.out.println(“2"); case 3: System.out.println(“3"); default :System.out.println("Not in 1, 2 or 3"); } } } Output : 2 3 Not in 1, 2 or 3

// In a switch, break statements are optional. class MissingBreak { public static void main(String args[]) { for(int i=0; i<12; i++) switch(i) { case 0: case 1: case 2: case 3: case 4: System.out.println("i is less than 5"); break; case 5: case 6: case 7: case 8: case 9: System.out.println("i is less than 10"); break; default: System.out.println("i is 10 or more"); } } } OUTPUT: i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is 10 or more i is 10 or more

Nested Switch Statement We can use switch statement inside other switch statement in Java. It is known as nested switch statement.

switch(expression1){ case value1: //code to be executed; break; case value2: switch(expression2){ case value21: //code to be executed; break; //optional case value22: break; //optional default: default code to be executed } break; default: code to be executed if all cases are not matched; }

Example: - You are searching for a department in a university and you’re asked to select a school from a choice of three schools namely: School of Arts School of Business School of Engineering Having selected a school you are again provided with a list of departments that fall under the department namely: School of Arts Department of finearts Department of sketcharts School of Business Department of Commerce Department of purchasing School of Engineering CSE ECE The initial choices for Computer Science, Business and Engineering schools would be inside as a set of switch statements. Then various departments would then be listed within inner switch statements beneath their respective schools.

import java.io.*; import java.util.Scanner; class NestedExample { public static void main(String args[]) { int a,b; System.out.println("1.School of Arts\n"); System.out.println("2.School of Business\n"); System.out.println("3.School of Engineering\n"); System.out.println("make your selection\n"); Scanner sobj = new Scanner(System.in); a=sobj.nextInt();

switch (a) { case 1: System.out.println("You chose Arts\n" ); case 2: break; System.out.println("You chose Business\n" ); case 3: // Engineering break; System.out.println("You chose Engineering\n" ); System.out.println("1.CSE\n" ); System.out.println("2.ECE\n" ); System.out.println("make your selection\n"); b=sobj.nextInt(); switch(b) { case 1: System.out.println("You chose CSE\n" ); break; case 2: System.out.println("You chose ECE" ); break; } break; } } }

enum in Switch Statement Java allows us to use enum in switch statement. An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters: enum Level { LOW , MEDIUM , HIGH } You can access enum constants with the dot syntax: Level myVar = Level.MEDIUM;

enum in Switch Statement public class JavaSwitchEnumExample { public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } public static void main(String args[]) { Day[] DayNow = Day.values(); for (Day Now : DayNow) { switch (Now) { case Sun: System.out.println("Sunday"); break ; case Mon: System.out.println("Monday"); break ; case Tue: System.out.println("Tuesday"); break ; case Wed: System.out.println("Wednesday"); break ; case Thu: System.out.println("Thursday"); break ; case Fri: System.out.println("Friday"); break ; case Sat: System.out.println("Saturday"); break ; } } } } Output: Sunday Monday Twesday Wednesday Thursday Friday Saturday

End of today session: Student can be able to write programs using java conditions RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 5 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

Previous Class

T o d a y ’ s Agenda Java Loops

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Iteration Statements Java’s iteration statements are for, while, and do- while. These statements are called loops. A loop repeatedly executes the same set of instructions until a termination condition is met.

while The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. while( condition) { // body of loop } The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

// Demonstrate the while loop. class While { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println(n); n- - ; } } } // The target of a loop can be empty. class NoBody { public static void main(String args[]) { int i, j; i = 100; j = 200; // find midpoint between i and j while(++i < -- j) ; // no body in this loop System.out.println("Midpoint is " + i); } }

do- while The do- while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is do { // body of loop } while ( condition); Each iteration of the do- while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.

// Demonstrate the do- while loop. class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println(n); n- - ; } while(n > 0); } } do { System.out.println("Help on:"); System.out.println(" 1. if"); System.out.println(" 2. switch"); System.out.println(" 3. while"); System.out.println(" 4. do- while"); System.out.println(" 5. for\n"); System.out.println("Choose one:"); choice = (char) System.in.read(); } while( choice < '1' || choice > '5'); System.in.read( ) is used to read characters from standard input.

for There are two forms of the for loop. The first is the traditional form of Java. for( initialization; condition; iteration) { // body } The second is the new “for-each” form. The for- each loop is essentially read- only. for(type itr- var : collection) { statement- block }

for Loop Variations for(int a=1, b=4; a<b; a++, b- - ) { } for(int i=1; !done; i++) { } // Parts of the for loop can be empty. class ForVar { public static void main(String args[]) { int i; boolean done = false; i = 0; for( ; !done; ) { System.out.println("i is " + i); if(i == 10) done = true; i++; } } } //infinite loop for( ; ; ) { // ... }

// Use a for-each style for loop. class ForEach { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use for-each style for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); } }

// Use for- each style for on a two- dimensional array. class ForEach3 { public static void main(String args[]) { int sum = 0; int nums[][] = new int[3][5]; // give nums some values for(int i = 0; i < 3; i++) for(int j=0; j < 5; j++) nums[i][j] = (i+1)*(j+1); // use for- each for to display and sum the values for(int x[] : nums) { for(int y : x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); } }

// Search an array using for-each style for. class Search { public static void main(String args[]) { int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; int val = 5; boolean found = false; // use for-each style for to search nums for val for(int x : nums) { if(x == val) { found = true; break; } } if(found) System.out.println("Value found!"); } }

Nested Loops Java allows loops to be nested. That is, one loop may be inside another. // Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } }

Try all types of printing pyramid programs.

Jump Statements Java supports three jump statements: break , continue , and return . These statements transfer control to another part of your program. Java supports one other way that you can change your program’s flow of execution: through exception handling . Exception handling provides a structured method by which run- time errors can be trapped and handled by your program. It is supported by the keywords try, catch, throw, throws, and finally.

Using break In Java, the break statement has three uses. First, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop . Third, it can be used as a “civilized” form of goto . break label; // Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }

// Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } } OUTPUT Before the break. This is after second block.

// This program contains an error. class BreakErr { public static void main(String args[]) { one: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); } for(int j=0; j<100; j++) { if(j == 10) break one; // WRONG System.out.print(j + " "); } } } Since the loop labeled one does not enclose the break statement, it is not possible to transfer control out of that block.

Using continue Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. In while and do- while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. As with the break statement, continue may specify a label to describe which enclosing loop to continue.

// Using continue with a label. class ContinueLabel { public static void main(String args[]) { outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j > i) { System.out.println(); continue outer; } System.out.print(" " + (i * j)); } } System.out.println(); } }

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL return The return statement is used to explicitly return from a method . That is, it causes program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it is executed.

// Demonstrate return. class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); } }

End of today session: Student can be able to write programs using java loops RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome

Java™: The Complete Reference UNIT – 1 & Chapter - 6 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

Previous Class

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabi Introducing Classes: Class Fundamentals, Declaring Objects, Assuming Object reference Variables, Introducing Methods, Constructors, The this Keyword, Garbage Collection, The Finalize() method, A Stack class.

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Class Fundamentals A class, defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object , and an object is an instance of a class . Because an object is an instance of a class, the two words object and instance used interchangeably.

The General Form of a Class A class is declared by use of the class keyword . Classes may contain only code or only data, most real- world classes contain both. class classname { type instance- variable1; type instance- variable2; // ... type instance- variableN; type methodname1(parameter- list) { // body of method } type methodname2(parameter- list) { // body of method } // ... type methodnameN(parameter- list) { // body of method } }

The General Form of a Class The data, or variables, defined within a class are called instance variables . The code is contained within methods . Collectively, the methods and variables defined within a class are called members of the class. Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.

A Simple Class a class declaration only creates a template; class Box { double width; double height; double depth; } Box mybox = new Box(); // create a Box object called mybox mybox will be an instance of Box. Thus, it will have “physical” reality. To access class variables, use the dot (.) operator . The dot operator links the name of the object with the name of an instance variable. mybox.width = 100; RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

/* A program that uses the Box class. Call this file BoxDemo.java */ class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }

Declaring Objects Obtaining objects of a class is a two- step process. First , you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Box mybox; // declare reference to object Second , you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator . mybox = new Box(); // allocate a Box object The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in the variable.

A Closer Look at new the new operator dynamically allocates memory for an object. class- var = new classname( ); class- var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. If no explicit constructor is specified, then Java will automatically supply a default constructor. A class is a logical construct. An object has physical reality.

Assigning Object Reference Variables Object reference variables act differently when an assignment takes place. Box b1 = new Box(); Box b2 = b1; Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object. When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.

Introducing Methods type name(parameter- list) { // body of method return value; } type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void . The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter- list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. value is the value returned.

Adding method Method With parameters Method Without Parameters Method Return a value The type of data returned by a method must be compatible with the return type specified by the method. The variable receiving the value returned by a method must also be compatible with the return type specified for the method.

Example

Constructors Automatic initialization of an object is performed through the use of a constructor. A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method . Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type , not even void. This is because the implicit return type of a class constructor is the class type itself. The constructor’s job to initialize the internal state of an object.

Constructors Constructors are Automatic Constructors Default Constructors Box mybox1 = new Box(); The default constructor automatically initializes all instance variables to zero. Parameterized Constructors Box mybox1 = new Box(10, 20, 15); Copy Constructors

class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } OUTPUT: Volume is 3000.0 Volume is 162.0 1. Default Constructors

class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } OUTPUT: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0 Parameterized Constructors

The this Keyword Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object . That is, this is always a reference to the object on which the method was invoked. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; }

Usage of java this keyword this can be used to refer current class instance variable . this can be used to invoke current class method (implicitly) this() can be used to invoke current class constructor. this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this can be used to return the current class instance from the method.

class Abc { int val; Abc() { System.out.println("Default Constructor Called"); } Abc(int x) { this(); val=x; System.out.println("Param Constructor " + this.val); } } class ThisEx { public static void main(String args[]){ Abc obj=new Abc(10); } }

Instance Variable Hiding It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. Local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. this , resolve any name space collisions that might occur between instance variables and local variables. Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }

Garbage Collection Since objects are dynamically allocated by using the new operator, how such objects are destroyed and their memory released for later reallocation? In some languages, such as C++ , dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation automatically . The technique that accomplishes this is called garbage collection . When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

Garbage Collection There is no explicit need to destroy objects. Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. Furthermore, different Java run- time implementations will take varying approaches to garbage collection. Do not to think about it while writing your programs.

System.gc

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL The finalize( ) Method Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non- Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization . By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the finalize() method.

protected void finalize( ) { // finalization code here } The keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. finalize( ) is only called just prior to garbage collection. It is not called when an object goes out- of- scope.

A Stack Class A stack stores data using first- in, last-out ordering. That is, a stack is like a stack of plates on a table— the first plate put down on the table is the last plate to be used. Stacks are controlled through two operations traditionally called push and pop . To put an item on top of the stack, you will use push. To take an item off the stack, you will use pop. As you will see, it is easy to encapsulate the entire stack mechanism.

// This class defines an integer stack that can hold 10 values. class Stack { int stck[] = new int[10]; int tos; // Initialize top-of- stack Stack() { tos = - 1; } // Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos-- ]; } }

class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); // push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); } } OUTPUT Stack in mystack1: 9 8 7 6 5 4 3 2 1 Stack in mystack2: 19 18 17 16 15 14 13 12 11 10

Java™: The Complete Reference UNIT – 1 & Chapter - 7 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Previous Class

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabus Overloading Methods, Using Object as Parameter, Argument Passing, Returning Objects, Recursion, Introducing Access control,

Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name , as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded , and the process is referred to as method overloading . Method overloading is one of the ways that Java supports polymorphism . When an overloaded method is invoked , Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types , the return type alone is insufficient to distinguish two versions of a method.

Method Overloading Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. Three ways to overload a method Number of parameters. add(int, int) add(int, int, int) Data type of parameters. add(int, int) add(int, float) Sequence of Data type of parameters. add(int, float) add(float, int) Invalid case of method overloading: int add(int, int) float add(int, int)

// Demonstrate method overloading. class OverloadDemo { void test () { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }

// Automatic type conversions apply to overloading . class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter void test(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } }

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Overloading Constructors Also overload constructor methods.

// Constructor Overloading class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = - 1; // use - 1 to indicate height = - 1; // an uninitialized depth = - 1; // box } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } OUTPUT Volume of mybox1 is 3000.0 Volume of mybox2 is - 1.0 Volume of mycube is 343.0

Using Objects as Parameters // Objects may be passed to methods. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(- 1, - 1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } } OUTPUT ob1 == ob2: true ob1 == ob3: false

class Box { double width; double height; double depth; // Notice this constructor. It takes an object of type Box. Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = - 1; // use - 1 to indicate height = - 1; // an uninitialized depth = - 1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } }

class OverloadCons2 { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); // create copy of mybox1 double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of cube is " + vol); // get volume of clone vol = myclone.volume(); System.out.println("Volume of clone is " + vol); } }

Argument Passing there are two ways that a computer language can pass an argument to a subroutine. call- by- value call- by- reference Java uses both approaches, depending upon what is passed. In Java, when you pass a primitive type to a method, it is passed by value. When you pass an object to a method, it is call- by- reference. When a primitive type is passed to a method, it is done by use of call- by- value. Objects are implicitly passed by use of call- by- reference.

// Objects are passed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { *= 2; /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } OUTPUT ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10

Returning Objects A method can return any type of data, including class types. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

// Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: "+ ob2.a); } } OUTPUT ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Recursion Java supports recursion. Recursion is the process of defining something in terms of itself. Recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.

// A simple example of recursion. class Factorial { // this is a recursive method int fact(int n) { int result; if(n==1) return 1; result = fact(n- 1) * n; return result; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } } OUTPUT Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120

Examples Given following three values, the task is to find the total number of maximum chocolates you can eat. money : Money you have to buy chocolates price : Price of a chocolate wrap : Number of wrappers to be returned for getting one extra chocolate. It may be assumed that all given values are positive integers and greater than 1. Examples: Input : money = 16, price = 2, wrap = 2 Output : 15 Price of a chocolate is 2. You can buy 8 chocolates from amount 16. You can return 8 wrappers back and get 4 more chocolates. Then you can return 4 wrappers and get 2 more chocolates. Finally you can return 2 wrappers to get 1 more chocolate. Input : money = 15, price = 1, wrap = 3 Output : 22 We buy and eat 15 chocolates We return 15 wrappers and get 5 more chocolates. We return 3 wrappers, get 1 chocolate and eat it (keep 2 wrappers). Now we have 3 wrappers. Return 3 and get 1 more chocolate. So total chocolates = 15 + 5 + 1 + 1 Input : money = 20, price = 3, wrap = 5 Output : 7

import java.io.*; class ChocolateWrapper { static int countRec(int choc, int wrap) { if (choc < wrap) return 0; int newChoc = choc / wrap; return newChoc + countRec(newChoc + choc%wrap, wrap); } public static void main (String[] args) { int money = 16; int price = 2; int wrap = 2; if(money>=1 && price>=1 && wrap>=1) { int totchoc = money/price; totchoc += countRec(totchoc, wrap); System.out.println(totchoc); } } }

Access Control How a member can be accessed is determined by the access specifier that modifies its declaration. Java supplies a rich set of access specifiers. Java’s access specifiers are public , private , and protected . Java also defines a default access level. protected applies only when inheritance is involved. public specifier, that member can be accessed by any other code. private, then that member can only be accessed by other members of its class. default, the member of a class is public within its own package, but cannot be accessed outside of its package.

class Test { int a; public int b; private int c; // default access // public access // private access // methods to access c // set c's value void setc(int i) { c = i; } int getc() { return c; } } class AccessTest { // get c's value public static void main(String args[]) { Test ob = new Test(); ob.a = 10; // These are OK, a and b may be accessed directly ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " + ob.getc()); } }

// This class defines an integer stack that can hold 10 values. class Stack { /* Now, both stck and tos are private. This means that they cannot be accidentally or maliciously altered in a way that would be harmful to the stack. */ private int stck[] = new int[10]; private int tos; // Initialize top- of- stack Stack() { tos = - 1; } // Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos- - ]; }} class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); // push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); // these statements are not legal // mystack1.tos = - 2; // mystack2.stck[3] = 100; } }

Java™: The Complete Reference UNIT – 1 & Chapter - 7 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Previous Class

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabus Understanding static, Introducing Nested and Inner classes, Exploring the String class, Using Command line Arguments, Varargs: variableLength Arguments.

static When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object . You can declare both methods and variables to be static. Example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables . When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable .

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. The static can be: Variable (also known as a class variable) Method (also known as a class method) Block Nested class

static variable If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects, for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading. Advantages of static variable: makes your program memory efficient . class Student{ int rollno; String name; String college=“RCEW"; } class Student{ int rollno; String name; static String college ="RCEW“; }

class Student{ int rollno; String name; static String college =“RCEW"; //constructor Student( int r, String n){ rollno = r; name = n; } //method to display the values void display (){ //instance variable //static variable System.out.println(rollno+" "+name+" "+college); } } public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //we can change the college of all objects by the single line of code //Student.college=“GPCET"; s1.display(); s2.display(); } }

College=RCEW

class Counter2{ static int count=0; //will get memory only once and retain its value Counter2(){ count++;//incrementing the value of static variable System.out.println(count); } public static void main(String args[]){ //creating objects Counter2 c1= new Counter2(); Counter2 c2= new Counter2(); Counter2 c3= new Counter2(); } } Output: 1 2 3

Static Method A static method belongs to the class rather than the object of a class. A static method can be invoked without the need for creating an instance of a class. A static method can access static data member and can change the value of it. They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. The static method cannot use non static data member or call non- static method directly. Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. classname.method( )

class Student{ int rollno; String name; static String college = "RCEW"; //static method to change the value of static variable static void change(){ college = “GPCET"; } //constructor to initialize the variable Student( int r, String n){ rollno = r; name = n; } //method to display values void display(){ System.out.println(rollno+" "+name+" "+college); } } public class TestStaticMethod{ public static void main(String args[]){ Student.change(); Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } } Output: 111 Karan GPCET 222 Aryan GPCET 333 Sonoo GPCET

class Calculate{ static int cube( int x){ return x*x*x; } public static void main(String args[]){ int result= Calculate.cube(5) ; System.out.println(result); } }

class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b ); } } OUTPUT a = 42 b = 99

Why is the Java main method static? It is because the object is not required to call a static method. If it were a non- static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL

static block Is used to initialize the static data member. It is executed before the main method at the time of classloading. class A2{ static { System.out.println("static block is invoked"); } public static void main(String args[]){ System.out.println("Hello main"); } } Output: static block is invoked Hello main

// Demonstrate static variables, methods, and blocks . class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } OUTPUT Static block initialized. x = 42 a = 3 b = 12 all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a * 4 or 12. Then main( ) is called, which calls meth(), passing 42 to x. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.

Can we execute a program without main() method? No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method. class A3{ static { System.out.println( "static block is invoked" ); System.exit( ); } } Output: static block is invoked

Nested Classes Java programming language allows us to create a class within a class. The nested class architecture is divided into two: nested classes that are declared static are called static nested classes nested classes that are non- static are called inner classes The main difference between these two is that the inner classes have access to all member of the enclosing class (including private), whereas the static nested classes only have access to static members of the outer class.

// Demonstrate an inner class . class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } OUTPUT display: outer_x = 100

// Demonstrate nested class . class TestOuter { static int data=30; static class Inner { void msg(){ System.out.println("data is "+data); } } public static void main(String args[]){ TestOuter.Inner obj= new TestOuter.Inner(); obj.msg(); } } OUTPUT data is 30

final The final keyword in java is used to restrict the user. The java final keyword can be used in many context. variable method class

final variable A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. It is a common coding convention to choose all uppercase identifiers for final variables . Variables declared as final do not occupy memory on a per- instance basis. Thus, a final variable is essentially a constant. A field that is both static and final has only one piece of storage that cannot be changed. The keyword final can also be applied to methods , and classes . A final variable that is not initialized at the time of declaration is known as blank final variable . We can initialize using constructors only. A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5; class A{ static final int data;//static blank final variable static { data=50;} public static void main(String args[]){ System.out.println(A.data); } }

final variable If you declare any parameter as final, you cannot change the value of it. class Bike11{ int cube( final int n ){ n=n+2; //can't be changed as n is final n*n*n; } public static void main(String args[]){ Bike11 b= new Bike11(); b.cube(5); } } Can we declare a constructor final? No, because constructor is never inherited.

class finalvar{ final int x=90; void run(){ x=400; } //final variable public static void main(String args[]) { finalvar obj= new finalvar(); obj.run(); } }//end of class Output: Compile Time Error

final method If you make any method as final, you cannot override it. Is final method inherited? Yes, final method is inherited but you cannot override it. class Bike{ final void run(){ System.out.println("running"); } } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error

final class If you make any class as final, you cannot extend it. final class Bike{ void run(){ System.out.println("running"); } } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error

String Class The first thing, strings are actually an object of type String. Even string constants are actually String objects. Example System.out.println("This is a String, too"); objects of type String are immutable ; once a String object is created, its contents cannot be altered. If you need to change a string, you can always create a new one that contains the modifications. Java defines a peer class of String, called StringBuffer , which allows strings to be altered. • + is used to concatenate two strings. Test two strings for equality by using equals( ). length of a string by calling the length( ) method . character at a specified index within a string by calling charAt( ).

// Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length ()); System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3 )); if(strOb1.equals(strOb2 )) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } } OUTPUT Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3

command line arguments Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command- line arguments to main( ). A command- line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command- line arguments inside a Java program, they are stored as strings in a String array passed to the args parameter of main( ). The first command- line argument is stored at args[0] , the second at args[1] , and so on. All command- line arguments are passed as strings .

command line arguments public class CommandLine { public static void main(String args[]) { for(int i = 0; i<args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } } d:/mahesh>javac CommandLine.java d:/mahesh>java CommandLine this is a command line 200 - 100 Output args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: - 100

Varargs: Variable- Length Arguments JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments . This feature is called varargs and it is short for variable- length arguments . A method that takes a variable number of arguments is called a variable- arity method , or simply a varargs method. example is the printf( ) Prior to JDK 5, variable- length arguments could be handled two ways, if the maximum number of arguments was small and known , then you could create overloaded versions of the method, one for each way the method could be called. In cases where the maximum number of potential arguments was larger , or unknowable , a second approach was used in which the arguments were put into an array, and then the array was passed to the method.

class PassArray { static void vaTest(int v[]) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Notice how an array must be created to hold the arguments. int n1[] = { 10 }; int n2[] = { 1, 2, 3 }; int n3[] = { }; vaTest(n1); // 1 arg vaTest(n2); // 3 args vaTest(n3); // no args } } OUTPUT Number of args: 1 Contents: 10 Number of args: 3 Contents: 1 2 3 Number of args: Contents: it is tedious to construct an array each time vaTest( ) is called, it is potentially error- prone.

varags A variable- length argument is specified by three periods ( ...). For example, here is how vaTest( ) is written using a vararg: static void vaTest(int ... v) { } This syntax tells the compiler that vaTest( ) can be called with zero or more arguments . As a result, v is implicitly declared as an array of type int[ ] . Thus, inside vaTest( ), v is accessed using the normal array syntax. The ... syntax simply tells the compiler that a variable number of arguments will be used.

// Demonstrate variable- length arguments. class VarArgs { // vaTest() now uses a vararg. static void vaTest(int ... v) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Notice how vaTest() can be called with a variable number of arguments. } vaTest(10); vaTest(1, 2, 3); vaTest(); // 1 arg // 3 args // no args }

Valid statement int doIt(int a, int b, double c, int ... vals) {} declare a regular parameter after the varargs parameter is invalid. int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error! declare the second varargs parameter is illegal. int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Overloading Vararg Methods You can overload a method that takes a variable- length argument.

// Varargs and overloading. class VarArgs3 { static void vaTest(int ... v) { System.out.print("vaTest(int ...): " +"Number of args: " + v.length +" Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } static void vaTest(boolean ... v) { System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: "); for(boolean x : v) System.out.print(x + " "); System.out.println(); } static void vaTest(String msg, int ... v) { System.out.print("vaTest(String, int ...): " +msg + v.length +" Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest(1, 2, 3); vaTest("Testing: ", 10, 20); vaTest(true, false, false); } } OUTPUT vaTest(int ...): Number of args: 3 Contents: 1 2 3 vaTest(String, int ...): Testing: 2 Contents: 10 20 vaTest(boolean ...) Number of args: 3 Contents: true false false

RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Varargs and Ambiguity Somewhat unexpected errors can result when overloading a method that takes a variable- length argument. These errors involve ambiguity because it is possible to create an ambiguous call to an overloaded varargs method.

// Varargs, overloading, and ambiguity. // This program contains an error and will not compile! class VarArgs4 { static void vaTest(int ... v) { System.out.print("vaTest(int ...): " +"Number of args: " + v.length +" Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } static void vaTest(boolean ... v) { System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: "); for(boolean x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest(1, 2, 3); // OK vaTest(true, false, false); // OK vaTest(); // Error: Ambiguous! } }

static void vaTest(int ... v) { // ... static void vaTest(int n, int ... v) { // ... Although the parameter lists of vaTest( ) differ, there is no way for the compiler to resolve the following call: vaTest(1) Does this translate into a call to vaTest(int ...), with one varargs argument, or into a call to vaTest(int, int ...) with no varargs arguments? There is no way for the compiler to answer this question. Thus, the situation is ambiguous. Because of ambiguity errors like those just shown, sometimes you will need to forego overloading and simply use two different method names . Also, in some cases, ambiguity errors expose a conceptual flaw in your code, which you can remedy by more carefully crafting a solution.
Tags