Introduction to JAVA – Unit1 SVIT,Bangalore Introduction ... Science (ISE)/Sem...

52
Introduction to JAVA – Unit1 SVIT,Bangalore Sreelatha . P.K Asst. Prof, CSE Dept. Page 1 UNIT -1 Introduction to JAVA Java is a general-purpose, object-oriented programming language. It is a blend of C & C++. It was developed by Sun Microsystems of USA by a team headed by James Gosling in the year 1991. It was first named as ‘Oak’. It was primarily developed to be a portable, platform-independent language, means that the programs built in java can be executed in any platform and under different environments. So that it can be embedded in various electronic devices, such as microwave ovens, remote control etc. C and C++ languages have problems in terms of reliability and portability. So the language java was formed, by removing the sources of problems of C and C++ and making the new language java simple, reliable , portable and powerful. Java is also used in web applications, because of its portability and security. Applets and servlet programs were developed, which acts as web browser and web server respectively. World Wide Web emerged at about the same time that Java was being implemented. Internet wanted portable programs, so Java was used in its programs. It was a perfect response to the demands of the newly emerging, highly distributed computing universe. JDK (Java Development Kit) It is the Java tool which contains all the classes , methods and variables used to build a Java program. It consists of – appletviewer (for viewing Java applets) javac (Java compiler) java (Java interpreter) javap (Java disassemble) javah(for C header files) javadoc(for creating HTML documents) jdb (Java debugger) The program done in a computer in Java is compiled using java compiler and is then interpreted in another remote system (if required). The Java debugger is used to locate errors in the program.

