Download
slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Core Java Notes PowerPoint Presentation
Download Presentation
Core Java Notes

Core Java Notes

144 Vues Download Presentation
Télécharger la présentation

Core Java Notes

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. CORE JAVA NOTES Prepared By Kumar Kishan Chandra

  2. JAVA FUNDAMENTALS • History • JDK and JRE • Byte Code and JVM (Java Virtual Machine) • Platform Independent • Applications and Applets • Principle of OOPs • First Java Application

  3. History of Java Java is a General Purpose, Object Oriented Programming Language developed by Sun Microsystems of USA I 1991. Originally called Oak by Games Gosling, one of the invention of the language, java was designed for the development of software for consumer electronic devices like TVs, VCRs, toasters and such other electronic Machines.This goal had a strong impact on the development team to make the language simple, portable and highly reliable. The java team which included Patrick Naughton discovered that the existing languages like C and C++ had limitations in terms of both reliability and portability. However, they modeled their new language Java on C and C++ but removed a number of features of of C and C++ that were considered as source of problems and thus made java really simple, reliable,portable and powerful language.

  4. Java Milestones : 1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer electronic devices. A team of Sun Microsystems programmers headed by James Gosling was formed to undertake this task. 1991 After exploring the possibility of most Object Oriented Programming Language C++, the team announced a new language named “Oak”. 1992 The team, known as a Green Project team by Sun, demonstrated the application of their new language to control a list of home appliances using a hand-held device with a tiny touch sensitive screen. 1993 The World Wide Web(WWW) appeared on the internet and transformed the text-based Internet into a Graphical-rich environment. The green Project team came up with the idea of developing Web Applets(tiny programs) using the new language that could run on all types of computers connected to Internet. 1994 The team developed a web browser called “Hot Java” to locate and run applet programs on Internet. Hot Java demonstrated the power of the new language, thus making it instantly popular among the Internet users. 1995 Oak was named “Java”, due to some legal snags. Java is just a name and is not an acronym. Many popular companies including Netscape and Microsoft announce to their support to Java.

  5. 1996 Java established itself not only a leader for Internet Programming but also as • a general-purpose, object oriented programming language. Java found its • home. • The most striking feature of the language is that it is a platform-neutral language. Java is a first programming language that is not tied to any particular hardware or operating system. • Features of Java : • Compiled and Interpreted. • Platform-Independent and Portable • Object-Oriented • Robust and Secure • Distributed • Familiar, Simple and Small • Multithreaded and Interactive • High Performance • Dynamic and Extensible

  6. JDK & JRE Java Environment includes a large number of development tools and hundreds of classes and methods. The development tools are part of the system known as Java Development Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also known as the Application Programming Interface (API). JDK : Java Development Kit comes with a collection of tools that are used for developing and running Java Programs. They include : appletviewer-> Enables us to run Java Applets (Without using java compatible browser) Java Java Interpreter, which runs applets and applications by reading and interpreting bytecode files. JavacThe Java compiler, which translates Java source code to byte code files that the interpreter understad. Javadoc Creates HTML-format documentation from Java source code files. Javah Produces header files for use with native methods. javap Java disassembler, which enables us to convert bytecode files into a program description. Jdb Java debugger, which helps us to find errors in our programs.

  7. Byte Code & JVM(Java Virtual Machine) Since platform-independence is a defining characteristic of Java, it is important to understand how it is achieved. Programs exist in two forms; source code and object code. Source Code is the textual version of the program that you write using a text editor. The programs printed in a book are shown as source code. The executable form of a program is object code. The computer can execute object code. Typically, object code is specific to a particular CPU. Therefore, it cannot be executed on a different platform. Java removes this feature in a very elegant manner. Like all computer languages, a java program begins with its source code. The difference is what happens when a Java program is compiled. Instead of producing executable code, the Java Compiler produces an object file that contains bytecode. Bytecodes are instructions that are not for any specific CPU. Instead, they are designed to be interpreted by a Java Virtual Machine (JVM). The key to Java’s platform-independence comes from the fact that the same bytecodes can be executed by any JVM on any platform. As long as there is a JVM implemented for a a given environment, it can run any Java program. For example, Java programs can execute under Windows 98,Solaris,IRIX, or any other platform for which a JVM can be implemented for that platform. This would then allow any Java program to execute in that new environment.

  8. Platform Independent Compilation is the process of converting the code that you type into a language that the computer understands-machine language. When you compile a program, the compiler checks for syntactical errors in code and lists all the errors on the screen. You have to rectify the errors and recompile the program to get the machine language code. The Java compiler compiles the code to bytecode that is understood by the Java environment. The bytecode is the result of compiling a Java program. You can execute this code on any platform. In other words, due to the bytecode compilation process and interpretation by a browser, Java programs can be executed on a variety of hardware and operating systems. The only requirement is that the system should have a java-enabled Internet browser.The java compiler is written in Java, and the interpreter is written in C. The Java Interpreter can execute Java Code directly on any machine on which a Java interpreter has been installed.

  9. Application and Applets There are two types of programs that can be built in Java Applications and applets. Applications can be directly executed by a JVM. In fact, Java can be used to develop programs for all kinds of applications, Hot Java itself is a Java Application program. Applets are small Java programs developed for Internet Applications. An applet located on distant computer (Server) can be downloaded via Internet and executed on a local computer (Client) using a Java enabled browser. We can develop applets for doing everything from simple animated graphics to complex games and utilities. Since applets are embedded in an HTML document and run inside a Web Page, creating and running applets are more complex than creating application. Stand alone program can read and write files and perform certain operations that applet can not do. An Applet can only run within a Web Browser. The Web browser includes a JVM that provides an execution environment for the applet. It is also possible to use a tool called the appletviewer to run an applet. This utility is included in the Java Development Kit(JDK) and is used to test applets. In this manner, an applet written by any developer in the world may be dynamically downloaded from the Web Server and executed on a client PC or workstation.

  10. Java Program Java Compiler Virtual Machine Source Code Bytecode Process of Compilation Bytecode Java Interpreter Machine Code Virtual Machine Real Machine Process of Converting bytecode into machine code

  11. Java Source Code Java Compiler Application Type Applet Type Java Enabled Browser Java Interpreter Output Output

  12. Principal of OOPs Object Oriented Programming (OOP) attempts to emulate the real world in software systems. The real world consists of objects, categorized in classes. In Object Oriented Programming, classes have attributes, represented by data member. The attributes distinguish an object of the class. Classes have behaviors, which are represented by methods. The methods define how an object acts or reacts. Feature of Object Oriented Programming : Information Encapsulation(Hiding) :- Objects provide the benefit of information hiding. Electrical writing in a television should not be tempered with, and therefore should be hidden from the user. Object Oriented programming allows you to encapsulate data that you do not want users of the object to access. Typically, attributes of a class are encapsulated. Abstraction :- Abstraction allows us to focus on only those parts of an object that concern us. Person operating the television does not need to know the intricacies of how it works. The person just needs to know how to switch it on, change channels, and adjust the volume.All the details that are unnecessary to users are encapsulated, leaving only a simple interface to interact with. Providing users with only what they need to know is known as abstraction. i.e. Abstraction lets us ignore the irrelevant details and concentrate on the essentials.

  13. Inheritance :- Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. Polymorphism :-.Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object Note:- Java is not oops  because it supports Primitive such as int, byte, long... etc, to be used, which are not objects.

  14. First Java Application Create the File The first step to create the HelloWorld application is to copy the text from listing 7.1 into a file called HelloWorld.java using your favorite text editor (by choosing Windows, NotePad, or SimpleText on the Macintosh). It is very important to call the file HelloWorld.java, because the compiler expects the file name to match the class identifier Listing 7.1 The HelloWorld application. public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World!!"); } }

  15. Class Declaration The first line public class HelloWorld declares a class, which is an Object-Oriented construct. As stated earlier Java is true Object-Oriented language and therefore, everything must be placed inside a class. Class is a keyword and declares that a new class definition follows. Opening Bace Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”, appearing in the last line in the example. The main() method Every java application program must include the main() method. This is starting point for the interpreter to begin the execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate the execution. Public : The Keyword public is an access specifier that declares the main method as unprotected and therefore making it to accessible to all other classes. Static : The keyword static which declares this method as one that belongs to the entire Class and not a part of any Objects of the class.

  16. The main must always be declared be declared as static since the interpreter uses this method before any objects are created. Void : The type modifier void states that the main method does not return any value. All parameters to a method are declared inside a pair of parentheses. Here, String args[] declares a parameter named args, which contains an array of objects Of the class type String. The Output Line The only executable Statement in the program is System.out.println("Hello World!!"); Since Java is a true Object Oriented Language, every method must be part of an Object. The println method is a member of the out Object, which is static data Member of the System class. This line prints Hello World!! to the screen. The method println always appends a newline character to the end of the string.

  17. Compile the Code To compile the program, you need to first install the JDK. Then, use the program javac included with the JDK to convert the text in listing 7.1 to code which the computer can run. To run javac, on a Macintosh drag the source file over the javac icon. On any other computer, type the line: javac HelloWorld.java at a command prompt. The javac program creates a file called HelloWorld.class from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as bytecodes which can be run by the Java interpreter. Run the Program Now that you have compiled the program, you can run it by typing at the command prompt: java HelloWorld After you do this, the computer should print to the screen Hello World!! That may not seem very interesting, but then it's a simple program. If you don't see the Hello World!! on the screen, go back and make sure you have typed in the file exactly as shown in listing 7.1, and make sure that you called the file HelloWorld.java.

  18. JAVA CONTROLS • Variables and Constants • Arithmetic Operator and Expressions • Type Conversion in Java • Comments in Java(3 Types) • Java’s Control Statements • If • If-else • Do-while • While • for • Increment and Decrement Operators • Escape Sequences Characters • Relational and Logical Operators • Ternary Operators • Switch case • Break • Bitwise Operators • Arrays-Single and Multidimensional

  19. Java Constant Numeric Constant Character Constant Integer Real Character String Variables and Constants Constants : Constants in Java refer to fixed values that do not change during the execution of a program. Java supports several types of constants given in figure below : Integer Constants : Refers to a sequence of digits. There are three types of Integers, namely, decimal,octal and hexadecimal integer. Decimal Integer consist of of a set of digits, 0 through 9, preceded by an optional minus sign. An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading 0. A sequence of digits preceded by ox or OX is considered as hexadecimal integer. They may also include alphabets A through F.

  20. Real Constants : Integer constant are inadequate to represent quantities that vary continuously, such as distance, heights, temperature, prices and so on. These quantities are represented by numbers containing fractional parts like 17.546. Such numbers are called real. The real number may also be expressed in exponential (or scientific ) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 102. The general form is : mantissa e exponent mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase. Since the exponent causes the decimal point to “float”, this notation is said to represent a real number in floating point form.

  21. Single Character Constants : A single character constant (or simply character constant ) contains a single character enclosed within a pair of single quote marks. Examples of character constants are : ‘5’ ‘X’ ‘;’ String Constant : A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets,digits,special characters and blank spaces. Example are : “Hello Java” “1997” • Variable : A variable is an Identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of program. Examples of variables : average,height,total_height. • Variable name may consist of alphabets,digits,the underscore(_) and dollor characters. • Rules to write Variable/Identifier in Java : • They must not begin with digit • Upper and lowecase are distinct. This means that the variable Total is not the sam as total or TOTAL. • It should not be a keyword. • White space is not allowed. • Variable names can be of any length.

  22. Data Types in Java Primitive (Intrinsic) Non-Primitive ( Derived) Numeric Non-Numeric Classes Arrays Interface Floating Point Integer Character Boolean Data Types Integer Types Java consists of four integer types: byte, short, int, and long, which are defined as 8-, 16-, 32-, and 64-bit signed values as summarized in Table below :

  23. The Java integer primitive types. Integer literals can be specified in decimal, hexadecimal, or octal notation. To specify a decimal value, simply use the number as normal. To indicate that a literal value is a long, you can append either "L" or "l" to the end of the number. Hexadecimal values are given in base 16 and include the digits 0-9 and the letters A-F. To specify a hexadecimal value, use 0x followed by the digits and letters that comprise the value. Similarly, an octal value is identified by a leading 0 symbol. For examples of specifying integer literals, see Table 3.7.

  24. Table 3.7. Examples of integer literals. Floating-Point Types Support for floating-point numbers in Java is provided through two primitive types-float and double, which are 32- and 64-bit values, respectively. Similar to integer literals are Java's floating-point literals. Floating-point literals can be specified in either the familiar decimal notation (for example, 3.1415) or exponential notation (for example, 6.02e23). To indicate that a literal is to be treated as a single precision float, append either "f" or "F". To indicate that

  25. it is to be treated as a double precision value, append either "d" or "D". Java includes predefined constants, POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN, to represent the infinity and not-a-number values. The following list shows some valid floating-point literals: 43.3F,3.1415d,-12.123f,6.02e+23f,6.02e23d,6.02e-23f,6.02e23d Boolean :- Java supports two Boolean literals-true and false. Character Literals :-A character literal is a single character or an escape sequence enclosed in single quotes, for example, 'b'. Escape sequences are used to indicate special characters or actions, such as line feed, form feed, or carriage return. The available escape sequences ar shown in Table 3.8. String Literals Although there is no string primitive type in Java, you can include string literals in your programs. Most applications and applets will make use of some form of string literal, probably at least for error messages. A string literal consists of zero or more characters (including the escape sequences shown in Table 3.8) enclosed in double quotes. As examples of string literals, consider the following: "A String“,"Column 1\tColumn 2”

  26. Table 3.8. Escape sequences.

  27. Arithmetic Operators and Expressions An expression is a operators and operands. It follows the rules of algebra and should be familiar. Java allows several types of expressions. The arithmetic operators are given below : + addition -subtraction *multiplication / division % modulus += addition assignment -=subtraction assignment *=multiplication assignment /=division assignment %=modulus assignment ++increment,--decrement

  28. An expression may appear on the right side of an assignment statement. For example, Int answer; Answer=100*31; Java expression may contain Variables, constants or both. For example assuming that answer and count are variables, this expression is perfectly valid. Answer=count-100;

  29. Increment/Decrement Operators The increment and decrement operators are used with one variable (they are known as unary operators): ++ increment operator -- decrement operator For instance, the increment operator (++) adds one to the operand, as shown in the next line of code: x++; is the same as x+=1; The increment and decrement operators behave slightly differently based on the side of the operand they are placed on. If the operand is placed before the operator (for example, ++x), the increment occurs before the value is taken for the expression. So, in the following code fragment, the result of y is 6: int x=5;int y=++x; // y=6 x=6 If the operator appears after the operand, the addition occurs after the value is taken. So y is 5 as shown in the next code fragment. Notice that in both examples, x is 6 at the end of the fragment. int x=5;int y = x++; //y=5 x=6 Similarly, the decrement operator (--) subtracts one from the operand, and the timing of this is in relation to the evaluation of the expression that it occurs in.

  30. The Relational Operators The most intuitive comparative operators are those that fall into a category known as relational operators. Relational operators include those standard greater-than and less-than symbols you learned about back in third grade. Conveniently enough, they work the same way as they did back in third grade, too. For instance, you know that if you write (3>4), you wrote something wrong (false). On the other hand (3<4) is correct (true). In Java and most other languages, you are not limited to evaluating constants; you are free to use variables, so the statement (Democrats> Republicans) is also valid. The complete list of relational operators is shown here: Operator Boolean Result < Less than <= Less than or equal to > Greater than >= Greater than or equal to The following two assignment statements produce identical results: result1 = a+b < c*d ; result2 = (a+b) < (c*d) ; Logical Expressions The third set of evaluation operators fall into a category known as logical expressions. Logical expressions work a bit differently than the previous operators, and are probably not something you covered in your third grade math class.

  31. Logical expressions operate either on a pair of booleans, or on the individual bits of an object. There are two types of logical operators which are divided roughly along these lines: • Boolean operators. Only operate on Boolean values. • Bitwise operators. Operate on each bit in a pair of integral operands. • The Conditional-And and Conditional-Or Operators • There are two primary Boolean operators: • Logical-AND: && • Logical-OR: || • Oddly, in most computer languages, including Java, there is no Conditional-XOR operator.

  32. The Conditional Operator The conditional operator is the one ternary or triadic operator in Java, and operates as it does in C and C++. It takes the following form: expression1 ? expression2 : expression3 In this syntax, expression1 must produce a Boolean value. If this value is true, then expression2 is evaluated, and its result is the value of the conditional. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. Consider the following examples. The first is using the conditional operator to determine the maximum of two values; the second is determining the minimum of two values; the third is determining the absolute value of a quantity: BestReturn = Stocks > Bonds ? Stocks : Bonds ; LowSales = JuneSales < JulySales ? JuneSales : JulySales ; Distance = Site1-Site2 > 0 ? Site1-Site2 : Site2 - Site1 ; In reviewing these examples, think about the precedence rules, and convince yourself that none of the three examples requires any brackets in order to be evaluated correctly.

  33. Type Conversion in Java Implicit Type Conversions Java performs a number of implicit type conversions when evaluating expressions. For unary operators (such as ++ or --), the situation is very simple: operands of type byte or short are converted to int, and all other types are left as-is. For binary operators, the situation is only slightly more complex. For operations involving only integer operands, if either of the operands is long, then the other is also converted to long; otherwise, both operands are converted to int. The result of the expression is an int, unless the value produced is so large that a long is required. For operations involving at least one floating point operand, if either of the operands is double, then the other is also converted to double and the result of the expression is also a double; otherwise, both operands are converted to float, and the result of the expression is also a float. Fortunately, implicit conversions take place almost always without your wanting or needing to know. The compiler handles all the details of adding bytes and ints together so you don't have to. short Width; long Length, Area; Area = Length * Width;// In the division below, Area will be converted to a double,// and the result of the calculation will be a double.

  34. Conversions and the Cast Operator : Normally with implicit conversion, the conversion is so natural that you don't even notice. Sometimes though it is important to make sure a conversion occurs between two types. Doing this type of conversion requires an explicit cast, by using the cast operator. The cast operator consists of a type name within round brackets. It is a unary operator with high precedence and comes before its operand, the result of which is a variable of the type specified by the cast, but which has the value of the original object. The following example shows an example of an explicit cast: float x = 2.0; float y = 1.7; x - ( (int)(x/y) * y) When x is divided by y in this example, the type of the result is a floating-point number. However, value of x/y is explicitly converted to type int by the cast operator, resulting in a 1, not 1.2. So the end result of this equation is that x equals 1.7. Not all conversions are legal. For instance, boolean values cannot be cast to any other type, and objects can only be converted to a parent class. Casting and Converting Integers The four integer types can be cast to any other type except boolean. However, casting into a smaller type can result in a loss of data, and a cast to a floating-point number (float or double) will probably result in the loss of some precision, unless the integer is a whole power of two (for example, 1, 2, 4, 8...).

  35. Casting and Converting Characters Characters can be cast in the same way 16-bit (short) integers are cast; that is, you can cast it to be anything. But, if you cast into a smaller type (byte), you lose some data. In fact, even if you convert between a character and a short you an loose some data. If you are using the Han character set (Chinese, Japanese, or Korean), you can lose data by casting a char into a short (16-bit integer), because the top bit will be lost. Casting and Converting Booleans There are not any direct ways to cast or convert a Boolean to any other type. However, if you are intent on getting an integer to have a 0 or 1 value based on the current value of a Boolean, use an if-else statement, or imitate the following code: int j;boolean tf;...j = tf?1:0; // integer j gets 1 if tf is true, and 0 otherwise. Conversion the other way can be done with zero to be equal to false, and anything else equal to true as follows: int j;boolean tf;...tf = (j!=0); // Boolean tf is true if j is not 0, false otherwise.

  36. Comments in Java Java supports three types of comment delimiters-the traditional /* and */ of C, the // of C++, and a new variant that starts with /** and ends with */. The /* and */ delimiters are used to enclose text that is to be treated as a comment by the compiler. These delimiters are useful when you want to designate a lengthy piece of code as a comment, as shown in the following: /* This is a comment that will span multiple source code lines. */ The // comment delimiter is borrowed from C++ and is used to indicate that the rest of the line is to be treated as a comment by the Java compiler. This type of comment delimiter is particularly useful for adding comments adjacent to lines of code, as shown in the following: Date today = new Date();      // create an object with today's date System.out.println(today);    // display the date Finally, the /** and */ delimiters are new to Java and are used to indicate that the enclosed text is to be treated as a comment by the compiler, but that the text is also part of the automatic class documentation that can be generated using JavaDoc

  37. The Java comment delimiters are summarized in Table 3.1. Table 3.1. Java comment delimiters.

  38. Control Statement Selection Statement Iteration Statement Jump Statement continue return If-else switch break while do for Java Control Statements if

  39. Selection Statement : These select one of several control flows. There are three types of selection statement in Java : if,if-else, and switch. If statement : The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is a two-way decision statement and is used in conjunction with an expression. The general form is : If(test expression) { Statement-block; } Statement-x; It allows the computer to evaluate the expression first and then, depending on whether the value of the expression (relation or condition) is ‘true’ or ‘false’. It transfers the control to a particular statement. If the statement is true then the Statement block will be executed;otherwise the statement-block will be skipped and the execution will jump to the statement-x. It should be remember that when the condition is true both the statement-block and statement-x are executed in sequence.

  40. Example : Class Demo { public static void main(String args[]) { If(args.length==0) System.out.println(“You must have command line arguments”); }} If-else statement if(test expression) { True-Block Statement(s); } Else { False-Block statement(s); } Statement-x;

  41. If the test expression is true, then the true-block statement(s) executed immediately following to the if statement, are executed; otherwise the false statement(s) will be executed, not both.In both the cases, the control is transferred subsequently to the statement-x. Nesting of If—else Statement If(test condition1) { if(test condition2) { Statement-1; } else { Statement-2; } } else { Statement-3; } Statement-x; If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be evaluated;otherwise statement-2 will be evaluated and then control is transferred to the statement-x.

  42. Switch Statement: The Java switch statement is ideal for testing a single expression against a series of possible values and executing the code associated with the matching case statement. Switch(expression) { Case value-1: block-1; break; Case value-2: block-2; break; …… …… default: default-block; break; } Statement-x;

  43. Iteration Statement : These specify how and when looping will take place. There are three types of Iteration statements: while, do and for The for Statement The first line of a for loop enables you to specify a starting value for a loop counter, specify the test condition that will exit the loop, and indicate how the loop counter should be incremented after each pass through the loop. This is definitely a statement that offers a lot of bang for the buck. The syntax of a Java for statement is as follows: for (initialization; testExpression; incremement)    statement For example, a sample for loop may appear as follows: int count;for (count=0; count<100; count++)    System.out.println("Count = " + count); In this example, the initialization statement of the for loop sets count to 0. The test expression, count < 100, indicates that the loop should continue as long as count is less than 100. Finally, the increment statement increments the value of count by one. As long as the test expression is true, the statement following the for loop setup will be executed, as follows: System.out.println("Count = " + count); Of course, you probably need to do more than one thing inside the loop. This is as easy to do as using curly braces to indicate the scope of the for loop.

  44. The while Statement Related to the for loop is the while loop. The syntax for a while loop is as follows: while (booleanExpression)    statement As you can tell from the simplicity of this, the Java while loop does not have the built-in support for initializing and incrementing variables that its for loop does. Because of this, you need to be careful to initialize loop counters prior to the loop and increment them within the body of the while loop. For example, the following code fragment will display a message five times: int count = 0;while (count < 5) {    System.out.println("Count = " + count);    count++;} The do…while Statement The final looping construct in Java is the do…while loop. The syntax for a do…while loop is as follows: do {    statement} while (booleanExpression);

  45. This is similar to a while loop except that a do…while loop is guaranteed to execute at least once. It is possible that a while loop may not execute at all depending on the test expression used in the loop. For example, consider the following method: public void ShowYears(int year) {    while (year < 2000) {        System.out.println("Year is " + year);        year++;    }} This method is passed a year value, then loops over the year displaying a message as long as the year is less than 2000. If year starts at 1996, then messages will be displayed for the years 1996, 1997, 1998, and 1999. However, what happens if year starts at 2010? Because the initial test, year < 2000, will be false, the while loop will never be entered. Fortunately, a do…while loop can solve this problem. Because a do…while loop performs its expression testing after the body of the loop has executed for each pass, it will always be executed at least once. This is a very valid distinction between the two types of loop, but it can also be a source of potential errors. Whenever you use a do…while loop, you should be careful to consider the first pass through the body of the loop.

  46. Jumping Of course, it is not always easy to write all of your for, while and do…while loops so that they are easy to read and yet the loops terminate on exactly the right pass through the loop. Java makes it easier to jump out of loops and to control other areas of program flow with its break and continue statements. The break Statement Earlier in this chapter, you saw how the break statement is used to exit a switch statement. In a similar manner, break can be used to exit a loop As an example of this, consider the following code: int year = 1909;while (DidCubsWinTheWorldSeries(year) == false) {    System.out.println("Didn't win in " + year);    if (year >= 3000) {        System.out.println("Time to give up. Go White Sox!");        break;    }}System.out.println("Loop exited on year " + year);

  47. This example shows a while loop that will continue to execute until it finds a year that the Chicago Cubs won the World Series. Because they haven't won since 1908 and the loop counter year starts with 1909, it has a lot of looping to do. For each year they didn't win, a message is displayed. However, even die-hard Cubs fans will eventually give up and change allegiances to the Chicago White Sox. In this example, if the year is 3000 or later, a message is displayed and then a break is encountered. The break statement will cause program control to move to the first statement after the end of the while loop. In this case, that will be the following line: System.out.println("Loop exited on year " + year); The continue Statement Just as a break statement can be used to move program control to immediately after the end of a loop, the continue statement can be used to force program control back to the top of a loop

  48. ARRAYS • One Dimensional Array : is a list of variables of the same type that are accessed through a common name. An Individual variable in the array is called an array element. Arrays from a convenient way to handle groups of related data. • To create an array, you need to perform two steps : • Declare Array • 2. Allocate space for its elements. • General Form for declaring one dimensional array given below : • type varName[]; • Here, type is a valid Java data type and varName is the name of the array. Like int a[]; • This creates a variable named a that refers to an integer array. But it does not actually create storage for the array. • Second approach to allocate space for One Dimensional Array is

  49. varName=new type[size]; Here varName is name of the array, type is a valid Java type, and size specifies the number of elements in the array. You can see that the new operator is used to allocate memory for the array. These two steps combines like type varName=new type[size]; For example consider this declaration and allocation : Int ia=new int[10]; Represents the structure of a one-dimensional array,here ia is array variable name that can hold 10 integer values. Multidimensional Array : In addition to one dimensional we can create arrays of two or more dimensions. In Java, Multidimensional array are implemented as arrays of arrays. You need to perform two steps to work with multidimensional arrays : 1. Declare the array and 2. allocate space for its elements.

  50. The General form is given below : Type varname = new type[size1][size2]; float a[][]=new float[2][2]; Here a is two dimensional array having 2 rows and 2 columns. i.e. size is 4, we can store 4 elements in that array.