You are on page 1of 85

UNIT - I

Introduction:
Programming Languages are classified into the following categories A)Monolytic Programming Languages B)Procedural Programming Languages C)Structured Programming Languages D)Object Oriented Programming Languages a) Monolytic Programming Languages: Monolytic Programming Languages contain number of lines of data. 1 ---2 ----100 --Drawback: 1. It is not subroutine concept. 2. The program code is duplicated each time it is to be used. Examples: Assembly Language, Basic b) Procedural Programming Languages: The important features of Procedural Programming Languages are i) Emphasis on algorithm rather than data ii) Programs are organized in form of subroutine iii) Program controls are through jumps (goto) and calls to subroutine iv) Data move overly around the system from function to function v) It follows top down approach in program design vi) It is suitable for medium size software applications Global data

Drawback:

1. Data Security problem 2. Difficult to maintain program code 3. It doesnt model to real world problem very well Examples: Fortran, Cobol c) Structured Programming Languages: In Structured Programming Languages programs consist of multiple modules and each module has a set of functions of related types. The important features of Structured Programming Languages are i) Programs are divided into individual procedures that performs discrete tasks ii) Procedures are independent of each other iii) Procedures have their own local data and processing logic iv) Introduction of the concepts of user defined datatypes v) Maintenance of a large software system costly Global data

Sub programming Drawback: Module 1 Module 2 1. Data Security problem 2. It doesnt model real world problem very well 1

Examples: Pascal, C d) Object Oriented Programming Languages: The important features of Object Oriented Programming Languages are i) Emphasis on data rather than functions ii) Programs are divided into objects iii) Functions that operate on the data of an object are together in the data structure iv) Data is hidden and cannot be accessed by external functions (Data security) v) Objects may communicate with each other through functions vi) New data can be easily added to the functions whenever necessary vii) It follows bottom-up approach in program designing Object A Data functions Object B Data functions

Data functions Object C The important features of Object Oriented Programming are a) Encapsulation b)Abstraction c)Inheritance d)Polymorphism a) Encapsulation: The mechanism by which the data and functions are bounded together with an object definition. By means of Encapsulation, it can possible to protect the data. b) Abstraction: It is the process of defining data type often called an abstract data type together with the principle of data hiding. Abstract Data type refers to the program defined data type together with a set of operations than can be performed on the data. Data hiding is a property where by the internal data structure of an object is hidden from the rest of the program. The data can be accessed only by the function declared with in the class. c) Inheritance: Inheritance is the mechanism that allows the programmer to derive new classes from existing classes. The derived classes inherit the methods and data of the parent class. d) Polymorphism: Polymorphism is a feature that allows giving a single name to different methods with different parameters. Depending on the parameters only one particular method is executed. Object Based Programming = Data Encapsulation + Data Hiding + Overloading (Polymorphism) Example: Ada Dynamic Binding: When a method is called within a program, it associated with the program at run time rather than at compile time is called dynamic binding. Object Oriented Programming = Object Based Programming Concepts + Inheritance + Dynamic Binding (Polymorphism) Example: C++, JAVA

Advantages of OOP
1. OOP uses objects in programming languages. 2. The independence of each object easily to development and maintenance of the program 2

3. Data Hiding and Data Abstraction increase reliability and helps the programmer to built secure programs. 4. Dynamic Binding increases flexibility by permitting the addition of new class objects without having to modify the existing code. 5. Inheritance with Dynamic Binding enhances asthe reusability of code.

Applications of OOP
1)Simulation and Modeling 2)User Interface Design 3)Artificial Intelligence and Expert Systems 4)Neural Networks 5)Web Designing 6)CAD/CAM System JAVA: Java Programming Language was designed by James Gosling at Sun Microsystems in 1991. This language was initially called Oak but was renamed Java in 1995. It follows both the features of C and C++. Java Programming Language was very useful on Internet Programming. Since, by this language we can easily transfer the information from server to the nodes through the network. It provides active programs when we are viewing the passive data and self-executing programs. Generally, in the case of network programs Security and Portability is the main active areas concern. The Java Applet Programming provides such things. Java programs are classified into 2 types. 1) Application Programs 2) Applet Programs An Application is a program run on the computer under the operating system of the computer. This is similar to the other programming languages. An Applet is an application designed to be transmitted over the Internet and executed by a Javacompatible Web browser.

Java Features/Buzz Words


a) Platform Independent: Java is a platform independent language. Once we create the program in one operating system, the program is worked in any operating system that is transmitted to the operating system. b) Portable: The most significant contribution of Java over other languages is its portability. Java programs can be easily moved from one computer system to another anywhere and any time. Changes and upgrades in operating systems, processors, system resources will not forces any changes in Java programming. c) Object oriented: Java is a true object oriented language. Why because without class we cant run the program. Without main we can run the program. Almost everything in Java is an object. All program code & data reside with objects and classes. The object model in Java is simple and easy. d) Robust & Secure: Java is a Robust Language. It provides many safe guards to ensure reliable code. It is designed as garbage collected language relieving the programmers, virtually all memory management problems. Java also incorporates the concept of exception handling, which captures serious errors and eliminates any risk on crashing the system. Security becomes an important issue for a language that is used for programming on Internet. Java systems not only verify all memory access but also ensure that no viruses are communicated with the Applet. e) Distributed: Java is designed as a distributed language for creating applications on network. It has the ability to share both data and program. Java applications can open and remote object on Internet as easily as they can do in local system. f) Simple & Small: Java is a simple & small language. Many features of C and C++ that are sources are unreliable code are not part of Java. For example, Java doesnt use Pointers, Preprocessors, Header files, goto statements and many others. g) Multi Threaded: Java was designed to meet the real-world requirement of creating interactive, networked programs. Java supports multithreaded programming, which allows to handling multi tasks simultaneously. This means we need not wait for the application to finish one task before beginning another one. h) Dynamic: Java is a dynamic language. Java is capable on dynamically linking in new class, libraries, methods and objects. Java support functions written in other languages such as C and C++. These functions are known as native methods. Native methods are linked dynamically at run time. i) Compile & Interpreted: Usually a Computer language is either compiled or interpreted. Java combined both these approaches thus making. Java is a two-stage system. First Java Compiler translates 3

source code into byte code instruction and therefore in the second stage Java Interpreter generates machine code that can be directly executed by the machine that is running the Java program. Interpreter is called JVM (Java Virtual Machine). Java applications are platform independent. JVM, JDK are platform dependent. Interpreter is different for all operating systems like DOS, UNIX etc., The main drawback of C is the program cannot run in any other operating system. It is advantage of Java. j) High performance: Java performance is impressing for an interpreted language due to the use of intermediate code. Java architecture is also design to reduce overheads during runtime. The incorporation of multithreading enhances, the overall executions, speed of Java programs.

BASICS OF JAVA ENVIRONMENT:


Editor Phase 1 Compiler Phase 2 Class loader Phase 3 disk Byte code verifier disk disk Primary Memory

Phase 4

Primary Memory

Phase 5

Interpreter

Primary Memory

Phase 1: Java program is typed in a text editor (Notepad, Edit plus) and makes corrections if necessary. The programmer specifies that the file in the editor should be save. The program is stored on a second storage device such as a disk. Java program files are stored with .java extension filenames. Save: c:\jdk1.2.1\bin\filename.java Phase 2: The programmer gives the command javac filename.java to compile the program. At this stage, the Java compiler translates the Java program into byte code that is the language understood by the Java Interpreter. If the program compiles correctly, a file called filename.class is produced. This is the file containing byte codes that will interpret during the execution phase. Phase 3: This phase is called loading. The program must place in memory before it can be executed. This is done by the class loader, which takes the .class file containing in byte code and translates it into the memory. The .class file can be loaded from a disk on your system or over a network. Phase 4: Byte code verifier confirms that all byte codes are valid and dont valid Java Security Instructions. Phase 5: Java Interpreter reads byte code and translates them into a language that the computer can understand and it executes the code. Java Development Kit: Java Development Kit is a collection of classes, Java compiler and Java virtual machine Interpreter. It also consist useful utilities for debugging, documentation, compiling and run java programs. The following are the some components of a Java Development Kit. javac: The java compiler, converts java source code into byte code Syntax: javac filename.java java: The java interpreter, executes java application byte does directly from class file Syntax: java filename 4

jdb: The java debugger that allows to step through the program one line at a time, set break points, and examine variables Syntax: jdb filename servletrunner: A simple web server to test servlets appletviewer: A java interpreter that executes java applet classes hosted by HTML Syntax: appletviewer filename.html Java Virtual Machine (JVM): Java provides both compiler and a software machine called JVM for each computer machine. The Java Compiler translates the Java Source Code (Java program) into an intermediate code known as byte code, which executes on special type of machine. This machine is called Java Virtual Machine and exists only inside the computer memory. The byte code is machine independent code and can run in any system. Source code Java Compiler Byte code The byte code is not a machine specific code. Java Interpreter takes the byte code and translates it into its own system machine language and runs the results. Byte code Java Interpreter Machine code Just In Time (JIT): The Java Virtual Machine is an interpreter that translates and runs each byte code instruction separately whenever it is needed by the computer program. In some cases it is very slow. As an alternative, Java also provides local compiler for each system that will compile byte code file into executable code for faster running. Java calls these compilers Just In Time compilers. Java Standard Library(JSL): The Java API (Application Programming Interface) is a collection of classes and methods grouped in the form of packages. JDK 1.2 has 58 packages, it is also known as Java Standard Library. The important Packages in Java are a) java.lang: It contains the main language support class. It contains wrappers, strings and basic features of Java b) java.util: It provides classes that support date, time, basic event processing etc., c) java.io: It provides reading and writing data in the form of streams. d) java.awt: It provides classes for creating GUI programs. e) java.applet: It includes set of classes to support for applet programming. f) javax.swing: It provides classes for swing operation programming. Differences between C++ and Java 1. Java does not include structure and union. 2. It is not possible to declare unsigned integer in Java. 3. Pointers dont exist in Java. 4. Java does not have a preprocessor. 5. There are no header files and delete operators. 6. Java does not allow goto, sizeof and typedef. 7. Java does not support the multiple inheritance. Java Tokens: Tokens are smallest individual units in a program. The compiler reads the source program one character at a time grouping the source program into a sequence of atomic units called Tokens. Reserved words, identifiers, constants, operators etc., are the examples of Java Tokens. Keywords: The Keywords or Reserved words are one, which have a special and predefined meaning to the Java compiler. There are 48 reserved words currently used in Java. These words cannot be used as names for a variable, constant, class or method. Reserved words are abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null 5

Note: const and goto are reserved for future use. Java reserved words true, false and null reserved words are used to represent the values. Datatype: Datatypes are used to specify the type of data that a variable can attain. There are 2 types of datatypes. 1. Primitive Datatypes 2. Non-Primitive Datatypes 1. Primitive Datatype: It is also called as standard, intrinsic or built-in datatypes. There are eight primitive datatypes available in Java. Those are byte, short, int, long, char, float, double and boolean. These can be classified into four groups. Integers : byte, short, int, long Floating point numbers : float, double Characters : char Boolean : boolean Type Size Range Bits Bytes int 32 4 -2,147,483,648 to 2,147,483,647 long 64 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 short 16 2 -32,768 to 32,767 byte 8 1 -128 to 127 float 32 4 3.4 e 0.38 to 3.4 e +0.38 double 64 8 1.7 e 308 to 1.7 e +308 char 16 2 0 to 65535 boolean 8 1 true / false Note: 1. Java does not support have any unsigned types 2. Variables of types char, byte, short, int, long, float and double are all given the value 0 by default 3. Variable of type boolean are given false by default 4. All primitive datatypes in Java are portable (Platform independent) 2. Non-Primitive Datatype: These are also known as Derived Datatype or Abstract Datatype or Reference type. These are built on primitive data types. Examples: string, class, array, interface etc., Variable: The name given to the various elements to store the information is called an identifier or variable. The rules for variables are as follows: Variable must be begin with a letter, a dollar ($) symbol or an underscore ( _ ) followed by a sequence of letters Variable names must be unique There should be no space in between any two characters of an identifiers Keywords cannot be used for variable name Java is a case-sensitive, so upper and lower case letters are distinct Declaring a Variable: All variables must be declared before they can be used. The basic form of a variable declaration is Syntax: type identifier; Where type is represents datatype of the variable, identifier is the name of the variable. Example: int a; More than one variable of the same type can be declared by using a comma-separated list. Syntax: type identifier1, identifier2, , identifiern; Example: float x, y, z; Initializing a Variable: Variable can also be initialized with equal sign and a value. Syntax: type identifier = value; Example: int a = 3; Dynamic Initialization: Java allows variables to be initialized dynamically, using any expression valid at a time the variable is declared. Example: class dyna { public static void main(String args[]) 6

} Scope & Lift-time of a Variable: An identifier duration also called lifetime is the period during which that identifier exist in memory. Identifier that represent local variables in a method i.e., parameters and variables declared in the method body have automatic duration. Automatic declaration are created when program control reaches their declaration they exist while the block in which they are declare is active and they are destroyed when the block in which they are declared is exceeded. We will refer to variables of automatic duration has automatic variables or local variables. Java also has identifiers of static duration. Variables and references of static duration exist from the point at which the class that defines them is loaded into memory for execution until the program termination. Identifier scope is where the identifier can be a reference in a program. The scope of an identifier is class scope and block scope. Methods and instance variable of a class have class scope. Class scope begins at the beginning left brace of the class definition and ends at the closing right brace of the class definition. Identifiers declared inside a block have block scope. Block scope begins at the identifiers declaration and ends at the terminating right brace of the block. Local variables of the method have block scope. Class: A class is a non-primitive datatype that contains member variables (data) and member functions (methods) that operates on the variables. A class is declared by the use of the class keyword. The general form of class definition is as follows. Syntax: class class-name { datatype instance-variable1; datatype instance-variable2; datatype instance-variablen; datatype methodname1(parameter-list) { // method body } datatype methodnamem(parameter-list) { // method body } } The data, or variables defined with in a class are called instance variables. The code is present with in methods. Collection of methods and variables defined with in a class are called members of the class. Example: class box { double width, height, depth; double volume( ) { return width*height*depth; } }

double a=3.0, b=4.0; double c=Math.sqrt(a*a+b*b); System.out.println(Hypotenuse is + c); }

Object: Object is an instance of the class. By means of the object only, we can access the functions
(methods). 7

main( ) { box a = new box( ); a.volume(); } Comments in a Program: Three types of comment statements are available in Java. They are i) Single line comment (//) ii) Multi line comment (/* and */) iii) Documentation comment (/** and */) 1. Single line comment: For a single line comment we use double slash (//) to begin a comment. It ends at the end of line. Example: // Program for stack operations 2. Multi line comment: For more than one line of information, we use multi line comments. Multi line comments are starts with /* and ends with */. Example: /* Program for stack operations Designed by shabbir PBRVITS, Kavali */ 3. Documentation comment: For the documentation purpose, we use documentation comments. Documentation comments are starts with /** and ends with */. Example: /** A test for JDK

Input and Output Statements: java.lang package consists a class called System which contains
console I/O methods. If we want to take the information from the keyboard and display the information on the screen, Java uses Stream objects. The system provides three basic streams. Those are a) System.in b)System.out c)System.err System.in refers to the standard input stream, System.out refers to the standard output stream and System.err refers to the standard error stream. System.out class consists of two methods to print the strings and values on the screen. They are 1. print( ) 2. println( ). 1. print( ): Syntax: System.out.print(list); This statement prints the values of the variable name specified in the list of output unit. Example: System.out.print(hai); System.out.print(java); O/P: haijava 2. println( ): Syntax: System.out.println(list); This statement prints the values of the variable name in the list, the cursor is advanced by one line and the next statement is print in the next line. Example: System.out.print(hai); System.out.print(java); O/P: hai java Note: Java has a version of the + operator for string concatenation that enables a string and a value of another datatype. Example: sum = 50 sum is + sum Here, sum is automatically converted to a string and concatenated with the sum is which results in the string sum is 50 Example: y#2=+7 O/P: y#2=7 Command Line Arguments: Java has the facility of command line arguments. Java main method consists array of string objects. When we run the program, the array will fill with the values of any arguments it was given in the command line.