Transcript of Introduction to JAVA – Unit1 SVIT,Bangalore Introduction ... Science (ISE)/Sem...

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 1

    UNIT -1

    Introduction to JAVA

    Java is a general-purpose, object-oriented programming language. It is a blend of C & C++. It was developed by Sun Microsystems of USA by a team headed by James Gosling in the year 1991. It was first named as ‘Oak’.

    It was primarily developed to be a portable, platform-independent language, means that the programs built in java can be executed in any platform and under different environments. So that it can be embedded in various electronic devices, such as microwave ovens, remote control etc.

    C and C++ languages have problems in terms of reliability and portability. So the language java was formed, by removing the sources of problems of C and C++ and making the new language java simple, reliable , portable and powerful.

    Java is also used in web applications, because of its portability and security. Applets and servlet programs were developed, which acts as web browser and web server respectively. World Wide Web emerged at about the same time that Java was being implemented. Internet wanted portable programs, so Java was used in its programs. It was a perfect response to the demands of the newly emerging, highly distributed computing universe.

    JDK (Java Development Kit)

    It is the Java tool which contains all the classes , methods and variables used to build a Java program. It consists of –

    • appletviewer (for viewing Java applets) • javac (Java compiler) • java (Java interpreter) • javap (Java disassemble) • javah(for C header files) • javadoc(for creating HTML documents) • jdb (Java debugger)

    The program done in a computer in Java is compiled using java compiler and is then interpreted in another remote system (if required). The Java debugger is used to locate errors in the program.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 2

    Java is an evolving programming language that began with the release of JDK. In the next phase, the Java development team included more interfaces and libraries as programmers demanded. These API extensions were added to the JDK and called as Java 2 Standard Edition (J2SE), Java 2 Enterprise Eidition (J2EE) has the API to build applications for a multi-tier architecture. Java 2 Mobile Edition(J2ME) contains the API used to create wireless Java applications.

    Java is interpreted

    A Java source file is first compiled using Java compiler, this produces the bytecode. Byte code is highly optimized set of instruction. It is an intermediate stage during the execution. The byte code is than interpreted by the Java Virtual Machine (JVM), to produce the output in the expected system.

    Due to the interpretation behavior of Java, this language is platform independent and portable .

    JVM(Java Virtual Machine)

    A Java Virtual Machine (JVM) is a virtual machine capable of executing Java bytecode. JVM enables Java to be both secure and portable.

    The Java compiler generates the bytecode, which is a highly optimized set of instructions. JVM is an interpreter for bytecode and creates the executable file. Thus Java is called an interpreted language.

    There are different JVMs for different operating systems. So only JVM need to be implemented for any other platform. Thus JVM helps in the portability of Java program. JVM also helps to make Java secure. Java code is executed by JVM and thus JVM has the control to prevent program from generating side effects to the system.

    JAVA PROGRAM JAVA COMPILER JVM

    bytecode Program output

    (Compiles Source Code) (Interpretes ByteCode)

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 3

    Difference between C , C++ and Java

    Feature C C++ Java

    Paradigms Procedural Procedural, OOP OOP

    Platform Dependence

    Yes Yes No

    Result from compiler

    Executable Code

    Executable Code Java bytecode

    Interpreter Not used Not used Used

    Memory management

    Manual Manual Managed using a garbage collector

    Pointers Yes Yes No

    Preprocessor Yes Yes No

    String Type Character arrays Character arrays, objects

    Objects

    Complex Data Types

    Structures, unions

    Structures, unions, classes

    Classes

    Inheritance No Multiple class Single class inheritance, and

    System1 Java source file

    (.java)

    javac

    Java bytecode files

    (.class)

    Intel x86 JVM

    Remote

    System

    System2 Java source file

    (.java)

    javac

    Java bytecode files

    (.class)

    ARM JVM

    Remote

    System

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 4

    inheritance interface

    Operator Overloading

    No Yes No

    Empty argument list Func(void) Func() or Func(void) Func()

    Global Variable Yes Yes No

    Goto Statement Yes Yes No

    Header Files Yes Yes No

    Destructor No Yes Uses finalize() method

    Java Features (buzzwords)

    The developers of Java wanted to design a language that solves all the problems of modern high-level language. They not only wanted secure and portable language but also a simple, compact and interactive language.

    The key attributes of Java are – • Simple • Secure • Portable • Object – Oriented • Robust • Multithreaded • Architecture – neutral • Interpreted • High performance • Distributed and • Dynamic

    Simple – Java is a simple language to learn and program. Many features of C and C++ are used in Java. It is very easy to familiarize Java as the same concepts of C, C++ and object – oriented programming are used here. Java is a simplified version of C++. Secure - Systems connected to Internet must be secure. There are more chances of virus attack while downloading. Viruses may affect your system or take important information like account no, password etc. from your system. Java achieved security by confining an applet to Java execution environment and not allowing it access to other parts of the computer.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 5

    Portability – portability means the code written and executed in a system must be able to execute in other systems of different environment also. This is achieved in Java by JVM. Changes and upgrades in operating system, processors and system resources will not force any changes in Java programs. Object-oriented – Java is true object-oriented language. Everything in Java is an object. All the program code resides in a class or object. The classes are arranged in packages and can be inherited. Robust – Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. The major two reasons for program failure are memory management mistakes and mishandled exceptions. These are handled very well in Java. It is designed as a garbage-collected language relieving the programmers from all memory management problems. It incorporates exception handling – handles serious errors and eliminates any risk of crashing the system. Multithreaded – Java supports multithreading. Java program has the capability of handling multiple tasks simultaneously. This means that we need not wait for the application to finish one task before beginning another. Example - we can listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer. Architectural-Neutral - The main issue of Java developers was t hat the code longevity and portability. The code executed in a system, may not execute in the same system due to the upgrades of OS, processors and change in core system resources. The Java designers made the language and built JVM such that a code written once can run anytime, anywhere and forever. Interpreted and High performance - A Java program is compiled to form an intermediate Java bytecode. This can be executed in any system that has implemented JVM. JVM interprets the bytecode to form an executable file. The bytecode is highly optimized and so there is high performance. Distributed – Java is designed as a distributed language, as it can share data and programs from Internet. Java handles TCP/IP protocol. Java also supports RMI, which enables a program to invoke remote methods.

    Dynamic – Java is a dynamic language. It is capable of dynamically linking in new class libraries, methods and objects in a safe manner.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 6

    Object – Oriented Programming

    Java is an object-oriented programming language. Object-oriented programming organizes a program. The main characteristics of object-oriented program is that it controls the access of data. Java is full of classes. Even a small program in Java contains a class. An object is an instance of a class. Object

    • An Object is an instance of user-defined data type called Class. It can also be said that object is a variable whose type is a user-defined Class.

    • Object is a real – time entity.

    • An object in Java is a representation of some physical, logical, or conceptual entity. For example, an object can be a vehicle, bank-account, animal, machine etc.

    Class

    • Class is a template for instantiating an object.

    • It encapsulates the attributes and behavior of an entity.

    • Similar objects belong to a class. For example, cat and dog belongs to animal class.

    Object is a run-type entity in object-oriented programming where as Class is just a template for generating an object. Abstraction

    • Abstraction is representation of only the essential features of an entity. For example, to drive a car, you only need to know about accelerator, brake, clutch, and some other controls without ever knowing how the things inside the car work.

    • Abstraction helps in managing the complexity of the software. Encapsulation

    • Encapsulation is bundling together the attributes and behaviors of an entity.

    • Encapsulation together with data/information hiding feature allows limited visibility to the class users. Access specifiers (private, public, and protected) in Java are used to implement data hiding.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 7

    • Object-oriented approach is a data-centric approach. Data together with operations that can manipulate it are encapsulation into a Class.

    Inheritance

    • Accessing the properties and operations of a class by another class is called inheritance

    • Inheritance is similar to inheriting characteristics from our parents.

    • Software development is costly and time-consuming. Object-orientation not only helps in managing complexity but also promotes software reusability through its 'inheritance' feature.

    • Using inheritance, a class (called derived-class) inherits already well-developed methods from another class (called base-class); thereby saving lot of time and money.

    Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

    Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

    A hierarchy of bicycle classes

    This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 8

    Polymorphism

    • Literally, polymorphism means many forms.

    • A function can exhibit many forms depending on the class of which it is a part. For example , we have a function called make_sound(). If is part of human object, make_sound() returns 'speak' and if it is a part of dog object then it returns 'bark'

    A First Simple Program – Java is full of classes, every method and variables in the program are from a class. The program name in Java should have the name of the class having the main function in it. The class name is extended with ‘.java’ extension to form the program name.

    Example - A program to print a statement.

    /*This is a simple program to print a statement at the console */ class Sample { public static void main(String args[ ]) { System.out.println(“This is java”); } } Output is : This is java

    The line1 and 2 is a comment statement, there are mainly 2 types of comments in Java. ‘//’ is a single line comment, using the // symbol comments the entire line starting from that symbol. The other type of comment is the multiline comment, the whole statements starting from ‘/*’ and ending with’*/’ are commented.

    The line - class Sample uses the keyword class to declare that new class is being defined. Sample is an identifier that is the name of the class. The class members are included in the ‘{’ & ‘}’.

    The line public static void main(String args[ ]) begins the main() method. public keyword is an access specifier, which allows the programmer to control the visibility of the class members. The main method must be declared as public, since it must be called by code outside of its class when the program is stated, JVM calls the main() function. static means that this variable or

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 9

    method is for the class not for any objects in particular. The main() method must be static as it is called without having to instantiate any class. void tells that main() does not return any value.

    Any information needed to pass to the method is received by the array specified in parenthesis of the main function. This is an array of strings.

    The line System.out.println(“This is java”); is used to display a line specified within double quotes. Execution of Java program The above program should have the filename as ‘Sample.java’. The filename should have the same case as the class name, as Java is case-sensitive.

    Java source file is compiled using Java compiler at the prompt as,

    C;\> javac Sample.java

    This creates a file called Sample.class that contains the bytecode version of the program. This cannot be directly executed it has to be interpreted by JVM as follows to get the output.

    C:\>java Sample

    The Java compiler will create separate class file for each class in the program. Then the java command is given with the name of the class which you want to execute.

    Data Types Every variable in Java has a data type. Data types specify the size and type of values that can be stored. The variety of data types available, allow the programmer to select the type appropriate to the needs of the application. Java data types are as follows –

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 10

    Integer Types Java defines four integer types: byte, short, int, and long. They can hold only whole numbers such as 123,-87. These integer data types differs in the size of the values that can be stored. The memory size and range of all the four integer data types are shown in table below – Type Size (in bytes) Minimum Value Maximum Value byte 1 -128 127

    short 2 -32,768 32,767 int 4 -2,147,483,648 2,147,483,647 long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

    Data Types in JAVA

    Primitive (Intrinsic)

    Non - Primitive (Derived)

    Numeric Non-Numeric

    Integer Floating-Point Character Boolean

    Classe Arrays

    Interface

    Byte

    Short

    Int

    Long

    Double

    Float

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 11

    Floating Point Types Integer types can hold only whole numbers and therefore we use another type known as floating point type to hold numbers containing fractional parts such as 27.45 and -1.345. There are two kinds of floating point storage in Java – float type and double type. The float type values are single-precision numbers while the double types represent double-precision numbers. Type Size (in bytes) Minimum Value Maximum Value float 4 3.4e-038 3.4e+038

    double 8 1.7e-308 1.7e+308 Floating point numbers are always treated as double-precision numbers. To force them into single-precision mode, f or F must be appended to numbers. Example - 1.234f, 3.53 F

    Character Type The data type used to store characters is char. It has a size of 2 bytes. It uses Unicode to represent characters. It holds a single character. Boolean Type Java has a primitive type, called Boolean, for logical values. It can have only one of two possible values, true or false.

    //A simple program to show the use of data type class DTypes { public static void main(String args[ ]) { byte b =34; //Declaration of byte variable int i=1000; //Declaration of integer variable

    char c1,c2; //Declaration of character variables c1 = 89; // Initialization of character variable c2 = ‘Y’; double dval=160000000000; //Declaration of double variable boolean b = true; //Declaration of Boolean variable

    System.out.println(“Value of byte variable b is ” +b); System.out.println(“Value of integer variable i is ” +i); System.out.println(“Value of character variable c1 is ” +c1); System.out.println(“Value of character variable c2 is ” +c2); System.out.println(“Value of double variable dval is ” +dval); if (b) System.out.println(“This is printed as b is true”);

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 12

    else System.out.println(“This is not printed as b is true”);

    } } Output of this program is –

    Value of byte variable b is 34 Value of integer variable i is 100 Value of character variable c1 is Y Value of character variable c2 is Y Value of double variable dval is 160000000000 This is printed as b is true

    Default Values

    Fields that are declared but not initialized will be set to a default by the compiler. This default will be zero or null, depending on the data type. The default values for the above data types are -

    Data Type Default Value

    byte 0

    short 0

    int 0

    long 0L

    float 0.0f

    double 0.0d

    char '\u0000'

    String (or any object) null

    boolean false

    Strings

    Strings are created using two classes in Java, String and StringBuffer. An object of String class is instantiated to store the value of strings. A Java string is not a character array and is not NULL terminated.

    Syntax for declaring a string String strname; strname = new String(“New string”);

    Eg –

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 13

    String firstName; firstName = new String(“Sajeev”); These statements can be combined as , String firstName = new String(“Sajeev”); An array of strings can be created. The statement

    String arg[] = new String[4]; This statement creates an array ‘arg’ to hold four string constants. String Methods The String class contains many methods to translate the string variables. Eg – toLowerCase(), trim(), replace(), concat() etc. The table below shows the lists of string methods. Here i and j are int indexes into a string, s and t are Strings, and c is a char. cs is a CharacterSequence. Method Task Performed i = s.length() length of the string s i = s.compareTo(t) compares t to s. returns t b = s.equals(t) true if the two strings have equal values b = s.equalsIgnoreCase(t) true if the two strings have equal values, case is not considered. i = s.indexOf(t) index of the first occurrence of String t in s i = s.indexOf(t, i) index of String t at or after position i in s c = s.charAt(i) Returns char at position i in s s1 = s.substring(i) substring from index i to the end of s s1 = s.substring(i, j) substring from index i to before index j of s s1 = s.toLowerCase() new String with all chars lowercase s1 = s.toUpperCase() new String with all chars uppercase s1 = s.trim() new String with whitespace deleted from front and back s1 = s.replace(c1, c2) new String with all c1 characters replaced by character c2 b = s.matches(regexStr) true if regular expression ‘regexStr’ matches the entire string in s s = String.valueOf(x) Converts x to String, where x is any type value

    //A program to sort an array of strings in alphabetical order.

    class StringOrdering { static String name[ ] ={“Madras”,”Delhi”,”Ahmedbad”,”Calcutta”,”Bombay”}; public static void main(String mar[]) { int size = name.length; String temp = null;

    for (int i = 0; i < size ; i++) {

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 14

    for( int j =i+1; j < size ; j++) { If(name[i].compareTo(name[j]) >0)

    { //swap the strings

    temp = name[i]; name[i] = name[j]; name[j] = temp;

    } }

    } for (int i = 0; i < size ; i++) {

    System.out.println(name[i]); }

    } }

    StringBuffer Class

    This is another class used to create String variables. While String creates strings of fixed length, StringBuffer creates strings of flexible length. Substrings can be inserted in the middle of another string, or append to the end of another string.

    Some of the methods of this class are

    Method Task Performed s1.setCharAt(n,’x’) Modifies the nth character to x s1.append(s2) Appends the string s2 to s1 at the end s1.insert(n,s2) Inserts the string s2 at the position n of the string s1 s1.setLength(n) Sets the length of the string s1 to n. If ns1.length() zeros are added to s1.

    Arrays An array is a group of variables of same type, which have a common name. Arrays of any data type can be created and may have one or more dimensions. A specific element in an array is accessed by its index or subscript in brackets.Eg – month_days[3];. Arrays offer a convenient means of grouping related information.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 15

    One-dimensional Arrays A one-dimensional array is a list of items having the same variable type and same name. The index is used to access the different values of the array. Creation of an array An array is created in 3 steps –

    o Declaration of array o Creation of memory locations for array o Initialization of array elements

    Declaration of array The general form of a one-dimensional array declaration is

    type var-name[ ]; OR

    type[ ] var-name; Here, type declares the data type of the array, which determines what type of data the array will hold and var-name is the array variable name. Eg - int month_days[]; Here, an array named month_days is declared of type ‘array of int’ This declaration only tells that month_days is an array variable, but memory is not allocated for this array. Creation of memory locations for array In Java arrays are dynamically allocated. After declaration of array, memory is assigned to array by using a special operator ‘new’. Java allows us to create arrays using new operator only, as shown below

    array-var = new type[size];

    Here, ‘type’ specifies the type of data being allocated, ‘size’ specifies the number of elements in the array, and ‘array-var’ is the array variable. Eg - month_days = new int[12]; This statement allocates a 12-element array of integers to month_days variable Initialization of array elements Array can be initialized in two ways –

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 16

    var-name[index] = value; Eg - month_days[1] = 28; This statement assigns the value 28 to the second element of month_days. Array can also be initialized when they are declared. In this case new operator is not used to allocate memory.

    type var-name[ ] = {list of values};

    The list of values are separated by commas and surrounded by curly braces. The array will automatically be created large enough to hold the number of elements specified during the array initialization. Eg – int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 }; Java strictly checks the range of array in the program. It checks that the user do not accidentally try to store or reference values outside the range of the array. For example, the run-time system will check the value of each index accessed in month_days array is between 0 and 11 inclusive. If we try to access elements outside the range of the array, there will be a runtime error. // Demonstrate a one-dimensional array. //Program to display the values of array class Array {

    public static void main(String args[]) {

    int month_days[]; //declaration of array month_days = new int[12]; //Allocation of memory month_days[0] = 31; // initialization of array month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30;

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 17

    month_days[11] = 31; for(int i=0;i

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 18

    { public static void main(String args[])

    { int twoD[][]; //Declaration twoD[][]= new int[4][5]; //allocation of memory int i, j, k = 0; for(i=0; i

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 19

    // second row with 2 columns

    // third row with 3 columns

    // fourth row with 4 columns

    Literals A literal is the source code representation of a fixed value; literals are represented directly in source code without requiring computation. As shown below, it is possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000; There are five major types of literals in Java –

    • Integer literals • Floating_point literals • Character literals • String literals • Boolean literals

    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. You signify a hexadecimal constant with a leading zero-x, (0x or 0X). An integer literal is of type long is ended with the letter L or l. Eg- int decVal = 26; // The number 26, in decimal int hexVal = 0x1a; // The number 26, in hexadecimal int octVal = 032; // The number 26, in octal

    Floating-Point Literals

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 20

    Floating-point numbers represent decimal values with a fractional component. They can be expressed in two ways –

    • Standard notation – consists of whole number component followed by a decimal point followed by a fractional component. For example, 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. For example, 6.022E23, 314159E–05, and 2e+100.

    A floating-point literal is by default of type double. It is of type float if it ends with the letter F or f. Double can be optionally end with the letter D or d.

    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, in Java. They can only be assigned to variables declared as boolean, or used in expressions with Boolean operators. 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. Eg - 'a', 'z', '@ etc. For characters that are impossible to enter directly, there are several escape sequences, such as '\'' for the single-quote character itself, and '\\n' for the newline character. 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, a backslash-u (\u), followed by exactly four hexadecimal digits. For example, '\u0061' Table of Character Escape Sequences Escape Sequence Description \ddd Octal character (ddd) \uxxxx Hexadecimal UNICODE character (xxxx) \' Single quote \" Double quote \\ Backslash \r Carriage return (returns to the start of same line)

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 21

    \n New line (also known as line feed) \f Form feed \t Tab \b Backspace String Literals String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are "Hello World" "two\nlines" "\"This is in quotes\"" The escape sequences and octal/hexadecimal notations work the same way as defined for character literals. In Java there is no line-continuation escape sequence, so a string must begin and end on the same line. Variables The variable is the basic unit of storage in a Java program. A variable may take different values at different times, unlike constants that remain unchanged during the execution of program. 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. The syntax of declaring a variable -

    type varname [ = value][, varname [= value] ...] ; here ‘type’ - one of Java's atomic types, or the name of a class or interface, ‘identifier’ - name of the variable. The variable can be initialized by specifying an equal sign and a value. It must be of the same type (or compatible) as that specified for the variable. Use a comma to declare more than one variable of the specified type. Eg - int a, b, c; // declares three variables of int type a, b, and c. int d = 3, e, f = 5; // declares three int type variable , d and f are initialized byte z = 22; // declares one byte type variable z. double pi = 3.14159; // declares and initializes a double variable. char x = 'x'; // declares a character variable x and initializes to value 'x'. The Scope and Lifetime of Variables

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 22

    Java allows variables to be declared within any block, which begins with an opening brace ‘{‘ and ended by a closing brace ‘}’. A block defines a scope. The variables declared in a block are visible (accessible) only in that block. // 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; // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2;

    } System.out.println("Variable y is not known here "); // x is still known here . System.out.println("x is " + x);

    } } Output – x and y: 10 20 Variable y is not known here x is 40 Type Casting A variable of one type can be converted to another data type , this process is called type casting. The general syntax of type casting is – Type var1 = (newtype) var2; Four integer types can be cast to any other data type except Boolean. Floating_point datatypes can also be casted to any other type except Boolean. Casting into a smaller type results in a loss of data. Floating point values if type casted to integer, it losses the fractional part of the floating value. Casts that results in No Loss of information

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 23

    From To byte short, char, int, long, float, double short int, long, float, double char int, long, float, double int long, float, double long float, double float double Java's Automatic Conversions The type casting takes place automatically when the following two conditions are met:

    • The two types are compatible. • The destination type is larger than the source type.

    When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.

    Type casting can easily be done from lower types to higher types.

    Access Specifiers

    The access to the code and variables in the class is controlled by encapsulation. The access specifier in the declaration determines the accessibility of its members. The access specifiers in Java are – public, private, and protected.

    When the member has a public specifier, then that member can be accessed by any other code. When the member is specified as private, then that member can only be accessed by other members of its class. protected applies only when inheritance is involved. So the main() function is specified as public, as it has to be invoked by Java run-time system.

    When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.

    Operators and Expressions: Java supports a rich set of operators. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Arithmetic Operators Arithmetic operators are used in mathematical expressions as used in algebra. The operands of the arithmetic operators must be of a numeric type. The following table lists the arithmetic operators: Operator Result

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 24

    + Addition - Subtraction or unary minus * Multiplication / Division % Modulus ++ Increment += Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment - - Decrement The Basic Arithmetic Operators The basic arithmetic operations-addition, subtraction, multiplication, and division- all do the same operations as in mathematic. The minus operator is also used as a unary operator, to negate the single operand. Unary operator means it acts on single operator. The division operator when applied to an integer type, there will be no fractional component attached to the result. The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-point types as well as integer types. The following simple example program demonstrates the arithmetic operators and modulus operator. It also illustrates the difference between floating-point division and integer division. 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; int x = 42 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); System.out.println("42 mod 10= " + 42 % 10);

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 25

    // arithmetic using doubles System.out.println("Floating 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); System.out.println("42.3 mod 10 = " +42.3 % 10);

    }

    } Output is – Integer Arithmetic a = 2 b = 6 c = 1 d = -1 e = 1 42 mod 10 = 2 Floating Point Arithmetic da = 2 db = 6 dc = 1.5 dd = -0.5 de = 0.5 42.3 mod 10 = 2.3 Arithmetic Assignment Operators There are assignment operators for all of the arithmetic binary operators. Thus, any statement of the form

    var = var op expression; can be rewritten as

    var op= expression; Java provides special operators that can be used to combine an arithmetic operation with an assignment. The statement a = a + 4;

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 26

    Can be rewritten as a += 4; The above statement uses the += assignment operator. Both statements perform the same action, they increase the value of a by 4. Similarly the statement a = a % 2; can be expressed as a %= 2; Here the %= obtains the remainder of a/2 and puts that result back into a. // Demonstrate several assignment operators. class OpEquals {

    public static void main(String args[]) {

    int a = 1; int b = 2; int c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c);

    } } Output – a = 6 b = 8 c = 3 Increment and Decrement The ++ and the - - are increment and decrement operators. The increment operator increases its operand by one. The decrement operator decreases its operand by one. Eg - the statement: x = x + 1; can be rewritten by using the increment operator as : x++; Similarly, the statement: x = x - 1; is equivalent to x—; These operators can appear both in postfix form and prefix form. In postfix form, the operator follows the operand as, x++. In prefix form, the operator precedes the operand as, ++x.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 27

    In the prefix form, the operand is incremented or decremented before the value is obtained for use in the expression. In postfix form, the previous value is obtained for use in the expression, and then the operand is modified. Eg - x = 42; y = ++x; In this case, y is set to 43, because the increment occurs before x is assigned to y. First x is incremented to 43 and then it is assigned to y. Thus, the line y = ++x; is the equivalent of these two statements: x = x + 1; y = x; Whereas in postfix form it is different x = 42; y = x++; the value of x is assigned to y first and then x is incremented. So after the execution of this statement, the value of y is 42 and x value is 43. The line y = x++; is the equivalent of these two statements: y = x; x = x + 1; // Demonstration of increment operator ++. class IncDec {

    public static void main(String args[]) {

    int a = 1; int b = 2; int c; int d; c = ++b; d = a++; c++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d);

    } } output –

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 28

    a = 2 b = 3 c = 4 d = 1 The Bitwise Operators The bitwise operators of Java can be applied to operands of integer types - long, int, short, byte, and character type. These operators act upon the individual bits of their operands. The bitwise operators are – Operator Result ~ Bitwise unary NOT & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR >> Shift right >>> Shift right zero fill >= Shift right assignment >>>= Shift right zero fill assignment

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 29

    The Bitwise AND (&) produces a 1 bit if both operands are 1. A zero is produced in all other cases. Eg – bit pattern of 42 is 00101010 and 15 is 00001111 00101010 & 00001111

    ——————— 00001010

    The Bitwise OR(|) produces 1 bit if either of the bits in the operands is a 1, if both the operands are 0 then OR operator produces 0. Eg -, bit pattern of 42 is 00101010 and 15 is 00001111

    00101010 | 00001111 ———————

    00101111

    The Bitwise XOR (^) produces 1 bit if exactly one of the operands is 1. Otherwise, the result is zero. The following example shows the effect of the ^. Eg - , 00101010

    ^ 00001111 ——————

    00100101 //Program to demonstrate the use of bitwise logical operators. class BitLogic {

    public static void main(String args[]) {

    String binary[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111","1000", "1001", "1010", "1011", "1100", "1101", "1110","1111"}; int a = 3; // 0011 in binary int b = 6; // 0110 in binary int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); int g = ~a; System.out.println(" a = " + binary[a]); System.out.println(" b = " + binary[b]);

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 30

    System.out.println(" a|b = " + binary[c]); System.out.println(" a&b = " + binary[d]); System.out.println(" a^b = " + binary[e]); System.out.println("~a&b|a&~b = " + binary[f]); System.out.println(" ~a = " + binary[g]);

    } } Output -

    a = 0011 b = 0110 a|b = 0111 a&b = 0010 a^b = 0101 ~a&b|a&~b = 0101 ~a = 1100

    The Left Shift operator(

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 31

    { num = num >), shifts all of the bits in the operand to the right a specified number of times. Syntax value >> num where, num specifies the number of positions to right-shift the value in value. The >> moves all of the bits in the specified value to the right the number of times specified by num. For each shift previous present bits are added to higher order bits and the lower most bits are lost. Eg – 00100000 is 32 00100000 >> 2 Result is 00001000 8

    Each time right shift is done, it divides that value by two and discards any remainder. When right shift is done, the top (leftmost) bits are filled in with the previous contents. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. Eg – -8 >> 1 is -4 -8 11111000 >> 1

    is 11111100 that is -4 The Unsigned Right Shift

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 32

    Sometimes filling of higher order bits with previous content while shifting is undesirable especially when working with pixel-based values and graphics. That is the programmer wants to fill the top most bits with zero only no matter what its initial value was. In such cases, the >> >operator is used, this is known as an unsigned right shift operator. This operator always shifts zeros into the high-order bit. Eg – -14 >>> 2 is 1073741820 -14 in binary is 11111111 11111111 11111111 11110010 After the unsigned right shift it becomes 00111111 11111111 11111111 11111100 1073741820 Bitwise Operator Compound Assignments The assignment operator and the bitwise operators can be combined and used. Eg – The following two statements, which shift the value in a right by four bits and assigns the result to a , are equivalent: a = a >> 4; a >>= 4; Similarly, the following two statements, which result in a being assigned the bitwise expression a OR b, are equivalent: a = a | b; a |= b; // Program to demonstrate the compound assignment operators class OpBitEquals {

    public static void main(String args[]) {

    int a = 1; int b = 2; int c = 3; a |= 4; b >>= 1; c

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 33

    Output – a = 3 b = 1 c = 6

    Relational Operators The relational operators determine the relationship that one operand has to the other. Usually, they determine equality and ordering of the operands. The relational operators are – Operator

    Result

    == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 34

    == Equal to != Not equal to ?: Ternary if-then-else The logical Boolean operators, &, |,!, and ^, operate on boolean values in the same way as that of bitwise operators on integers. The table below shows the effect of each logical operation: A B A | B A & B A^ B ! A False False False False False True True False True False True False False True True False True True True True True True False False Short-Circuit Logical Operators The operators AND (&&) and OR (||) are called the short-circuit logical operators, as it reduces the evaluation process. 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.

    Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone.

    The Assignment Operator The assignment operator is the single equal sign, =. Its syntax is –

    var = expression; where, the type of var must be compatible with the type of expression. Eg – X = 300;

    x = y = z = 100; // set x, y, and z to 100 The ? Operator Java includes a special ternary (three-way) operator that can replace certain types of if then- else statements. Syntax –

    expression1 ?expression2 : expression3 where, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. Eg – ratio = ((denom == 0) ? 0 : num / denom);

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 35

    If denom equals zero, then the expression between the question mark and the colon is evaluated and sent to ratio as the result. If denom does not equal zero, then the expression after the colon is evaluated and sent as the result. // Demonstrate ? operator class Ternary {

    public static void main(String args[]) {

    i = -10; k = i < 0 ? -i : i ; // get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k);

    } } Output – Absolute value of -10 is 10 Operator Precedence Each operator in Java has some precedence. The precedence of Java operators are – Highest ( ) [ ] .

    ++ -- ~ ! * / % + - >> >>> >= < > b + 3 First adds 3 to b and then shifts a right by that result. This expression can be rewritten using redundant parentheses like this: a >> (b + 3) Suppose if a should be first shifted right by b positions and then add 3 to that result, then the expression should be changed as (a >> b) + 3

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 36

    Control Statements Control statements causes the flow of execution to advance or branch based on changes to the state of a program. Program control statements can be put into the following categories: selection, iteration, and jump. 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 statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion. All of Java's control statements are examined here.

    Java supports two selection statements: if and switch. These statements allows to control the flow of program's execution based upon conditions known only during run time. if The if statement is Java's conditional branch statement. It can be used to route program execution through two different paths. Syntax – if (condition is true )

    statement1; else

    statement2; Here, each statement may be a single statement or a compound statement enclosed in curly braces. The condition is any expression that returns a boolean value. The else clause is optional. If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. Eg1 – …… int a, b,res; a=6; b=0; if( b != 0) res = a/b; …… …. Here, if b is not zero, then a is divided by b. Eg 2– String passwd = “sai”; ……

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 37

    if( passwd == “vidya”) System.out.println(“Valid Password”); else System.out.println(“In-valid Password”); ………. …….. Nested ifs A nested if is an if statement that comes in the statement of another if or else. The else statement always refers to the nearest if statement that is within the same block as the else. Eg – if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; // this if is else a = c; // associated with this else } else a = d; // this else refers to if(i == 10) The final else is not associated with if(j100), because it is the closest if within the same block. The if-else-if Ladder When a series of decisions are involved, a sequence of nested ifs and elses are required. The if else-if ladder looks like this: if(condition)

    statement; else if(condition)

    statement; else if(condition)

    statement; . . else

    statement; When one of the if statement conditions is true, the statement associated with that if is executed, and the rest of else if conditions are bypassed. If none of the conditions is true, then the final else

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 38

    statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. //A program to demonstrate if-else-if statements, to find the number of days in a month . class IfElse { public static void main(String args[]) { int month = 4; // April int days; String year = “leapyear”; if(month =2) { if(year = “leapyear”) days = 29; else days = 28; } else if(month == 1 || month == 3 || month == 5|| month == 7|| month == 8|| month == 10|| month == 12) days = 31; else days = 30; System.out.println("April has " + days + "days."); } } Ouput is – April has 30 days. Switch The switch statement is a multiway branch statement. It provides an easy way to execute different parts of the code based on the value of an expression. It is an alternative for a large series of if-else-if statements. Syntax – switch (expression) {

    case value1: // statement sequence break; case value2: // statement sequence break;

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 39

    .

    .

    . case valueN: // statement sequence break; default: // default statement sequence

    } The expression must be of type byte, short, int, or char. The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. // A simple example of the switch. class SampleSwitch { public static void main(String args[]) { int month = 4; // April String year = “leapyear”; switch(month){ case 2: if(year = “leapyear”) System.out.println("Month has 29 days."); else System.out.println("Month has 28 days."); break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println("Month has 31 days."); break;

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 40

    case 4: case 6: case 9: case 11: System.out.println("Month has 30 days."); break; default: System.out.println(“In-valid month”); } } } Ouput is – Month has 30 days. The break statement is optional. If you omit the break, execution will continue on into the next case also. In the above program the case 1,3,5,7,8,10 and 12 execute the same statement as there is no break between them. Nested switch Statements A switch can be part of the statement sequence of an outer switch. This is called a nested switch. Syntax – switch(expression) { case value1: switch(expression2) { // nested switch case value0: //statement sequence break; case value1: // no conflicts with outer switch //statement sequence break; } break; case value2: // ... Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. Three important features of the switch statement:

    • The switch can only test for equality and looks for a match, whereas if can evaluate any type of boolean expression.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 41

    • No two case constants in the same switch can have identical values. A switch statement enclosed by an outer switch can have case constants in common.

    • A switch statement is usually more efficient than a set of nested ifs. Iteration Statements The iteration statements or loops of Java are for, while, and do-while. A loop repeatedly executes the same set of instructions until a termination condition is met. while The while loop is the most fundamental looping statement of Java. It repeats a statement or block while its controlling expression is true. Syntax – while(condition) { // body of loop } The condition can be any Boolean expression(An expression which returns true or false). 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. //A program to demonstrate the while loop. class While { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n—; } } } Output is – tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 42

    tick 2 tick 1 The body of the loop will not execute even once if the condition is false to begin with. do-while Sometimes it is required to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In do-while loop the test of expression is done at the end. Syntax – 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. The do-while loop condition must be a Boolean expression. // A program to demonstrate the do-while loop. class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println("tick " + n); n—; } while(n > 0); } } The loop in the preceding program, can also be written as follows: do { System.out.println("tick " + n); } while(—n > 0); For loop There are two for loops in Java. The first is the traditional form that is used in other languages also. The second is the new “for-each” form.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 43

    The syntax of the for statement – for(initialization; condition; iteration) { // body } When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. The initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false. //A program to demonstrate the for loop. class ForTick { public static void main(String args[]) { int n; for(n=10; n>0; n—) System.out.println("tick " + n); } } As the for loop contains only 1 statement, there is no need for the curly braces. Often the control variable of the for loop is only used within that loop, So it is possible to declare the variable inside the initialization portion of the for. For example, the preceding program can be changed as follows as the control variable n is used inside the for only. …………… ……… for(int n=10; n>0; n—) System.out.println("tick " + n); } } Using the Comma in for loop Initialization and iteration portions of the for loop may need more than one statement, this can be implemented by using a comma in the for loop. When the loop is controlled by the interaction of two or more variables, it would be useful if both variables could be included in the same for statement.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 44

    Eg – // Using the comma. class Comma {

    public static void main(String args[]) {

    int a, b; for(a=1, b=4; a

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 45

    { public static void main(String args[]) {

    int nums[ ] ={1,2,3,4,5,6,7,8,9,10}; int sum = 0; for(int x : nums) {

    System.out.println("Value is : " + x); sum = sum + x;

    } System.out.println("Summation: " + sum);

    } } Output – Value is : 1 Value is : 2 Value is : 3 Value is : 4 Value is : 5 Value is : 6 Value is : 7 Value is : 8 Value is : 9 Value is :10 Summation : 55 Note: 1) break; statement can be used to terminate the loop early. 2) Even if the value of the iteration variable is changed, it will not change the value in collection. Nested Loops Java allows loops to be nested. That is, one loop may be inside another loop. Eg – // Loops may be nested. class Nested {

    public static void main(String args[]) {

    int i, j;

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 46

    for(i=0; i

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 47

    { public static void main(String args[]) {

    while(i < 10) {

    if(i == 5) break; // terminate loop if i is 5 System.out.println("i: " + i); i++;

    } System.out.println("Loop complete.");

    } } Output – i: 0 i: 1 i: 2 i: 3 i: 4 Loop complete. Here, when the if condition is true, the while loop is terminated. Using break as a Form of Goto Java uses an expanded form of the break statement to do operations such as, exiting from a nested set of loops. So it does not support a goto statement. This form of break can be used to break out of one or more blocks of code. Syntax –

    break labelname; Here, labelname is the name of a label that identifies a block of code. Using break label the execution moves to the end of the labeled block. The labeled block of code must enclose the break statement.

    By using the labeled break statement we can exit from a set of nested blocks. But we

    cannot use break to transfer control to a block of code that does not enclose the break statement. A block can be named by using a valid Java identifier as a label followed by a colon. Break statement can be used to exit from this labeled block.

    Loop1 : for(initialization; condition; increment) {

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 48

    …………………. for (initialization; condition; increment)

    { ……….. if(condition)

    break Loop1; ……… ……… }

    …………… } ……………….. ……………….

    // Program to demonstrate use of break to exit from nested loops class BreakLoop {

    public static void main(String args[]) {

    outer: for(int i=0; i

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 49

    During the loop operations, it might be required 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 increment portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed.

    for(initialization; condition; increment) { …………………. for (initialization; condition; increment)

    { ……….. if(condition)

    continue; ……… ……… }

    …………… } ……………….. ……………….

    // Demonstrate continue. // A program that uses continue to cause two numbers to be printed on each line class Continue {

    public static void main(String args[]) {

    for(int i=0; i

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 50

    0 1 2 3 4 5 6 7 8 9 This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Continue statement may also specify a label to describe which enclosing loop to continue.

    Loop1 : for(initialization; condition; increment) { …………………. for (initialization; condition; increment)

    { ……….. if(condition)

    continue Loop1; ……… ……… }

    …………… } ……………….. ……………….

    Control statement - 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 at any time of execution. Syntax – return; // A program to 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.");

    }

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 51

    } Output – Before the return. The final println( ) statement is not executed. As soon as return is executed, control passes back to the caller, here java run-time system.

  • Introduction to JAVA – Unit1 SVIT,Bangalore

    Sreelatha . P.K

    Asst. Prof, CSE Dept. Page 52

    http://download.oracle.com/javase/tutorial/

    http://www.java2s.com/Tutorial/Java/CatalogJava.htm

    http://home.cogeco.ca/~ve3ll/jatutor4.htm