Building the Java Program:


8

Java is a text file that contains one or more class definitions. Java compiler requires that a source file use the .java file name extension. Example: class Example { public static void main(String[] args) { System.out.println("Hello"); } } The keyword class is used to declare the new class is being defined Example is an identifier that is the name of the class Entire class definition will be between the opening curly brace ({) and the closing curly brace (}) public keyword is an access specifier, which allows the programmer to control the visibility of class members The keyword static allows main() to be called without having to instantiate a particular instance of the class. Since, main() method is called by the Java interpreter before any objects are made The keyword void used to tell the compiler that main() does not return a value main() is a method called when a Java application begins String args[] declares a parameter named args, which is an array of instances of the class string. args receives any command line arguments present when the program is executed Now the file is saved with .java extension . Let the file name is taken as Example.java

Compiling & Running the Java Program:


To compile Example.java program by the compiler javac, specify the name of the source file on the command line as C:\> javac Example.java Here, the Java compiler creates a file called Example.class that contain byte code version of the program. The class file is run by the Java interpreter, called java by passing the name to command line argument as C:\> java Example O/P: Hello Example: Write a program to read two values and print the values class ex2 { public static void main(String[] args) { System.out.println(args[0]); System.out.println(args[1]); }} Primitive datatypes are to be converted into object type by using the wrapper classes. Integer class is used as wrapper class for primitive datatype int. parseInt( ) method converts string to an int. Example: Write a program to read two integer values and print the sum class ex3 { public static void main(String[] args) { int a,b,sum; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); sum=a+b; System.out.println("sum of a and b is"+sum); } }

OPERATORS
Operator is a symbol that performs a specified operation between the data items. Java provides the following different types of operators. a) Arithmetic operators: Operator Meaning 9

+ * / %

Addition Subtraction Multiplication Division Modulus

Example: class arope { public static void main(String[] args) { int a,b,sum,sub,mul,div,mod; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); sum=a+b; sub=a-b; mul=a*b; div=a/b; mod=a%b; System.out.println("Addition="+sum); System.out.println("Subtraction="+sub); System.out.println("Multiplication="+mul); System.out.println("Division="+div); System.out.println("Remainder="+mod); } } b) Arithmetic Assignment Operators: Syntax: variable operator = expression Which is equivalent to variable = variable operator expression Operator Example Equivalent Expression += a+=4 a=a+4 -= a-= 5 a=a5 *= a*=3 a=a*3 /= a/=8 a=a/8 %= a%=5 a=a%5 c) Assignment Operator: = is an assignment operator used to assign the value to a variable. Syntax: variable = value; Example: a = 7; d) Increment and Decrement Operators: ++ and --' are Javas increment and decrement operators. The increment operator increased its operand by one. The decrement operator decreased its operand by one. Example: class a { public static void main(String[] args) { int x=4; System.out.println("x++:"+ ++x); //O/P: 5 int y=10; System.out.println("x++:"+ y++); //O/P: 5 int p=5; int t=--p+3; System.out.println("t :"+t); //O/P: 7 } } e) Relational Operators: Relational Operators determines the relationship between the two operands. 10

Operator == != > < >= <=

Meaning equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to

Example A= =B A!=B A>B A<B A>=B A<=B

f) Logical Operators: Logical operators are used to check for compound conditions, which are formed, by the combination of two or more relational expressions. Java provides the following logical operators and these are follows truth tables and produce Boolean values. Operators: Logical AND && Logical OR || Logical NOT ! Truth table for Logical AND(&&): Op1 Op2 Op1 && Op2 T T T T F F F T F F F F Truth table for Logical OR(||): Op1 Op2 Op1 && Op2 T T T T F T F T T F F F Truth table for Logical NOT(!): Op1 !Op1 T F F T g) Conditional Operator: Java has a decision operator called conditional operator. ? : are conditional operators. These operators are also called ternary operators. Syntax: testconditon ? expression1 : expression2 Here, if the testcondition is true, then expression1 is evaluated otherwise, expression2 is evaluated. Example: max = (a>b) ? a : b; h) Bit-wise Operators: The following bit-wise operators are provided by Java. These operators act upon the individual bits on their operands. Operator Meaning ~ Bit-wise unary NOT & Bit-wise AND | Bit-wise OR ^ Bit-wise exclusive OR >> Shift right << Shift left |= Bit-wise OR Assignment ^= Bit-wise exclusive OR Assignment >>= Shift right Assignment <<= Shift left Assignment These operators act upon the individual bits on their operands. Bit-wise Logical Operators (&, |, ^ and ~) follows the following truth tables Op1 Op2 Op1|Op2 Op1&Op2 Op1^Op2 ~Op1 0 0 0 0 0 1 1 0 1 0 1 0 0 1 1 0 1 1 1 1 1 1 0 0 11

javax.swing: It is package contains an important class called JOptionPane class. This class is used to
display dialog boxes. It provides two important predefined methods showInputDialog and showMessageDialog called static methods. Such methods are always used their class name followed by a dot operator. ShowInputDialog: showInputDialog is a method of class JOptionPane. It is a static method and the general format is as Syntax: JOptionPane.showInputDialog(argument); The argument indicates to the user what to do in the text field. Example: JOptionPane.showInputDialog(Enter a value); When we perform this operation the input dialog box is available as Input

Enter a value OK cancel

The users types characters in the text field then clicks the ok button, it returns string to the program. showMessageDialog: showMessageDialog is method of class JOptionPane. It is a static method. The general format of showMessageDialog is in two ways. Syntax1: JOptionPane.showMessageDialog(null,argument1); The first argument must be null keyword. The second argument is the string that is required to display. The title bar of message dialog contains the string Message to indicate that the dialog is presenting a message to the user. The default icon is INFORMATION_MESSAGE. Example: JOptionPane.showMessageDialog(null,value=+x); Message

Value=10 OK

Syntax2: JOptionPane.showMessageDialog(null,argument2,argument3,argument4) The first argument must be null keyword. The second argument is the message to display. The third argument is the string to display in the title bar of the dialog. The fourth argument is a value indicating the type of message dialog to display. For argument4 some of the message dialogs are JOptionPane.PLAN_MESSAGE JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE Example:
JOptionPane.showMessageDialog(null,value=+x,output, JOptionPane.ERROR_MESSAGE)

output import statement: import statement is Value=10 the #include statement in C. Using the import similar to OK statements, we can access to classes that are part of other packages. Example: import javax.swing.JOptionPane; This statement instructs that the interpreter to load the JOptionPane class contained in the javax.swing package. Example: import javax.swing.JOptionPane; class ch 12

{ public static void main(String[] args) { String sn1; int x; sn1=JOptionPane.showInputDialog("Enter x value"); x=Integer.parseInt(sn1); JOptionPane.showMessageDialog(null,"value="+x,"output",JOptionPane.ERROR_MESSAGE); }}

Control Statements
Depending on the results of computations the flow of control may require to jump from one part of the program to another part, such jumps are called Control statements. The control statements are of two categories. 1)Decision (Conditional) control statements 2)Loop control statements 3)Jump control statements 1. Decision (Condition) Control statements: In decision control statements, depending on the result of evaluation of an expression a statement or block of statements are executed. The condition involves boolean values either true or false. Java provides the following decision control statements. a)if statement b)if-else statement c)nested if-else statement d)switch a) if statement: The if statement conditionally process the statements when the specified test condition is true. Syntax: if(condition) { // Block of statements } Flowchart:
Conditi on

Block of statements

Next statements Here, if the condition is true then block of statements are executed. Otherwise, block of statements are not executed and the control is passed to the next statements available after the block statements. The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces. Example: class if1 { public static void main(String[] args) { int a=6,b=4; if(a>b) System.out.println("a is big"); }} b) if-else statement: In if-else statement general form is as Syntax: if (condition) { //true block statements } else { //false block statements 13

} Flowchart: Co ndi tio n true block statements

false block statements

Next statements Here, first the test condition is evaluated. If the condition is true, then true block statements are executed otherwise false block statements are executed. The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces. Example: class if2 { public static void main(String[] args) { int a=2,b=4; if(a>b) System.out.println("a is big"); else System.out.println("b is big"); } } c) Nested if-else statement: The if-else statement is placed within another if-else statement such methods are called nested if-else statement. Syntax: if (condition1) { else if(condition2) { //block1 statements } else { //block2 statements } } else { //block3 statements } Lab Program1: Write a program to print the roots of a quadratic equation ax2+bx+c=0 import javax.swing.JOptionPane; import java.text.DecimalFormat; class lab1 { public static void main(String[] args) { double a,b,c,dis,root1,root2,p; 14

DecimalFormat d=new DecimalFormat("0.00"); a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value")); b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value")); c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value")); dis=(b*b-4*a*c); if(dis==0) { System.out.println("Roots are real and equal"); root1=-b/(2*a); System.out.println("Root1="+(d.format(root1))); System.out.println("Root2="+(d.format(root1))); } else if(dis>0) { System.out.println("Roots are real and different"); p=Math.sqrt(dis); root1=(-b+p)/(2*a); root2=(-b-p)/(2*a); System.out.println("Root1="+(d.format(root1))); System.out.println("Root2="+(d.format(root2))); } else System.out.println("Roots are imaginary"); } } d) switch statement: The switch statement allows section among the multiple section of a code depending on the value of an expression. The objective is to check several possible constant values for an expression. Syntax: switch (expression) { case value1: block1 statements break; case value2: block2 statements break; | default: default block statements } exp ress ion Flowchart: block1 statements Block2 statements default block1statements First, the switch statement evaluates the expression and check whether the evaluated value is Next statements coinciding with any case value or not. If any value is coinciding, it executes that particular block of statements until the break statement is reached. After executing the statements the control is transferred out of the statements that are available after the switch statement. If any value is not coinciding with the case value then it executes default block statements. Default block is an optional. Note: case values are either integer constant or character constant. Example: 15

class if4 { public static void main(String[] args) { int rno; rno=Integer.parseInt(args[0]); switch(rno) { case 1:System.out.println("RED"); break; case 2:System.out.println("GREEN"); break; case 3:System.out.println("BLUE"); break; default:System.out.println("Select 1,2 or 3 only"); } } } Example: class if5 { public static void main(String[] args) { char rno='t'; switch(rno) { case 'a':System.out.println("RED"); break; case 'b':System.out.println("GREEN"); break; case 'c':System.out.println("BLUE"); break; default:System.out.println("Select 1,2 or 3 only"); } } } 2. Loop Control Statements: A Loop statement allows to run a statement or block of statements repeatedly for a certain number of times. The repetition is continues while the condition is true. When the condition becomes false, then loop ends and control passed to the next statements following the loop. Repetitive execution of statements is called looping. Java provides three types of loop control statements. a) while statement b) do-while statement c) for statement a) while statement: while loop executes the statements repeatedly as long as a given condition becomes true. When the condition becomes false the control immediately pass to the next statements available after the loop statements. Syntax: while (condition) { //statements } Flowchart:

cond ition

statements

Next statements 16

The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces. Lab Program2: Write a program to print the first n fibonacci sequence numbers class lab2 { public static void main(String[] args) { int f0=1,f1=1,i=3,f2,n; n=Integer.parseInt(args[0]); System.out.println(f0); System.out.println(f1); while(i<=n) { f2=f0+f1; System.out.println(f2); f0=f1; f1=f2; i++; } } } b) do-while statement: In do-while loop statements, first the control executes the statements then it checks for the condition. The statements are executed repeatedly as long as a given condition becomes true. If the condition becomes false then the control comes out from the loop and executes the statements available after the loop statements. Syntax: do { //statements } while (condition); Flowchart: statements condition

Next statements The statements are either simple or compound statements. If the statements are single statement then they ended with a semicolon. If the statements are compound statements then they are placed in between the left and right curly braces. The main difference between while and do-while statement is dowhile statement executes the statements at least once even the condition becomes false. Example: Write a program to check whether a given number is Armstrong number (153) or not class labd { public static void main(String[] args) { int x,n,temp,sum=0; n=Integer.parseInt(args[0]); temp=n; 17

do { x=n%10; sum=sum+x*x*x; n=n/10; }while(n>0); if(sum==temp) System.out.println("Number is armstrong"); else System.out.println("Number is not armstrong"); } } c) for statement: The for statement also repeat a statement or compound statements for a specified number of times. The general form of for statement is as Syntax: for (initialization;condition;increment/decrement) { //statements } Flowchart: initializat ion condit ion statement s Next statements

Initialization is the start with the assigning value to the variable and it executes only once at the start of the loop. Then the control checks for the test condition. In condition section, if the condition becomes true then the control pass to the block of statements and executed. After executing the statements the control pass to the increment/decrement section. After incrementing/decrementing the variable again the control is passed to the condition section. This procedure is repeated as long as the condition becomes true. If the condition becomes false, the control passes out of the loop statements. Note: 1. Multiple initializations are possible by comma operator. Ex: for( i = 0,j = 5; i<n; i++, j--) 2. At the place of condition section, it is also possible to use relational expressions Example: Lab Program3: To print all prime numbers between a given range import javax.swing.JOptionPane; class lab3 { public static void main(String[] args) { int n,j,x,count; //n=Integer.parseInt(args[0]); n=Integer.parseInt(JOptionPane.showInputDialog("Enter range")); for(int i=1;i<=n;i++) { x=i; count=0; j=2; while(j<x) { if(x%j==0) { 18

count=1; break; } j++; } if(count==0) System.out.println(x+"is prime"); } } }

3. Jump Control Statements: Java provides the following Jump Control statements.
a) break statement b)continue statement c)return statement d)exit statement a) break statement: break statement executed in a while, do-while, for or switch statements causes immediate exist from that structure. It can be used in two ways as unlabeled break and labeled break statement. Unlabeled break statement: Syntax: break; Example: for(int k=1;k<=10;k++) { if(k= =5) break; System.out.println(k); } O/P: 1234 Labeled break statement: To break out of nested structures, we can use the labeled break statements. This statement, when executed in a while, do-while and for statements causes immediate exit from that structure and any number of enclosing repetition structures. Program execution resumes with the first statement after the enclosing labeled compound statement. Example: class ex { public static void main(String[] args) { stop: { for(int row=1;row<=10;row++) { for(int col=1;col<=5;col++) { if(row==3) break stop; System.out.print("* "); } .out.println("\n"); } O/P: ***** } ***** } } b) continue statement: continue statement executed in a while, do-while or for statements skip the remaining statements in the body of that structure and proceeds with the next iteration of the loop. It can be used in two ways as unlabeled continue and labeled continue statement. Unlabeled continue statement: Syntax: continue; Example: for(int k=1;k<=10;k++) { if(k= =5) 19

continue; System.out.println(k); } O/P: 1 2 3 4 6 7 8 9 10 Labeled continue statement: The labeled continue statement when executed in a repetition structure skips the remaining statements in that structure body and any number of enclosing repetition on structure and proceeds with the next iteration of an enclosed labeled repetition. Example: class ex { public static void main(String[] args) { stop: for(int row=1;row<=4;row++) { for(int col=1;col<=3;col++) { if(col==2) continue stop; System.out.print(col); } System.out.println("\n"); } } } O/P: 1111 c) return statement: The return statement is used to explicitly return from a method. This causes program control to transfer back to the caller of the method. The return statement immediately terminates the method in which it executes. Syntax: return; d) exit statement: The method exit( ) is defined in System package. The purpose of exit is to terminate the program with a specific exit code. Syntax: System.exit(exit_code); The program finish normally by placing exit_code as 0 other value means error. Example: System.exit(0);

Arrays
An Array is a group of contiguous or related data items that share a common name. A particular value is indicated by writing a number called index number or subscript in square bracket after the array name. Arrays are classified into different types. They are 1)One-Dimensional Array 2)Two-Dimensional Array 3)Multi-Dimensional Array One-Dimensional Array: One-Dimensional Array is a list of homogenious items can be given one variable name using only one subscript. Individual value of an array is called an element. Like an ordinary variable, arrays must be declared and created in the computer memory before they are used. Creation of an array contains two sections. They are 1. Declaration of the array 2. Creating memory locations. Syntax: type arrayname[ ]; // declaration arrayname = new type[size]; // allocation of memory (or) type arrayname[ ]=new type[size]; Where, type defines the datatype of the variables stored in the array arrayname defines the name of the array new operator is used to allocate dynamic memory in the computer for the array size defines the number of memory location of the array Example: int number[]; number = new int[5]; It can also be initialize arrays automatically when they are declared. The syntax is as 20

Syntax: type arrayname[]={list of values}; Where, list of values contains number of values separated by commas and surrounded by curly braces Example: type number[]={35,40,56,23}; In Java, all arrays store the allocated size in a variable named length. We can access the length of the array using the syntax Syntax: arrayname.length; Example 1: Write a program to read 5 numbers and print the sum of it. class arr1 { public static void main(String[] args) { int sum=0; int no[]=new int[10]; for(int i=0;i<5;i++) { no[i]=Integer.parseInt(args[i]); sum=sum+no[i]; } System.out.println("Total="+sum); } } Example 2: Write a program to sort the list of values in ascending order class arr1 { public static void main(String[] args) { int temp; int no[]={34,78,23,11,99}; for(int i=0;i<no.length-1;i++) { for(int j=i+1;j<no.length;j++) { if(no[i]>no[j]) { temp=no[i]; no[i]=no[j]; no[j]=temp; } } } for(int i=0;i<no.length;i++) System.out.println(no[i]); } } Two-Dimensional Array: A Two-Dimensional Array is a collection of homogeneous data items that share a common name using two subscripts. It stores table of data. This representation is very useful for matrix representations as first subscript represents the number of rows and second subscript represents the number of columns. Syntax: type arrayname[][]; // declaration arrayname = new type[size1][size2]; // allocation of memory (or) type arrayname[ ][]=new type[size1][size2]; Where, type defines the datatype of the variables stored in the array arrayname defines the name of the array new operator is used to allocate dynamic memory in the computer for the array size1 defines the number of rows of memory location of the array size2 defines the number of columns of memory location of the array Example: int number[][]; number = new int[5][6]; 21

It can also be initialize arrays automatically when they are declared. The syntax is as Syntax: type arrayname[][]={list of values}; Or type arrayname[][]={{row1 values}, {row2 values}, .. } Lab Program 6: Java program to multiply two matrices import javax.swing.JOptionPane; class arr2 { public static void main(String[] args) { int m,n,p,q,i,j,k; int a[][]=new int [10][10]; int b[][]=new int [10][10]; int c[][]=new int [10][10]; m=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix A")); n=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of Matrix A")); p=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix B")); q=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of Matrix B")); if(n==p) { for(i=0;i<m;i++) { for(j=0;j<n;j++) a[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter a["+i+"]["+j+"]:"));} for(i=0;i<p;i++) { for(j=0;j<q;j++) b[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter b["+i+"]["+j+"]:")); } for(i=0;i<m;i++) { for(j=0;j<q;j++) { c[i][j]=0; for(k=0;k<n;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } for(i=0;i<m;i++) { System.out.println(); for(j=0;j<q;j++) System.out.print(" "+c[i][j]); } } else { JOptionPane.showMessageDialog(null,"Multiplication not possible"); } }} Multi-Dimensional Array: Multi-Dimensional Array is a list of values shared by a common name using multi subscripts. If the array contains three subscripts then the array is called as Three-Dimensional array and so on. Syntax: type arrayname[][][]=new int[size1][size2][sizen]; Example: type number[][][]=new int[4][5][6];

Type conversion and Casting:


Java permits mixing of constants and variables of different types, but during execution it follows type conversions. In Java, type casting can be done in two ways. They are 1. Implicit Type Casting 2. Explicit Type Casting 1. Implicit Type Casting: In an expression, if the operands are of different types the lower type is automatically converted to the higher type before the operation preceeds by the Java Interpreter. The result 22

is of the higher type. Such type of casting is called Implicit Type Casting. In Implicit Type Casting there is no loss of data. The following are some of implicit type castings with no loss of data

from

to

byte short, char, int, long, float, double short char, int, long, float, double char int, long, float, double int long, float, double long float, double float double 2. Explicit Type Casting: If we want to force to convert the operands of an expression from one type to another type depending on user choice, such type of casting is called Explicit Type Casting. In Explicit Type Casting there is a chance of data loss when we convert the operands from higher type to lower type. The process of converting the value is known as Casting a value. The general form of casting is as Syntax: (datatype) expression; Example: x = (int) 7.5; Note: The final result of an expression is converted to the type of the variable before assigning to the left hand side variable. In such case following chances are introduced. float to int causes truncation of the fractional part double to float causes rounding of digits long to int causes dropping of the excess of higher order bits **

Unit II
Class: A class is a non-primitive datatype that contains member variables (data) and member functions
(methods) that operates on the variables. A class is declared by the use of the class keyword. The general form of class definition is as follows. Syntax: class class-name { datatype instance-variable1; datatype instance-variable2; datatype instance-variablen; datatype methodname1(parameter-list) { // method body } datatype methodnamem(parameter-list) { // method body } } The data, or variables defined with in a class are called instance variables. The code is present with in methods. Collection of methods and variables defined with in a class are called members of the class. Example: class box { double width, height, depth; double volume( ) { return width*height*depth; } 23

Creating Objects: An Object in Java is a block of memory that contains space to store all the instance
variables. Creating an object of a class is a two-step process. 1. Declare a variable of the class type. At this stage, the variable refers to an object only. 2. Assigning an actual, physical copy of the object and assign it to that variable by means of new operator. The new operator dynamically allocates memory for an object and returns a reference to that object. Example: Rectangle rect1; // reference rect1 = new Rectangle(); // instantiate (or) Rectangle rect1 = new Rectangle(); The first statement declares a variable to hold the object reference. null rect1 The second statement assigns the object reference and allocates memory rect1 Rectangle object

Note: Each object contains its own instance variables of its class. This means that any changes to the variables of one object have no effect on the variables of another. But the function name is name for both objects. It is also possible to create two or more references to the same object. Example: Rectangle r1 = new Rectangle( ); Rectangle r2 = r1; r1 r2 Rectangle object

Methods: Methods allows the programmer to modularize a program. All variables declared in method
definition are local variables and method parameters are also local variables. All methods must define inside a class definition. The general form of a method is as Syntax: type method-name (parameter-list) { // body of the method } where, type specifies the type of data returned by the method. If the method does not return any value, its return type must be void The method-name is a valid identifier parameter-list is a sequence of type and identifier pairs separated by commas. The variable receives the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty body of the method describes the operations to be performed on the data Example: int sum(int a, int b) { int c; c=a+b; return c; } 24

Accessing class members:

All variables must be assigned values before they are used in our program. All class members are accessed by means of dot operator. The general format of accessing instance variable of the class by dot operator is as Syntax: objectname.variablename; Where, objectname is name of the object, variablename is the name of the instance variable. Example: rect1.length=15; rect1.width=10; rect1 15 10 rect1.length rect1.width

The general format of accessing instance methods of the class by dot operator is as Syntax: objectname.methodname(parameter-list); Where, objectname is name of the object, methodname is the name of the instance method that calls with the object and paramerter-list is a list of actual values separated by commas. Example: void getdata(int x, int y) { length=x; width=y; } rect1.getdata(10,20); // Write a program to calculate the area of a rectangle. class Rectangle { int length1,width1; void getdata(int x,int y) { length1=x;width1=y; } int calarea() { int area=length1*width1; return area; } } class prg { public static void main(String[] args) { int a,b; Rectangle rect1=new Rectangle(); Rectangle rect2=new Rectangle(); rect1.length1=15; rect1.width1=4; a=rect1.length1*rect1.width1; System.out.println("Area of Rectangle1="+a); rect2.getdata(2,3); b=rect2.calarea(); System.out.println("Area of Rectangle2="+b); } }

Method Overloading: In Java it is possible to define two or more methods within the same class that
share the same name as long as these methods have different sets of parameters (Based on the number of parameters, the types of the parameters and the order of the parameters). Then the methods are said to be overloaded, and the process is referred as Method Overloading. 25

When the overload method is called the Java compiler selects the proper method by examine the number, type and order of the arguments in the call. Method Overloading is commonly used to create several methods with same name that perform fast accessing. Note: Two methods differ in only by return type will result in a syntax error. Example1: class overload { int square(int x) { return x*x; } double square(double x) { return x*x; } } class check { public static void main(String[] args) { overload r1=new overload(); int k=r1.square(3); double p=r1.square(4.0); System.out.println("k value="+k); System.out.println("p value="+p); } } Example2: class overload1 { int sum(int x) { return x+x; } int sum(int x,int y,int z) { return x+y+z; } } class check1 { public static void main(String[] args) { overload1 r1=new overload1(); int k=r1.sum(3,5,7); System.out.println("k value="+k); } }

Constructors: A constructor is a special method of class, which is invoked automatically, whenever an


object of a class is created. It has the same name as its class and resides similar to a method. A constructor has the following characteristics. It doesnt have any return type not even void The constructor can be declared as public 26

It can be overloaded It is normally used to initialize the member of the object Different types of Constructors: 1) Default Constructor: A constructor that accepts no parameters is called the default constructor. If no constructors are defined for a class, the Java system automatically generates the default constructor. Example: class Time1 { int hour,min,sec; public Time1() { hour=10; min=45; sec=23; } void printdata() { System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds"); } } class const1 { public static void main(String[] args) { Time1 t=new Time1(); t.printdata(); } } O/P: 10hours:45minutes:23seconds 2) Parameterized Constructor: A constructor that takes arguments as parameters is called parameterized constructor. If any constructors are defined by a class with the parameters, Java will not create a default constructor for the class. Example: class Time1 { int hour,min,sec; public Time1(int h,int m,int s) { hour=h; min=m; sec=s; } void printdata() { System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds"); } } class const2 { public static void main(String[] args) { Time1 t=new Time1(10,9,4); t.printdata(); } } O/P: 10hours:9minutes:4seconds

Constructor Overloading: An interesting feature of the constructor is that a class can have multiple
constructors. This is called Constructor Overloading. All the constructors have the same name as corresponding to the class name that they are differ only interms of their signature as number of arguments or datatypes or order. 27

Example: class Time1 { int hour,min,sec; public Time1() { hour=0; min=0; sec=0; } public Time1(int h) { hour=h; min=0; sec=0; } public Time1(int h, int m) { hour=h; min=m; sec=0; } public Time1(int h,int m,int s) { hour=h; min=m; sec=s; } void printdata() { System.out.println(hour+"hours:"+min+"minute:"+sec+"sec"); } } class const3 { public static void main(String[] args) { Time1 t=new Time1(); t.printdata(); Time1 t1=new Time1(9); t1.printdata(); Time1 t2=new Time1(7,8); t2.printdata(); Time1 t3=new Time1(10,9,4); t3.printdata(); } } Static Class Members: Generally each class contains instance variables and instance methods. Every time the class is instantiated, a new copy of each of them is created. They are accessed using the objects with the dot operator. If we define a member that is common to all the objects and accessed without using a particular object i.e., the member belong to the class as a whole rather than the objects created from the class. Such facility can be possible by using static keyword. The members declared with the static keyword are called static members. Example: static int x; static int show(int x,int y); The important points about static class members are Static members can be accessible without the help of objects. It can be accessible by using the syntax: classname.members; A static method can access only static members (data + method) 28

A static block will be executed first (before main). Static variables are initialized first A static member data store the same memory for all objects Static method cannot be referred to this or super in anyway. Example1: class static1 { static int c=0; void increment() { c++; } void display() { System.out.println("Value="+c); } } class Mstatic { public static void main(String[] args) { static1 s=new static1(); static1 s1=new static1(); static1 s2=new static1(); s.increment(); s1.increment(); s2.increment(); s.display(); s1.display(); s2.display(); } } O/P: value=3 value=3 value=3 without static keyword 0 s1 0 0 s2 0 s3

with static keyword

s1 s2 s3 Example2: class static1 { static int a=10; static int b=34; static void call() { System.out.println("Value1="+a); }} class Mstatic1 { public static void main(String[] args) { 29

static1.call(); System.out.println("Value2="+static1.b); } } O/P: Value1=10 Value2=34 Example3: class static2 { static int a=10,b; static void method(int x) { System.out.println("x="+x); System.out.println("a="+a); System.out.println("b="+b); } static { System.out.println("static block"); b=a*4; } } class Mstatic2 { public static void main(String[] args) { static2.method(35); } } O/P: static block x=35 a=10 b=40

Access Modifiers/Control:
Java provides four types of Access Modifiers. They are public, protected, default and private. Access Location public protected friendly or default private Same class Y Y Y Y Sub class in same package Y Y Y N Other classes in same package Y Y Y Y Sub classes in other packages Y Y N N Non-sub classes in other Y N N N packages For good programming technique place member data as private and member functions as public. Example: class modi { private int k=6; void display() { System.out.println("k in display="+k); } } class ex { public static void main(String[] args) 30

{ modi obj=new modi(); obj.display(); //System.out.println("k in main="+obj.k); //this statement provides error since private variable //can not be possible to access by other class } }

this keyword: Java define this keyword, that can be used inside any method to refer the current object.
this is always a reference to the object on which method was invoked. this reference is implicitly used to refer to both the instance variables and methods of current object. Example 1: class Box { int len,dep,hei; Box(int len,int dep, int hei) { this.len=len; this.dep=dep; this.hei=hei; } int volume() { return len*dep*hei; }} class this1 { public static void main(String[] args) { Box obj=new Box(1,2,3); int x=obj.volume(); System.out.println("volume="+x); }} O/P: olume=6 this reference is also used explicitly refer to the instance variables. Example 2: class Box { int len=10; void method() { int len=40; System.out.println("local value="+len); System.out.println("Instance value="+this.len); } } class this2 { public static void main(String[] args) O/P: local value=40 { Instance value=10 Box obj=new Box(); obj.method(); }} Argument Passing: Arguments passed to a sub-routine (method) is falls into two categories. 1. Call by value 2. Call by reference 31

1. Call by Value: Call by value copies the value of an argument into the formal parameter of the subroutine. Therefore, if changes made to the parameter of the sub-routine have no effect on the argument used to call it. Example: class Test { void meth(int i, int j) { i*=2; j/=2; } } class cbv { public static void main(String[] args) { Test obj=new Test(); int a=4,b=7; System.out.println("Before calling a="+a+" b="+b); obj.meth(a,b); System.out.println("After calling a="+a+" b="+b); } } O/P: Before calling a=4 b=7 After calling a=4 b=7 2. Call by Reference: In this method, a reference to an argument is passed to the parameter. Inside the parameter, this reference is used to access the actual argument specified in the call. Therefore, any changes made to the parameter will effect the argument used to call it. This one is also referred as passing an object as parameter to a method. Example: class Test { int a,b; Test(int i,int j) { a=i; b=j; } O/P: Before calling a=4 b=5 void meth(Test ox) After calling a=8 b=2 { ox.a*=2; ox.b/=2; } } class cbr { public static void main(String[] args) { Test obj=new Test(4,5); System.out.println("Before calling a="+obj.a+" b="+obj.b); obj.meth(obj); System.out.println("After calling a="+obj.a+" b="+obj.b); } }

Recursion: A recursive method is a method that calls itself either directly or indirectly through another
method. A method call itself is termed as Recursion. Example: fact(n) = 1 ; if n=0 32

n*fact(n-1) ; n 1 // Write a program to print the factorial of a given number using recursion class a { double fact(double x) { if(x==0) return 1; else return x*fact(x-1); } } class recur { public static void main(String[] args) { a obj=new a(); int p=Integer.parseInt(args[0]); double t=obj.fact(p); System.out.println("facatorial="+t); } } // Write a program to print the first n Fibonacci sequence numbers using recursion (Lab Program: 2) class a { int f(int x) { if(x==0||x==1) return x; else return (f(x-1)+f(x-2)); } } class fibo { public static void main(String[] args) { a obj=new a(); int p=Integer.parseInt(args[0]); for(int i=1;i<=p;i++) { int t=obj.f(i); System.out.println(" "+t); } }} // Write a program to print the sum of n numbers using the recursive formula sum (n) = 0 ; if n = 0 n + sum(n-1) ; if n 1 Random Number Generation: The elements of change can be introduced through the random method. Consider the following statement double value = Math.random( ); The random( ) method generates a double value from 0.0 to 1.0(not included). The range of values produced directly by random is often different than what is needed in a specific application. Example: A program that stimulates rolling six-sided die would required random integers in the range (1,6) 33

The general formula for this type of problems using random method is a+(int)(Math.random( )*b). Where a is a shifting value that is equal to the fist number in the range of integers and b is the scaling factor that is equal to the width of range of the integer. class random { public static void main(String[] args) { for(int i=1;i<=20;i++) { int s=1+(int)(Math.random()*6); System.out.print(s); if(i%5==0) System.out.print("\n"); } } }

Recursion Vs Iteration: Recursion

Iteration

1. Recursion uses a selection structure like 1. Iteration uses a repetitive structure if, if-else etc., like while, do-while etc., 2. Recursion terminates when base case is 2. Iteration terminates when the loop recognized Continuation condition fails 3. It can occur infinitely 3. It can occur infinitely 4. Extra memory is required 4. Extra memory is not required Nested Class and Inner Classes It is possible to define a class within another class such classes are known as nested classes. A nested class has access to all of the variables and methods of its outer class. But the outer class doesnt access the variables and methods of nested class. Since the scope of a nested class is bounded by the scope of its enclosing class. There are two types of nested classes: static and non-static A static nested class is a class started with static modifier. Due to the static it must access the members of its enclosing class through an object. Direct access cannot be possible. A non-static class is a class as ordinary representation of class. The most important type of the non-static class is Inner class. The inner class has access to all of the variables and methods of its outer class. Thus, inner class scope is fully within the scope of its outer class. Example: class outer { int out_x=34; void test() { inner in=new inner(); in.display(); } class inner { void display() { System.out.println("value="+out_x); } } } class test { public static void main(String[] args) 34

{ outer y=new outer(); y.test(); } }

Strings
A string is a collection of characters. Java implements strings as object type of String. Java provides three types of string handling classes. 1.String Class 2.StringBuffer Class 3.StringTokenizer Class String and StringBuffer classes are defined in java.lang pacakage. StringTokenizer are defined in java.util package.

1. String Class:
A string is an object of class String. String literals or constants written as a sequence of characters in double quotes. A string may be assigned in declaration to string reference as String color = blue It initializes string reference color to refer the anonymous string object blue. Note: 1. Once we create a string object, we cannot change the contents of string instance. 2. A variable declared as a string reference can be changed at any time. String Constructors: String class provides several types of constructors. They are a) String( ): It creates an empty string with no characters in it. b) String(String): It takes one String as a parameter. c) String(StringBuffer): Allocates a new string that contains the sequence of characters currently contained in the string buffer argument. d) String(byte[] bytes): Construct a new String by converting the specified array of bytes using the platform's default character encoding. e) String(bytes byte[], int startindex, int numberofcharacters): Allocates new string positioned with the startindex by counting the number of charactes. f) String(char chars[]): Creates a string initialized by an array of characters. g) String(char chars[], int startindex, int numberofcharacters): Creates a string initialized by an array of characters with the startindex by counting the number of charactes.

Methods: 1. int length( ): It returns the number of characters in a given string.


String s1=new String(hello); System.out.println(s1.length()); class len { public static void main(String[] args) { String s1=new String("hello"); System.out.println(s1.length()); } } 2. char charAt(int where): It returns the character at the specified location. where must be a nonnegative specified location within the string. The first element of a string is considered to be at position zero. Example: class pos { public static void main(String[] args) { String s1=new String("hello java"); char c=s1.charAt(7); System.out.println("character="+c); }} 3. void getChars(int sourcestart, int sourceend, char target[], int targetstart): It extracts more than one character at a time and copy the characters of the string into a character array. 35 Example:

The first argument is the starting index from which characters are copied in the string. The second argument is the index that is one part of the last character to be copied from the string. The third argument is the array into which the characters are copied. The last argument is the starting index where the copied characters are placed in the character array. Example: class get { public static void main(String[] args) { String s1="java programming language"; char c[]=new char[10]; s1.getChars(3,8,c,0); for(int i=0;i<(8-3);i++) System.out.print(c[i]); } } O/P: a prog 4. boolean equals( ): It compares the two strings and returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. Syntax: boolean equals(Object string); Example: class equal { public static void main(String[] args) { String s1=new String("india"); String s2=s1; if(s1.equals(s2)) System.out.println("Strings are Equal"); else System.out.println("Strings are not Equal"); } } 5. boolean equalsIgnoreCase( ): It compares the two strings and returns true if the strings contain the same characters in the same order, and false otherwise by ignoring the case characters. Syntax: boolean equalsIgnoreCase(String str); Example: class equall { public static void main(String[] args) { String s1=new String("india"); String s2=new String(InDia); if(s1.equalsIgnoreCase(s2)) System.out.println("Strings are Equal"); else System.out.println("Strings are not Equal"); } } 6. int compareTo(String str ): It returns 0 if the two strings are equal. Negative number if the invoking string is less than str and postivite number if the invoking string is greater than str that is passed as an argument. The comparision is case-sensitive. Example: class comp 36

{ public static void main(String[] args) { String s1=new String("hello"); String s2=new String("india"); if((s1.compareTo(s2))>0) System.out.println("S1 is greater than s2"); else if((s1.compareTo(s2))<0) System.out.println("S2 is greater than s1"); else System.out.println("Two stings are equal"); } } O/P: S2 is greater than s1 If we want to ignore case differences when comparing two strings, we use the syntax of the form: int compareToIgnoreCase(String str) This method was added by Java 2. 7. regionMatches( ): It compares a specific region inside a string with another specific region in another string. It follows two methods. 1. boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numchars) 2. boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numchars) The first argument is the starting index of the string that invokes the method. The second argument is a comparison string. The third argument is starting index in the comparison string. The last argument is the number of characters to compare between the two strings. IgnoreCase is true the method ignores the case of the objects being compared. Example 1: class rmatch1 { public static void main(String[] args) { String s1=new String("happy birthday"); String s2=new String("Happy birthday"); if(s1.regionMatches(0,s2,0,5)) System.out.println("Match"); else System.out.println("Not Match"); } } Example 2: class rmatch1 { public static void main(String[] args) { String s1=new String("happy birthday"); String s2=new String("Happy birthday"); if(s1.regionMatches(true,0,s2,0,5)) System.out.println("Match"); else System.out.println("Not Match"); } } 8. int indexOf(int ch): 37

int indexOf(String str): int indexOf(char ch): It search for the first occurrence of a character. If the character is found the index of that characters in the string is returned. Otherwise, it returns -1. Example: class index { public static void main(String[] args) { String letter=new String("Java programming language"); System.out.println(letter.indexOf('v')); //O/P: 2 System.out.println(letter.indexOf("programming")); //O/P: 5 System.out.println(letter.indexOf('A')); //O/P: -1 } } 9. int indexOf(int ch, int startIndex): int indexOf(String ch, int startIndex): int indexOf(char ch, int startIndex): It searches the occurrence of character from the startIndex argument. Example: class indexof { public static void main(String[] args) { String letter=new String("Java programming language"); System.out.println(letter.indexOf('m',2)); //O/P: 11 } } 10. int lastIndexOf(int ch): int lastIndexOf(char ch): int lastIndexOf(String ch): It searches the last occurrence of the character. The search is performed from the end of the string towards the beginning of the string. If the character is found the index of that character in the string is return. Otherwise, it returns -1. Example: class lindexof { public static void main(String[] args) { String letter=new String("Java programming language"); System.out.println(letter.lastIndexOf('n')); //O/P: 19 System.out.println(letter.lastIndexOf("language")); //O/P: 17 } } 11. int lastIndexOf(int ch, int startIndex): int lastIndexOf(String ch, int startIndex): int lastIndexOf(char ch, int startIndex): It searches the last occurrence of the character starting with the startIndex to search the string from ending to the beginning. Example: class lindexof { public static void main(String[] args) { String letter=new String("Java programming language"); System.out.println(letter.lastIndexOf('n',11)); //O/P: -1 }} 12. String substring(int startIndex): It returns a copy of the sub string that begins that startIndex and return to the end of the invoking string. 38

Example: class sub { public static void main(String[] args) { String s=new String("Java programming language"); System.out.println(s.substring(8)); } } O/P: gramming language 13. String substring(int startIndex, int endIndex): It returns all the characters from the beginning index upto but not including the ending index. Example: class s13 { public static void main(String[] args) { String s=new String("program"); System.out.println(s.substring(2,5)); //O/P: ogr } } 14. boolean startsWith(String str): boolean endsWith(String str): The startsWith( ) method determines whether a given string begins with a specified string or not. Conversely, endsWith( ) method determines whether string ends with a specified string or not. Example: class s14 { public static void main(String[] args) { String s=new String("Java is a program"); if(s.startsWith("is")) System.out.println("Match"); else System.out.println("Not Match"); } } //O/P: Not Match 15. String concat(String str): It concatenates two string objects. Example: class s15 { public static void main(String[] args) { String s=new String("Java "); String s1=s.concat("program"); System.out.println(s1); } } O/P: Java program 16. String replace(char original, char replacement): It replace all characters of one character in the invoking string with another character. Example: class s16 39

{ public static void main(String[] args) { String s="Hello"; System.out.println(s.replace('l','w')); }

//O/P: Hewwo

} 17. String toLowerCase(): It converts all uppercase characters into lowercase characters of a string. Example: class s17 { public static void main(String[] args) { String s="HELLO"; System.out.println(s.toLowerCase()); //O/P: hello } } 18. String toUpperCase():It converts all lowercase characters into uppercase characters of a string. Example: class s17 { public static void main(String[] args) { String s="hello"; System.out.println(s.toUpperCase()); //O/P: HELLO } } 19. String trim(): It returns a copy of the invoking string from which any leading and lining white space has been removed. Example: class s18 { public static void main(String[] args) { String s=" hello"; System.out.println(s.trim()); } } 20. char[] toCharArray(): It returns a character array containing a copy of the characters in a string. Example: class s20 { public static void main(String[] args) { String s="hello"; char ch[]=s.toCharArray(); for(int i=0;i<ch.length;i++) System.out.println(ch[i]); } }

21. String toString(): It converts all objects into strings objects. Example: 40

class s21 { public static void main(String[] args) { Integer i=new Integer(10); System.out.println(i.toString()); //O/P: 10 } } LabProgram 5: Write a program to sort the list of names in ascending order. class lab5 { public static void main(String[] args) { String ch[]={"india","hai","andhra"}; String temp; for(int i=0;i<ch.length-1;i++) { for (int j=i+1;j<ch.length;j++) { if((ch[i].compareTo(ch[j]))>0) { temp=ch[i]; ch[i]=ch[j]; ch[j]=temp; } } } for(int i=0;i<ch.length;i++) System.out.println(ch[i]); } }

2. StringBuffer Class:
Once a string object is created its contents cannot be changed. But the StringBuffer class provides the feature of creating and manipulating dynamic string information i.e., mutable strings. Every StringBuffer class is capable for storing a number of characters specified by its capacity. If the capacity of StringBuffer exceeded the capacity is automatically expanded to accommodate the additional characters.

StringBuffer Constructors:
a) StringBuffer(): It is a default StringBuffer Constructor to create StringBuffer with no characters init and an initial capacity of 16 characters. b) StringBuffer(String str): It takes a string argument to create a StringBuffer containing the characters of the string argument. The initial capacity is the number of arguments in the string argument + 16. c) StringBuffer(int size): It takes an integer argument and creates a StringBuffer with no characters init. The initial capacity is specified by the integer. Example: class sb { public static void main(String[] args) { StringBuffer s1,s2,s3; s1=new StringBuffer(); s2=new StringBuffer("hello"); s3=new StringBuffer(45); System.out.println(s1.capacity()+s2.capacity()+s3.capacity()); //O/P: 82 } } Methods: 1. int length(): It returns the number of characters in a StringBuffer. 41

Example: class sb1 { public static void main(String[] args) { StringBuffer s=new StringBuffer("hello"); System.out.println(s.length()); //O/P: 5 } } 2. int capacity(): It returns the number of characters that can be stored in a StringBuffer without allocating more memory. Example: class sb2 { public static void main(String[] args) { StringBuffer s=new StringBuffer("hello"); System.out.println(s.capacity()); //O/P: 21 } } 3. void ensureCapacity(): It is provided to allow the programmer to guarantee that a StirngBuffer has a minimum capacity where capacity specifies the size of the buffer. Example: class sb3 { public static void main(String[] args) { StringBuffer s=new StringBuffer("hello"); s.ensureCapacity(75); System.out.println(s.capacity()); //O/P: 75 } } 4. void setLength(int len): It increase or decrease the length of StringBuffer. Example: class sb4 { public static void main(String[] args) { StringBuffer s=new StringBuffer("abcdefghijkl"); s.setLength(5); System.out.println(s); //O/P: abcde } } 5. char charAt(int where): It returns a character at the specified where position. Example: class sb5 { public static void main(String[] args) { StringBuffer s=new StringBuffer("abcdefghijkl"); System.out.println(s.charAt(7)); //O/P: h } } 6. void setCharAt(int where, char ch): It takes an integer and a character argument and sets the character at the specified position of the character argument. 42

Example: class sb6 { public static void main(String[] args) { StringBuffer s=new StringBuffer("abcdef"); //O/P: Hbcdef s.setCharAt(0,'H'); System.out.println(s); } } 7. void getChars(int Sourcestart, int Sourceend, char Target[], int Targetstart): It copies the sub string of a StringBuffer into character array. Sourcestart specifies the starting index from which characters should be copied in StringBuffer. Sourceend specifies the index one past the last character to be copied from the StringBuffer. Target specifies the character array into which the characters are to be copied. Targetstart specifies the starting location of the character array from where the first character should be placed. Example: class sb7 { public static void main(String[] args) { StringBuffer s=new StringBuffer("abc def"); char ch[]=new char[s.length()]; s.getChars(3,s.length(),ch,0); for(int i=0;i<ch.length;i++) System.out.println(ch[i]); //O/P: def } } 8. StringBuffer reverse(): It returns the reverse contents of the StringBuffer. Example: class sb8 { public static void main(String[] args) { StringBuffer s=new StringBuffer("abcdef"); System.out.println(s.reverse()); } }

3. StringTokenizer class:
In programming languages, statements are divided into individual pieces like identifiers, keywords, and operators etc., called Tokens. Java provides StringTokenizer class that breaks a string into its component tokens. This class is available in java.util package. Tokens are separator from one another by delimiters (special operators), white space characters such as blank, tab, new line and carriage return. StringTokenizer Constructors: a) StirngTokenizer(Stirng str) b) StirngTokenizer(Stirng str, String delimiters) c) StirngTokenizer(Stirng str, String delimiters, boolean delimiterAsToken) In all versions str is a string that is tokenized. In the first version, the default delimiters are used. In the second version and third versions delimiters in string that specifies the delimiters. In the third version if delimiterAsToken is true then the delimiters also returned as tokens when the string is tokenized otherwise, the delimiters are not returned. Delimiters are not returned as tokens by the first two forms.

Methods:
43

1. int countTokens(): Using the current set of delimiters the method determines the number of tokens left to be tokenized and return the result. 2. boolean hasMoreTokens(): It returns true if one or more tokens remain in the string and returns false if there are none. 3. String nextToken(): It returns the next token as string. Example: import java.util.*; class st { public static void main(String[] args) { String s=new String("abc def gh"); StringTokenizer t=new StringTokenizer(s); System.out.println(t.countTokens()); while(t.hasMoreTokens()) System.out.println(t.nextToken()); }} O/P: 3 abc def gh LabProgram 7: Write a program that reads a line of integers, then displays each integers and the sum of all the integers import javax.swing.JOptionPane; import java.util.*; class lab7 { public static void main(String[] args) { //String s=new String("4$8$9$67"); //StringTokenizer t=new StringTokenizer(s,"$"); String s; s=JOptionPane.showInputDialog("Enter the string"); StringTokenizer t=new StringTokenizer(s,"$"); int a,sum=0; System.out.println(t.countTokens()); while(t.hasMoreTokens()) { a=Integer.parseInt(t.nextToken()); System.out.println(a); sum=sum+a; } System.out.println("Total="+sum); }} LabProgram 4: Write a program to check whether a given string is palindrome or not. import javax.swing.JOptionPane; class lab4 { public static void main(String[] args) { String s; s=JOptionPane.showInputDialog("Enter a String"); char ch[]=s.toCharArray(); int i,j,count=0; 44

for(i=0,j=ch.length-1;i<j;i++,j--) { if(ch[i]!=ch[j]) { System.out.println("Not polindrome"); count=1; break; } } if(count==0) System.out.println("Polindrome"); }}

Garbage Collection
Objects are dynamically allocated by using the new operator such objects are destroyed automatically and their memory released for later reallocation in Java. The technique that accomplishes this is called Garbage Collection. Garbage collection works when no references to an object exist, the object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. Java run-time implementations will take various approaches to garbage collection.

finalize( ) method:
The garbage collector of an object called this method when the garbage collection determines that those are no more references to the object. It is also placed some actions inside the finalized method. The following points are related to finalize( ) method. 1. Every class has Object class as a super class 2. Every class in Java can have a finalize( ) method that returns resources to the system 3. A class should have only one finalize( ) method that takes no argument. Method finalize( ) is originally defined in class Object The finalize( ) method has the following syntax Syntax: protected void finalize( ) { // finalization code } Example: class Garbage extends Object { int x,y; void setdata(int a,int b) { x=a; y=b; } void printdata() { System.out.println("x="+x+" y="+y); } protected void finalize() { System.out.println("finalizer"); }} class Mg { public static void main(String[] args) { O/P: x=10 y=20 Garbage obj=new Garbage(); finalizer Garbage obj1=new Garbage(); x=10 y=20 obj.setdata(10,20); obj.printdata(); obj1=null; System.gc(); // method to call garbage collector //obj1.setdata(2,3); //error obj.printdata(); }} 45

Unit III
Inheritance: The mechanism of deriving a new class from an old one is called inheritance. A class that is
inherited (old class) is called a super class or base class or parent class. The class that does the inheriting (new class) is called a subclass or derived class or child class. Inheritance allows subclasses to inherit all the variables and methods of their parent classes. Inheritance is classified into different forms. a) Single Inheritance: Derivation a subclass from only one super class is called Single Inheritance. Super class (or) Base class (or) Parent class A Subclass (or) Derived class (or) Child class b) Hierarchical Inheritance: Derivation of several classes from a single super class is called Hierarchical Inheritance. A B

c) Multilevel Inheritance: Derivation of a class from another derived class s called Multilevel Inheritance. A B C d) Multiple Inheritance: Derivation of one class from two or more super classes is called Multiple Inheritance. But Java does not support Multiple Inheritance directly. It can be implemented by using Interface concept. A B C e) Hybrid Inheritance: Derivation of a class involving more than one form of Inheritance is called Hybrid Inheritance. A B D Defining a Subclass: A subclass is defined as Syntax: class subclass-name extends superclass-name { variable declaration; method declaration; } The keyword extends signifies that the properties of the super class name are extended to the subclass name. The subclass will now contain its own variables and methods as well as those of the super class. But it is not vice-versa. Example 1: Program for Single Inheritance C

46

class A { int len,bre; void getdata(int x,int y) { len=x; bre=y; } void printdata() { System.out.println("length="+len); System.out.println("Breadth="+bre); } } class B extends A { int wid; void putdata(int x,int y,int z) { len=x; bre=y; wid=z; } void printdata1() { printdata(); System.out.println("Width="+wid); } void calarea() { int area=len*bre*wid; System.out.println("Area="+area); } } class si { public static void main(String[] args) { B obj=new B(); obj.putdata(10,20,30); obj.printdata1(); obj.calarea(); } } Example 2: Program for Hierarchical Inheritance class A { int len,bre; void getdata(int x,int y) { len=x; bre=y; } void printdata() { System.out.println("length="+len);System.out.println("Breadth="+bre); } } class B extends A 47

{ int wid; void getdata1(int x,int y) { getdata(x,y); } void calarea() { printdata(); int area=len*bre; System.out.println("Area="+area); } } class C extends A { int wid; void putdata(int x,int y,int z) { len=x; bre=y; wid=z; } void printdata1() { printdata(); System.out.println("Width="+wid); } void calarea1() { int area=len*bre*wid; System.out.println("Area="+area); } } class hi { public static void main(String[] args) { B obj=new B(); obj.getdata1(10,20); obj.calarea(); C obj1=new C(); obj1.putdata(1,2,3); obj1.printdata1(); obj1.calarea1(); } } //Example Program for Hierarchical Inheritance import java.text.*; class Employee { int Empno; double Basic,DA,HRA; String Empname; void readdata(int x,String y) { Empno=x;Empname=y;} void readsalary(double x,double y,double z) 48

{ Basic=x; DA=y; HRA=z; } void printdata() { System.out.println("Employee Number:"+Empno); System.out.println("Employee Name :"+Empname); } void printsalary() { DecimalFormat df=new DecimalFormat("0.00"); System.out.println("Employee Basic :"+df.format(Basic)); System.out.println("Employee DA :"+df.format(DA)); System.out.println("Employee HRA :"+df.format(HRA)); } } class TSalary extends Employee { void showdata() { readdata(111,"Vishnu"); printdata(); readsalary(2589.00,567,1090); printsalary(); } void calsalary() { DecimalFormat df=new DecimalFormat("0.00"); double netsal; netsal=Basic+DA+HRA; System.out.println("Employee Netsalary="+df.format(netsal)); } } class PSalary extends Employee { double Itax; void readtax(double x) { Itax=x; } void showdata() { readdata(1000,"Kamal"); printdata(); readsalary(12589.00,1567,2090); printsalary(); } void calsalary() { DecimalFormat df=new DecimalFormat("0.00"); double Gsal,netsal; Gsal=Basic+DA+HRA; 49

netsal=Gsal-Itax; System.out.println("Income Tax Amount="+df.format(Itax)); System.out.println("Employee Netsalary="+df.format(netsal)); } } class Harch { public static void main(String[] args) { TSalary obj=new TSalary(); obj.showdata(); obj.calsalary(); PSalary obj1=new PSalary(); obj1.readtax(800); obj1.showdata(); obj1.calsalary(); } } Example 3: Program for Multilevel Inheritance import javax.swing.JOptionPane; class student { int rno; void readdata1() { rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number")); } void printdata1() { System.out.println("Roll Number="+rno); } } class exam extends student { int m1,m2,m3; void readdata2() { readdata1(); m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks")); m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks")); m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks")); } void printdata2() { printdata1(); System.out.println("Sub 1 marks="+m1); System.out.println("Sub 2 marks="+m2); System.out.println("Sub 3 marks="+m3); } } class results extends exam { int avg; void printdata3() { 50

printdata2(); avg=(m1+m2+m3)/3; if(avg<35) System.out.println("FAIL"); else if(avg>=35 && avg<50) System.out.println("THIRD CLASS"); else if(avg>=50 && avg<60) System.out.println("SECOND CLASS"); else if(avg>=60 && avg<75) System.out.println("FIRST CLASS"); else if(avg>=75) System.out.println("DISTINCTION"); } } class mi { public static void main(String[] args) { results obj=new results(); obj.readdata2(); obj.printdata3(); } }

Member Access Rules:


1. By means of sub class object it is possible to access all the instance variables and instance methods of the super class. 2. By means of sub class object it cannot be possible to access the instance variable of super class, if it is declared as private. Since, the data is protected in that class. import javax.swing.JOptionPane; class student { private int rno; void readdata1() { rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number")); } } class exam extends student { void printdata1() { readdata1(); System.out.println("Roll Number="+rno); // produces compilation error } } class mi2 { public static void main(String[] args) { exam obj=new exam(); obj.printdata1(); } }

51

3. Referring to super class object with a subclass reference produces syntax error. In such case we need type casting. Example: import javax.swing.JOptionPane; class student { int rno; void readdata1() { rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number")); } } class exam extends student { void printdata1() { readdata1(); System.out.println("Roll Number="+rno); } } class mi2 { public static void main(String[] args) { student s1=new exam(); exam e1=(exam)s1; e1.printdata1(); } } super keyword: A subclass constructor is used to construct the instance variable of both the subclass and the super class. The subclass constructor uses the keyword super to invoke the constructor method of the super class. The keyword super is used subject to the following conditions. super may be used only within the subclass constructor method The call to super class constructor must appear as the first statement with in the subclass constructor If a parameterized constructor is used, then the signature is matched with the parameters passed to the super method as super(parameter-list); Example 1: class student { public student() { System.out.println("super"); }} class exam extends student { public exam() { System.out.println("sub"); }} class s { O/P: super public static void main(String[] args) sub { exam obj=new exam(); } 52

}a Example 2: class student { public student() { System.out.println("super"); } } class exam extends student { public exam() { super( ); // explicit call of super( ) System.out.println("sub"); } } class s { public static void main(String[] args) { exam obj=new exam(); } } O/P: super sub Example 3: class student { int len,bre; public student(int a,int b) { len=a; bre=b; } int area() { return len*bre; } } class exam extends student { int ht; public exam(int x,int y,int z) { super(x,y); ht=z; } int volume() { return len*bre*ht; } } class s { public static void main(String[] args) { exam obj=new exam(2,3,4); System.out.println("area="+obj.area()); System.out.println("volume="+obj.volume()); } } 53

Another important use of super is applicable to situations in which member names of a subclass hide members by the same name in the super class. It is similar to the this keyword except that it always refers to the super class of the subclass in which it is used. The general form is as super.member where member can be either a method or an instance variable Example: class A { int i=7; } class B extends A { int i=6; void show() { System.out.println("super i="+super.i); System.out.println("sub i="+i); } } class s1 { public static void main(String[] args) { B obj=new B(); obj.show(); } }

Method Overriding
A method in a subclass has the same name, type of the variables and order of the variables as a method in its super class, then the method in the subclass is said to be override the method in the super class. The process is called Method Overriding. In such process the method defined by the super class will be hidden. When the method is called, the method defined in the super class has invoked and executed instead of the method in the super class. The super reference followed by the dot (.) operator may be used to access the original super class version of that method from the subclass. Note: 1. Method Overriding occurs only when the name and type signature of the two methods are identical. 2. If method name is identical and the type signature is different, then the process is said to be Method Overloading. Example 1: class A { int i,j; public A(int a,int b) { i=a; j=b; } void show() { System.out.println("i="+i+"\n"+"j="+j); } } 54

class B extends A { int k; B(int a,int b,int c) { super(a,b); k=c; } void show() { System.out.println("k="+k); } } class override { public static void main(String[] args) { B obj=new B(1,2,3); obj.show(); } } O/P: k=3 Example 2: class A { int i,j; public A(int a,int b) { i=a; j=b; } void show() { System.out.println("i="+i+"\n"+"j="+j); } } class B extends A { int k; B(int a,int b,int c) { super(a,b); k=c; } void show() { super.show(); System.out.println("k="+k); } } class override { public static void main(String[] args) { B obj=new B(1,2,3); 55

O/P:

i=1 j=2 k=3

obj.show(); }} Resolve the method call at compile time is known as compile time or early binding or static binding. Resolve the method at run time is known as run time or late binding or dynamic binding. Method Overriding forms on the basis of Java concept Dynamic Method Dispatch. It is the mechanism by which a call to an overridden function is resolved at run time, rather than compile time. And this method is very useful to show for Java implements run-time polymorphism. Super class reference variable can refer to a subclass object is the principle to resolve calls to overridden methods at run time. If a super class contains a method that is overridden by a subclass, then when different types of objects are referred to through a super class reference variable, different version of the methods are executed and the determination is made at run time. Lab Program 21: Example program for Java supports Run time Polymorphism. class figure { double dim1,dim2; figure(double x,double y) { dim1=x; dim2=y; } double area() { System.out.println("Area undefined"); return 0; } } class rectangle extends figure { rectangle(double a,double b) { super(a,b); } double area() { System.out.println("Rectangle Area"); return dim1*dim2; } } class triangle extends figure { triangle(double x,double y) { super(x,y); } double area() { System.out.println("Triangle Area"); return dim1*dim2/2; } } class run { public static void main(String[] args) { figure obj=new figure(10,10); rectangle obj1=new rectangle(9,5); 56

triangle obj2=new triangle(10,8); figure a; //a is a reference of type figure(super class) a=obj1; //a refers to object of rectangle(sub class) System.out.println("Area="+a.area()); a=obj; //a refers to object of figure System.out.println("Area="+a.area()); a=obj2; //a refers to object of triangle System.out.println("Area="+a.area()); } } O/P: Rectangle Area Area=45.0 Area undefined Area=0.0 Triangle Area Area=40.0

Abstract Class:
Classes from which objects cannot be instantiated with new operator are called Abstract Classes. Each abstract class contains one or more abstract methods. In a class if there exist any method with no method body is known as abstract method. An abstract method is declared as Syntax: abstract type method-name (parameter-list); abstract is a keyword used for declaring abstract methods. To declare a class as abstract, use the abstract keyword in front of the class keyword at the beginning of the class declaration. No objects are created to an abstract class. For the abstract methods, the implementation code will be defined in its subclass. Example: abstract class figure { double dim1,dim2; figure(double x,double y) { dim1=x; dim2=y; } abstract double area(); } class rectangle extends figure { rectangle(double a,double b) { super(a,b); } double area() { System.out.println("Rectangle Area"); return dim1*dim2; } } class triangle extends figure { triangle(double x,double y) { super(x,y); 57

} double area() { System.out.println("Triangle Area"); return dim1*dim2/2; } } class abs { public static void main(String[] args) { //figure obj=new figure(10,10); //error rectangle obj1=new rectangle(9,5); System.out.println("Area="+obj1.area()); triangle obj2=new triangle(10,8); figure a; a=obj2; System.out.println("Area="+a.area()); } } Note: 1. We cannot declare any abstract constructors. 2. Concrete (general) methods are also being inside any abstract class. 3. Abstract classes are used for general purposes. 4. An abstract class must be subclass and override it methods. 5. Super class has only method name and signature end with semicolon. 6. Abstract classes cannot be used to instantiate objects, but they can used to create object reference due to Java supports Run-time Polymorphism.

final keyword
A final is a keyword used for three purposes. They are a) final as constant: A variable can be declared as constant with the keyword final. It must be initialized while declaring. One we initialized the variable with final keyword it cannot be modified in the program. This is similar to the const in C/C++. Example: final int x = 10; x = 45 //error b) final to prevent overriding: A method that is declared as final cannot be overridden in a subclass method. It the methods that are declared as private are implicitly final. Example: class A { final void show( ) { System.out.println(Hello); } } class B extends A { void show( ) { //error System.out.println(Hai); } } c) final to prevent inheritance: The class that is declared as final implicitly declares all of its methods as final. The class cannot be extended to its subclass. Example: final class A 58

{ void show( ) { System.out.println(Hello); } } class B extends A { void show( ) { System.out.println(Hai); } } //error

Object Class
Java provides a special class called Object class that is available in java.lang package. It is the super class of all other classes. So, a reference variable of type Object is created, it refers to object of any other class. Object class defines the following methods that are available in every object. Method Purpose Object clone( ) Creates a new object that is the same as the object being cloned boolean equals(Object object) Determines whether one object is equal to another void finalize( ) Called before an unused object is recycled Class getClass( ) Obtains the class of an object at run time int hashCode( ) Returns the hash code associated with the invoking object void notify( ) Resumes execution of a thread waiting on the invoking object void notifyAll( ) Resumes execution of all threads waiting on the invoking object String toString( ) Returns a string that describes the object void wait( ) Waits on another thread of execution void wait(long milliseconds) void wait(long milliseconds, int nanoseconds) Array of Objects: To instantiate more than one object for a single class, we use Array of Objects. Example: import javax.swing.JOptionPane; class a { int x,y; void readdata() { x=Integer.parseInt(JOptionPane.showInputDialog("Enter x value")); y=Integer.parseInt(JOptionPane.showInputDialog("Enter y value")); } void printdata() { System.out.println("x="+x+"\n"+"y="+y); } } class aob { public static void main(String[] args) { a ob[]=new a[5]; for(int i=0;i<5;i++) { ob[i]=new a(); ob[i].readdata(); ob[i].printdata(); 59

}}

UNIT IV
INTERFACES
Interface is a collection of method declaration and constants that one or more classes of objects will use. Interface definition is same as class except that it consists of the methods that are declared have no method body. They end with a semicolon after the parameter list. Syntax for an interface is as follows. Syntax: <access specifier> interface <it-name> { type varname1=value; type varname2=value; . . returntype method-name1(parameter-list); returntype method-name2(parameter-list); . . } Here, access specifier is public or not used. public access specifier indicates that the interface can be used by any class. Otherwise, the interface will accessible to class that are defined in the same package as in the interface. interface keyword is used to declare the class as an interface. it-name is the name of the interface and it is a valid identifier. Variables declared inside the interface are implicitly final and static. They cannot be changed in the implementing class. All the methods in an interface are implicitly abstract methods. Method implementation is given in later stages. The main difference between a class and interface is class contains methods with method body and the interface contains only abstract methods. Example: public interface shape { int radius=2; public void area(int a); } Implementing Interfaces: Once an interface has been defined, one or more classes can implement that interface. implements keyword used for implementing the classes. The syntax of implements is as follows. Syntax: class class-name implements interface1, interface2, .. interfacen { .. .. // class body .. } If a class implements more than one interface, the interfaces are separated with a comma operator. The methods that implement an interface must be declared public. Also type signature of the implementing method must match exactly the type signature specified in the interface definition. Example: interface it1 { int x=10,y=20; public void add(int a,int b); public void sub(int a,int b); } 60

class it2 implements it1 { public void add(int s,int w) { System.out.println("Addition="+(s+w)); } public void sub(int s,int w) { System.out.println("Subtraction="+(s-w)); } public static void main(String[] args) { it2 obj=new it2(); obj.add(3,4); obj.sub(5,2); System.out.println(obj.x+obj.y); obj.x=70; // error since x is final variable in interface } } Note: 1. Interface methods are similar to the abstract classes so, that it cannot be instantiated. 2. Interface methods can also be accessed by the interface reference variable refer to the object of subclass. The method will be resolved at run time. This process is similar to the super class reference to access a subclass object. Example: interface it1 { int x=10,y=20; public void add(int a,int b); public void sub(int a,int b); } class it2 implements it1 { public void add(int s,int w) { System.out.println("Addition="+(s+w)); } public void sub(int s,int w) { System.out.println("Subtraction="+(s-w)); } public static void main(String[] args) { it2 obj=new it2(); it1 ref; ref=obj; System.out.println(ref.x+ref.y); } } 3. If a class includes an interface but does not fully implement the methods defined by that interface, then the class becomes abstract class and must be declared as abstract in the first line of its class definition. Example: interface it1 61

{ int x=10,y=20; public void add(int a,int b); public void sub(int a,int b); } abstract class it2 implements it1 { public void add(int s,int w) { System.out.println("Addition="+(s+w)); } } class it3 extends it2 { public void sub(int s,int w) { System.out.println("Subtraction="+(s-w)); } public static void main(String[] args) { it3 obj=new it3(); obj.add(5,6); } }

Various forms of Interface Implementations:


1. interface implements class extends class 2. interface implements interface 3. class extends class class 4.
A

A B C A implements
C
D

interface

interface extends interface

implements

extends
C
B

interface A implements interface implements class

interface implements

C D

62

Multiple Inheritance: Multiple Inheritances does not support by Java directly. Multiple Inheritances
enables to derive a class from multiple parent classes. Let A and B are parent classes and C is the derived class
A
B

Java provides Interface approach to support the concept of Multiple Inheritance. A class can also implements multiple interfaces. Example: class Test { int sub1,sub2,sub3; void readdata1(int x,int y,int z) { sub1=x; sub2=y; sub3=z; } void printdata1() { System.out.println("sub1 marks="+sub1); System.out.println("sub2 marks="+sub2); System.out.println("sub3 marks="+sub3); } } interface Sports { int smarks=55; public void printdata2(); } class Result extends Test implements Sports { int sum; public void printdata2() { printdata1(); sum=sub1+sub2+sub3+smarks; System.out.println("Total Marks="+sum); } } class mul { public static void main(String[] args) { Result obj=new Result(); obj.readdata1(35,67,89); obj.printdata2(); } }

63

Hybrid Inheritance: Derivation of a class involving more than one form of Inheritance is called Hybrid
Inheritance.
A B D C

Example: import javax.swing.JOptionPane; class Student { int rno; String name; void readdata1() { rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number")); name=JOptionPane.showInputDialog("Enter name"); } void printdata1() { System.out.println("Roll number="+rno); System.out.println("Name ="+name); } } class Test extends Student { int m1,m2,m3; void readdata2() { m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks")); m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks")); m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks")); } void printdata2() { System.out.println("Sub1="+m1+" Sub2="+m2+" Sub3="+m3); } } interface Sports { int smarks=55; public void printdata3(); } class Result extends Test implements Sports { int sum; public void printdata3() { System.out.println("Sports marks="+smarks); } public void readdata3() { readdata1(); readdata2(); } public void printdata4() 64

{ sum=m1+m2+m3+smarks; printdata1(); printdata2(); printdata3(); System.out.println("Total Marks="+sum); } } class hy { public static void main(String[] args) { Result obj=new Result(); obj.readdata3(); obj.printdata4(); } }

PACKAGES
Package is a collection of related classes. Each class defines number of methods. Java packages are classified into 2 types. 1. Java API (Application Programming Interface) packages (or) Predefined packages (or) Built-in packages: These packages are defined by the system. Some of the example for system defined packages are java.lang, java.util, java.io, java.awt, java.applet etc., 2. User defined packages: These packages are defined by the user.

Defining a Package:
To define a package, place package command as the first statement in the Java source file. So, that any class declared within that file will belong to the specified package. The syntax of package creation is as follows. Syntax: package pack-name; where pack-name is the name of the package. Example: package mypack; public class number { public void add (int a,int b) { System.out.println(Sum=+(a+b)); } } The class that is defined in the package must be start with the public access modifier. So, that it can be accessible by any another of them. If it is not public, it is possible to access only in that package. Java uses file system directories to store packages. We save the program with number.java and compile the package is as javac d . number.java Due to this compilation mypack directory is automatically created and .class file is stored in that directory. Package creation has completed. The package information is now including in our actual program by means of import statement. import is a keyword that links the package with our program. It is placed before the class definitions. import mypack.*; or import mypack.number;

65

Example 1: import mypack.number; class pack { public static void main(String[] args) { number obj=new number(); obj.add(3,4); } } Example 2: package math1; public class Mcal { public void square(int x) { System.out.println("Square of "+x+" is"+(x*x)); } public void cube(int x) { System.out.println("cube "+x+" is"+(x*x*x)); } } import math1.Mcal; class calc { public static void main(String[] args) { Mcal obj=new Mcal(); obj.square(3); obj.cube(4); } } Example 3: package p6; public class Balance { String name; double bal; public Balance(String n, double b) { name=n; bal=b; } public void show() { if(bal<0) { System.out.println(name+"---"+bal); } } }

66

import p6.Balance; class Account { public static void main(String[] args) { Balance c[]=new Balance[3]; c[0]=new Balance("John",123.33); c[1]=new Balance("Arun",157.02); c[2]=new Balance("Siri",-12.33); for(int i=0;i<3;i++) c[i].show(); } } Note: 1. Java source file contains only one public class and any number of non-pubic classes. The filename should be same as the name of the public class with .java extension. 2. Package contain any number of public and default classes. Example: package p1; public class x { // body of x this class is accessible } class y { // body of y not accessible due to non-use } of public access modifier Let we want to access all the classes of information then the classes are stored in different files with the same package name. Example: package mypack; public class number { public void add (int a,int b) { System.out.println(Sum=+(a+b)); } } package mypack; public class number1 { public void sub(int a,int b) { System.out.println("sub="+(a-b)); } } import mypack.number; import mypack.number1; class pack { public static void main(String[] args) { number obj=new number(); obj.add(3,4); number1 obj1=new number1(); obj1.sub(6,2); } } 67

Sub Packages: It is also possible to create sub packages for the main package.
Syntax: package pack1.pack2; where pack1 is the main package and pack2 is the sub package. Example: package pack1; public class x { public void show() { System.out.println("Super"); } } package pack1.pack2; public class y { public void display() { System.out.println("Sub"); } } import pack1.x; import pack1.pack2.y; class che { public static void main(String[] args) { x obj=new x(); obj.show(); y obj1=new y(); obj1.display(); } }

Access Protection
Java provides four types Access modifiers as public, private, default and protected. Any variable declared as public, it could be accessed from anywhere. Any variable declared as private cannot be seen outside of its class. Any variable declared as default, it is visible to subclasses as well as to other classes in the same package. Any variable declared as protected, it allows an element to be seen outside of current package, but only to classes that subclass directly. Same class Same package sub class Same package non-subclass Different package sub class Different package non-subclass Example: package p1; public class protect { int n=1; private int n_pri=2; protected int n_pro=3; public int n_pub=4; public Yes Yes Yes Yes Yes private Yes No No No No default Yes Yes Yes No No protected Yes Yes Yes Yes No

68

public protect() { System.out.println("Super constructor"); System.out.println("default="+n); System.out.println("private="+n_pri); System.out.println("protected="+n_pro); System.out.println("pubic="+n_pub); } } package p1; class derive extends protect { derive() { System.out.println("Sub constructor"); System.out.println("default="+n); //System.out.println("private="+n_pri); //since it is a private variable in package p1 System.out.println("protected="+n_pro); System.out.println("pubic="+n_pub); } } import p1.protect; class same { public static void main(String[] args) { protect obj=new protect(); } }

CLASSPATH
A class path is an environmental variable, which tells the java virtual machine and other java tools (java, javac), where to find the class libraries, including user-defined class libraries. By default, java uses the classpath as C:\jdk1.2.1\lib\classes.zip A user defined class path is set for the environment as C:\>SET CLASSPATH=%CLASSPATH%;C:\P

69

UNIT V
EXCEPTION HANDLING Exception: An exception is an abnormal event that rises during the execution of a program and disturbs the normal flow of instructions i.e., exception is a run-time error. Consider the following example: class hello { public static void main(String[] args) { int a=10,b; b=a/0; System.out.println("value="+b); } } When we try to compile this program, it does not produce any errors. But when it runs the program it produces a message as java.lang.ArithmeticException: / by zero. This exception error message is displayed and the program terminates without executing the remaining statements. Exception Handling: Exception Handling is designed for error processing. It enables a program to catch all types of exceptions of certain type or related type. Exception handling is designed for dealing with Synchronous errors such as an attempt to divide by zero, out of bounds exception etc., It is not designed to deal with Asynchronous errors such as mouse checks, key strokes etc., Exception Handling is used in situation arises the system can recover from causing the exception. The procedure is called Exception Handling and done by the Exception Handler. All exception types are subclasses of built-in class Throwable. It is a super class. The class is available in java.lang package. It contains errors and exceptions. Throwable (super class) Errors (Asynchronous) Exceptions (Synchronous)

Run-time Exceptions IO Exceptions Java defines several exception classes inside the java.lang package. These are all subclass of Runtime Exceptions. The following are the some of the examples of exceptions and these are unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds IllegalArgumentException Illegal argument used to invoke a method IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format StringIndexOutOfBounds Attempt to index outside the bounds of a string java.lang package contains some another type of exceptions that does not handle itself. Here, the compiler checks that what is to be done when this arise, because of this checking that they are called checked exceptions. Examples for checked exceptions are 70

Exception ClassNotFoundException IllegalAccessException InterruptedException NoSuchMethodException

Meaning Class not found Access to a class is denied One thread has been interrupted by another thread A requested method does not exist

Exception-Handling Fundamentals
Java exception handling is managed through five keywords. They are 1) try 2)catch 3) throw 4) throws 5) finally. The general format of an exception-handling block is as Syntax: try { // block of code to monitor for errors } catch (ExceptionType1 exob) { // exception handler for exception type1 } catch (ExceptionType2 exob) { // exception handler for exception type2 } . . finally { // block of code to be executed before of try block ends } Here, ExceptionType is the type of exception that has occurred and exob is the exception object. try block: The statements that are produces exception are identified in the program and the statements are placed with in a try block Syntax: try { // block of code to monitor for errors } If an exception occurs within the try block, the appropriate exception handler (catch block) associated with the try block handles the exception immediately. catch block: The catch block is used to process the exception raised. The catch block is placed immediately after the try block. Syntax: catch (ExceptionType exob) { // exception handler for exception type } finally block: This block is placed after the last catch block. This block is executed regardless of whether or not an exception is raised. Syntax: finally { // block of code to be executed before of try block ends } 1. The control enters into the try block and executes the statements. If an exception is raised, the exception throws and it caught by exception handler catch block. And the particular catch block statements are executed. The control never backs again to the try block. If no exceptions raised, catch blocks are not executed the control directly passed to the finally block. 2. No statements are placed between try block and catch block. 71

Example 1: class ex11 { public static void main(String[] args) { try { int a=10,b; b=a/0; System.out.println("b="+b); } catch(ArithmeticException e) { System.out.println("Exception raised"); } System.out.println("Quit"); } } O/P: Exception raised Quit Example 2: class ex12 { public static void main(String[] args) { int x[]=new int[10]; try { x[20]=100; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception caught"); } finally { System.out.println("Not possible to print"); System.out.println("Quit"); } } }

Methods of Exception Object


a) String getMessage( ): It returns the descriptive string stored in an exception. Example: / by zero b) String toString( ): It returns an error message with the class name of the exception the descriptive string to be stored in the exception. Example: java.lang.ArithmeticException: / by zero package class string

72

c) void printStackTrace( ): This is the standard output error stream. It displays the error message with the class name of the exception the descriptive string to be stored in the exception along with the line number and name of the program. Example: java.lang.ArrayIndexOutOfBoundsException at ex12.main (ex12.java:8) class name file name line number

method name

Example 1: class ex12 { public static void main(String[] args) { int x[]=new int[10]; try { x[20]=100; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); System.out.println(e.toString()); e.printStackTrace(); } } } Example 2: class ex12 { public static void main(String[] args) { String s=new String("Java programming language"); try { System.out.println(s.substring(45)); } catch(StringIndexOutOfBoundsException e) { System.out.println(e.getMessage()); System.out.println(e.toString()); e.printStackTrace(); } } } Example 3: import java.text.DecimalFormat; class n { public static void main(String[] args) { try { double x=25.6776; DecimalFormat d=null; 73

System.out.println(d.format(x)); } catch(NullPointerException e) { System.out.println(e.getMessage()); System.out.println(e.toString()); e.printStackTrace(); } } }

Multiple Catch Statements


Multiple catch clauses handle the situation where more than one exception could be raised by a single piece of code. In such situations specify two or more catch blocks, each specify different type of exception. Multiple catch statements are arranged in respective order of exceptions that araised by the try block (optional). Example: class cat { public static void main(String[] args) { try { int a=args.length; System.out.println("a="+a); int b=42/a; int c[]={1}; c[42]=99; } catch(ArithmeticException e) { System.out.println(e.getMessage()); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } } Note: A subclass must come before their super classes in a series of catch statements. Exception class is the super class of all exceptions. Example: class cat1 { public static void main(String[] args) { try { int a=0; int b=42/a; } catch(ArithmeticException e) {System.out.println(e.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } } 74

Nested try Statements


A try block is placed inside the block of another try block is termed as Nested try block statements. If any error statement is in outer try block it goes to the corresponding outer catch block. If any error statement is in inner try block first go to the inner catch block. If it is not the corresponding exception next goes to the outer catch, which is also not corresponding exception then terminated. Example: class ntry { public static void main(String[] args) { try { int a=args.length; int b=42/a; System.out.println("a="+a); try { if(a==1) a=a/(a-a); if(a==2) { int c[]={1}; c[42]=99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array Exception:"+e); } } catch(ArithmeticException e) { System.out.println("Arithemetic exception:"+e); } } } Example: class ntry1 { public static void main(String[] args) { try { int a=args.length; int b=42/a; System.out.println("b="+b); } catch(ArithmeticException e) { System.out.println("Arithemetic exception:"+e); } finally { System.out.println("final block"); } System.out.println("after try block"); }} 75

throw statement
All previous exceptions are catching that are thrown by the java run time system. It is also possible to create for a program that throws an exception explicitly, using the throw statement. The general format of throw statement is Syntax: throw throwable-instance; Here, throwable-instance must be an object type of Throwable class or subclass of Throwable. There are two ways to obtain a Throwable object. 1. Using a parameter into a catch clause 2. Creating one with the new operator Example: class ntry2 { public static void main(String[] args) { try { throw new ArithmeticException("hello"); } catch(ArithmeticException e) { System.out.println(e.getMessage()); } } } O/P: hello Example: class t { public t() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("caught"); throw e; //rethrow the exception } } } class ntry2 { public static void main(String[] args) { try { t obj=new t(); } O/P: caught catch(NullPointerException e) Recaught { System.out.println("Recaught"); } } } 76

throws statement
If a method is capable of causing an exception that it doesnt handle, it must specify the behavior to the callers of the method can guard themselves against that exception. This can be done by throws statement in the method declaration. A throws statement lists the types of exceptions that a method might throw. This is necessary for all exceptions except that those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws statement. Otherwise, it reports compile time error. The general format of throws statement is as Syntax: type method-name(parameter-list) throws exception-list { // method body } Here, exception-list is a comma-separated list of the exceptions that a method can throw. Example: class t { public t()throws NullPointerException { System.out.println("caught"); throw new NullPointerException("demo"); } } class ntry3 { public static void main(String[] args) { try { t obj=new t(); } catch(NullPointerException e) { System.out.println("Recaught"); } }} O/P: caught Recaught

User-defined Exceptions
It is also possible to create our own exceptions types to handle situations specific to our application. Such exceptions are called User-defined Exceptions. User-defined exceptions are created by extending Exception class. The throw and throws keywords are used while implementing user-defined exceptions. Example: class own extends Exception { own(String msg) { super(msg); } } class Test1 { public static void main(String[] args) { try { int mark=Integer.parseInt(args[0]); 77

if(mark>100) { throw new own("Greater than 100"); } System.out.println("Marks="+mark); } catch(own e) { System.out.println("Exception caught"); System.out.println(e.getMessage()); } finally { System.out.println("completed"); } } } O/P: Exception caught Greater than 100 completed

MULTITHREADED PROGRAMMING
A Multithreaded program contains two or more parts that can run concurrently. Each part of such program is called a thread, and each thread defines a specific path of execution. Multithreading is a specialized form of Multitasking. Multitasking: All modern operating systems support the concept of multitasking. Multitasking is the feature that allows the computer to run two or more programs concurrently. CPU scheduling deals with the problem of deciding for which of the process, the ready queue is to be allocated. It follows CPU (Processor) scheduling algorithms. a) Priority Scheduling: Process Burst time Priority P1 10 2 P2 01 4 P3 02 2 P4 01 1 P5 05 3 P2 P5 P1 P3 P4

0 1 6 16 18 19 The priority scheduling follows on Sun Solaris systems. But it doesnt work on the present operating systems like windows NT etc., The thread with a piece of system code is called the thread scheduler. It determines which thread is running actually in the CPU. The Solaris java platform runs a thread of given priority to completion or until a higher priority thread becomes ready at that point preemption occurs. b) Round-Robin Scheduling: Process Burst time P1 P2 P3 Time Quantum (or) Time Sliced : P1 0 4 P2 8 P3 11 P1 P2 15 19 24 10 03 04 P1 23 78 P2 25 P1 29 P1 33 P1 37

Round Robin scheduling is available on Windows 95 and Windows NT is time sliced. Java supports thread implementation depending on round robin scheduling. Here, each thread is given a limited amount of time called time quantum. While executing the process when that time quantum expires the thread is made to wait state and all threads that are equal priority get their chances to use their quantum in round robin fashion. Difference between Multiprocessing and Multithreading Multiprocessing Multithreading 1. More than one process running simultaneously 1. More than one thread running simultaneously 2. Its part of a program 2. Its part of a program 3. Its a heavy wait process 3. Its a light wait process 4. Process is divided into threads 4. Threads are divided into sub threads 5. There is no communications between 5. Within the process threads are processors directly communicated Note: 1. Java provides built-in support for multithreaded programming 2. Java multithreading is a platform independent 3. Elimination of main loop/polling is the main benefit of multithreaded programming.

Thread States (or) Lift-Cycle of a Thread


The life cycle of a thread contains several states. At any time the thread is falls into any one of the states. The thread that was just created is in the born state. The thread remains in this state until the threads start method is called. This causes the thread to enter the ready state. The highest priority ready thread enter the running state when the system assigns a processor to the thread i.e., the thread begins executing. When a running thread calls wait the thread enters into a waiting state for the particular object on which wait was called. Every thread in the waiting state for a given object becomes ready on a call to notify all by another thread associated with that object. When a sleep method is called in a running thread, that thread enters into the suspended (sleep) state. A sleeping thread becomes ready after the designated sleep time expires. A sleeping thread cannot use a processor even if one is available. A thread enters the dead state when its run( ) method complete (or) terminates for any reason. A dead thread is eventually be disposed of by the system. One common way for a running thread to enter the blocked state is when the thread issues an input or output request. In this case a blocked thread becomes ready when the input or output waits for completes. A blocked thread cant use a processor even if one is available.

Thread class constructors


1)Thread( ) 2)Thread(String Threadname) 3)Thread(Runnable obj) 4)Thread(Runnable obj, String name) 5)Thread(ThreadGroup tg, String Threadname)

Methods
1. String getName( ): It obtains the name of the thread. 2. void setName(String str): It sets the name of the thread. 3. int getPriority( ): It obtains the priority of the thread. 4. void setPriority(int): It sets the priority of the thread. 5. boolean isAlive( ): Determines if a thread is still running or not. It returns true if the thread upon which it is called is still running. Otherwise, it returns false. 6. void sleep(long milliseconds): Suspend a thread for a period of time. 7. void start( ): Start a thread by calling its run method. 8. void run( ): It defines the code that constitutes the new thread. When ever the start( ) method executes it automatically call of run( ) method. 9. void join( ): This method waits until the thread on which it is called terminates. 10. Thread currentThread( ): It returns a reference to the currently executing thread. 11. void yield( ): A thread can call the yield method to give other threads a chance to execute.

79

12. ThreadGroup getThreadGroup( ): It returns the name of the thread group which contain currently running thread. ThreadGroup represents set of Threads. It has one constructor method as ThreadGroup(String name). Main Thread: When a java program starts up, one thread begins running immediately. This one is main thread, which is created by virtual machine. It is executed in the program for the first time. It must be the last thread to finish execution. When the main thread stops the program terminates. Even though the main thread is automatically created when the program starts, it can be controlled through Thread object. For this we obtain a reference to by calling the method currentThread( ). Example: class demo { public static void main(String[] args) { Thread obj=Thread.currentThread(); System.out.println("current="+obj); obj.setName("india"); System.out.println("after="+obj); } } O/P: current=Thread[main,5,main] after=Thread[india,5,main] Example: class demo { public static void main(String[] args) { Thread obj=Thread.currentThread(); try { for(int n=5;n>0;n--) { System.out.println(n); obj.sleep(1000); } } catch(InterruptedException e) { System.out.println("exception"); } } }

Creating a new Thread


A new thread can be created in two ways 1. implements the Runnable interface 2. extends the Thread class itself 1. implements the Runnable interface: Runnable is a system defined interface. Once we create a class, it implements the Runnable interface forms a thread class. To implement Runnable, a class need only implement a single method called run( ). Example: class new1 implements Runnable { Thread t; public new1() { t=new Thread(this,"child thread"); 80

System.out.println("sub thread="+t); t.start(); } public void run() { try { for(int n=5;n>0;n--) { System.out.println("child="+n); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("child exception"); } System.out.println("child exit"); } } class demo1 { public static void main(String[] args) { new new1(); try { for(int n=5;n>0;n--) { System.out.println("main="+n); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("main exception"); } System.out.println("main exit"); } } 2. extending the Thread class: The second way to create a thread is to create a new class that extends Thread, and then create an instance of that class. The extending class must override the run( ) method. It must also call start( ) to begin execution of the new thread. Example: class newthread extends Thread { public newthread() { super("child thread"); System.out.println("sub thread="+this); start(); } public void run() { try 81

{ for(int n=5;n>0;n--) { System.out.println("child="+n); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("child exception"); } System.out.println("child exit"); } } class demo2 { public static void main(String[] args) { new newthread(); try { for(int n=5;n>0;n--) { System.out.println("main="+n); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("main exception"); } System.out.println("main exit"); } } Example: class a extends Thread { public void run() { for(int n=0;n<5;n++) { if(n==3) yield(); System.out.println("child 1="+n); } } } class b extends Thread { public void run() { for(int n=0;n<5;n++) { try { sleep(1000); } 82

catch(Exception e) { } System.out.println("child 2="+n); } }} class c extends Thread { public void run() { for(int n=0;n<5;n++) { if(n==2) stop(); System.out.println("child 3="+n); } } } class demo3 { public static void main(String[] args) { a obj=new a(); b obj1=new b(); c obj2=new c(); obj.start(); obj1.start(); obj2.start(); } } Example: class b implements Runnable { Thread t; b(String tname) { t=new Thread(this,tname); t.start(); } public void run() { try { for(int n=0;n<5;n++) { System.out.println("child 1="+n); //sleep(1000); can't work in the case implementing interface Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("child exception"); } } } class demo4 { public static void main(String[] args) { b obj1=new b("one"); b obj2=new b("two"); System.out.println("b is alive:"+obj1.t.isAlive()); 83

System.out.println("c is alive:"+obj2.t.isAlive()); try { obj1.t.join(); obj2.t.join(); } catch(InterruptedException e) { System.out.println("child exception"); } System.out.println("b is alive:"+obj1.t.isAlive()); System.out.println("c is alive:"+obj2.t.isAlive()); } }

Thread Priorities
Every thread in Java is assigned a priority value, when more than one thread is computing for CPU time. Generally highest priority thread is running before the lowest priority thread. It is also possible to set priority to each thread by the user using setPriority( ) method. System defined thread priorities are Thread.MIN_PRIORITY 1 Thread.MAX_PRIORITY 10 Thread.NORM_PRIORITY 5 The default priority is Thread.NORM_PRIORITY Example: class Demo extends Thread { public void run() { for(int i=1;i<=3;i++) System.out.println(getName()+" "+i); } } class ThprDemo { public static void main(String[] args) { Demo obj=new Demo(); Demo obj1=new Demo(); Demo obj2=new Demo(); obj.setPriority(Thread.MAX_PRIORITY); obj1.setPriority(Thread.MIN_PRIORITY); obj2.setPriority(Thread.NORM_PRIORITY); obj.start(); obj1.start(); obj2.start(); } } O/P: Thread-1 1 Thread-1 2 Thread-1 3 Thread-3 1 Thread-3 2 Thread-3 3 Thread-2 1 Thread-2 2 Thread-2 3

Synchronization
When two or more threads need access to a shared resource, they need someway to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called Synchronization. Java uses the concept of monitor (also called Semaphore) for Synchronization. 84

A monitor is an object that is used as a mutually exclusive lock, or mutex. The monitor allows one thread at a time to execute a Synchronized method on the object.

85

You might also like