Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Core Java Java is object oriented, dynamic, distributed, interpreted, multithreaded and platform in depended language mainly use for Web application. Java was developed by Sun Micro Systems in 1991.Initially its name was ‘Oak’ but later when they officially launch it in 1995 renamed as java. Java provides complete development environment using which we can develop different kinds of application. There are three platforms in java1)J2SE:-Java 2 Standard Edition(JVM). Using this platform we can create standard application for desktop PC. Standard application are not shareable. The latest version of J@SE is 1.6. 2)J2EE:-Java 2 Enterprise Edition. Using this platform we can develop Enterprise application which can be simultaneously used by any no. of clients from anywhere. 3)J2ME:-Java 2 Micro Edition.(KYM)Kilobyte Using this platform we can develop application for small devices like, Mobiles, PDA (Personal Digital Assistance) or TV setup box. Programs in Java:There will be two types of program in Java. 1) Java Application 2) Java Applet Java Application Java Applet 1)It is small Java programs which runs which runs It is also small program, under the control of local OS. Runs under the control of Web Browsers like, internet explorer, Mozilla etc. 2)Application are independent means It always dependent on web they can be run by own. document(HTML). 3)An Application can contain Menubar,Toolbar toolbar,Menu An Applet as liking of Title bar etc bar,title bar etc. 4)Application are not shareable. document Since it is part of web so,they are shareable. Features of Java:- 1)Object Oriented:-As the name suggest in Object Oriented Programming each & every things around object i.e. every attributes & methods are using objects. There are some features of OOPs. i)Classes & Objects:-Classes are general structure or templates which contains attributes(variables) and methods(implementation of variable). Using classes only objects can be createdEg:-Animal,Car,Pen are classes. Objects are instances of class use to access class members(variables & methods).i.e. without object we cannot access attributes & methods. Eg:-dog, santro, Reynolds they are objects of their corresponding class type. ii)Encapsulation(Data Hiding):-These features is also based on class concept because encapsulation is process of bending attributes & methods in single unit to protect data accessibility directly. We can apply access specifies like private,protected,public to restricted the attributes & method accessibility. iii)Data Abstraction:-These features allow us to use the functionality of particular object without having any idea about that object i.e. we can follow only needed things.These features is also based on class concept. iv)Inheritance:- class 1(parent/base/super) Attributes & methods class 2(child/derived/sub) Attributes & Methods of its own + Class 1 attributes & methods Inheritance is way of creating new classes using some existing classes to reuse the existing code. The class which is already it existence is super class while newly created class is called sub class. Advantage of Inheritance:i)Same code is being reuse thus it reduce the code redundancy. ii)Less storage is required because same code can be reuse by any no. of classes. iii)It save the timing to re-write the same code again. v)Polymorphism:-It is liability of object to do more than one operation on the basic of different-different application. 2)Dynamic(User Interactive):-Using Java we can create user interactive application so that if user input some data he can get some o/p. 3)Interpreted:-When Java source code is compiled by Java compiler(Javac) it generate .class file which is also called byte code instruction. Byte codes are highly optimized set of instruction which are neither readable nor executable. So,we required Java interpreter(Java) which read the byte code and generate the output.Thus Java is interpreter based language. .C/.CPP .Java Compile Compile (Javac) .exe Executable .Class CPU H/W not Executable Java (interpreter) JVM H/W 4)Distributed:-Java provide some technology like RMI(Remote Method Invocation) as well as J2EE platform using which we can create application which can be simultaneously use by any no. of clients anywhere.(Eg-Web site) 5)Multithreaded:-Every program in Java is considered as a thread it is also possible that using same application multiple process(thread) can be handled that application is called Multithreaded. 6)Platform Independed:-When java source code is compiled by Java compiler(Javac) it generate byte code.Byte code make the Java as platform independent language because same byte code can be run on any platform. 7)Robust & Secure:-Since in Java the code never interact with CPU(H/W) it always interact through JVM. So, Java code is secure. Structure of Java Application 1.package statement; (optional) 2.import statements; (optional) 3.Class ClassName { Attributes & methods Public static void main(String args[ ]) { Statements; Exp; } } ClassName.java(save) Simple Java Program:Class Test { Public static void main(String args[]) { System.out.println(“This is demo of first java application”); } } How to compile and run java program using textpad:i)To compile:ctrl+1(or) click on tools-->compile java ii)To run:ctrl+2(or) click on toolsrun java application How to compile and run using Notepad:While using Notepad we have to used command prompt to compile and run the program. i)for compile:javac filename.java compiler source code ii)for run:java filename Interpreter Note:1)Some time we get error like “javac is not recognized an internal or external command…….”. Therefore, we must have to set path environment variable. To do so class all the open programs then copy the path of JDK bin folder then right click on My Computer Property advanced Environmental Variable User Value New New User Value ? Variable Name Path Variable Name Complete Path Ok Then click ok Cancel X 2)Some time code is compiled successfully but at run time we get some error likeException in thread main java.lang.No such classDefFound:className.This indicate that either class name is proper or path of byte code is not found(.classfile). So,wee must have to classPath environmental variable.To set the classpath copy the folder location where .class file is been created. Right click on My Computer Property Variable User Variable User value New New User Value ? Variable Name Path Variable Name Complete Path Ok Adavanced Enviornmental X Cancel Then click ok. Some Notes about first program:i)Every programs in java must start with class .class name must be used as a file name because created using class name. ii)Every class must contain at least one method namely. public static void main(String args[]) where keyboard public indicate that main method accessibility from anywhere. Keyboard static indicate that main method is static method i.e. static members can be called directly without creating any object. Main method always must contain an array of string class type.Arguments belongs to command line argument. iii)In order to display any message or value we have to useSystem.out.println(“ “); System.out.print(“ “); Here system is predefine class defined in java.lang package. Out is static member of system class therefore the signature. ClassName.memberName Print or println is method of printStrem class defined in java is package. Some coding conversions in Java:i)Every classes and interfaces name always begins with capital letter.If it consist of multiple words then connecting first letter must be in capital. Eg:System String StringBuffer Pre-defined class InputStream FileInputStream Runnable AditionListener Pre-defined Interfaces WindowListener ii)Every packages name are completely in small letters. Java.lang Java.awt Pre-defined packages name. Java.applet iii)All predefined methods name always begins with small letters but if it consist of multiple word then the first letter of all connecting word must be capital. Print() Println() Size() Length() readLine() parseInt() parseFloat() iv)All predefined constants name almost fully capitalized form. Font.Bold=>Bold is static member of Font class color.RED Data Types in Java:Data type specify which type of value mostly contain by particular variable. There are mainly two types of data type. Data types Predefined/primitive data types User defined/custom data types i)Primitive Data type:Data types which are already defined is called primitive or pre-defined data types.It can be categorized into four categories. Logical-boolean Textual-char Integral-byte,short,int,long Floating-float,double ii)boolean:Use to represent logical value in terms of true and false. iii)char:Use to represent one or multiple characters. Memory required-16 bits(2 bytes) Range->0-65535(All international character) Since,java character represent Unicode character set between ‘\u0000’ as well as it also support alphabets of all internationalized lang.Therefore it required 1 byte additional. iv)byte:It is integral type which allow only integer numbers. Memory required-8 bits(1 byte) Range->-2 n-1 to 2n-1 -1(only for integral) Where n is no. of bits required for memory-27 to 27 -1 -128 to 127(total 0-255[256]) v)short:It is also integral type which required 16 bit memory-215 to 215 -1 -32768 to 32767(0-65535) Note:- While performing any arithmetic operation on short data type result is Automatically promoted to ‘int’ data type. vi)int:It is also integral type Memory required-32 bits(4 bytes) Range -231 to 231 -1 vii)long:-In java long is also datatype.It required 64 bits of memory. Range -263 to 263 -1 viii)float:By default all floating numbers in java are in double form.So,to represent it as a float we must have to append letter ‘F’ or ‘f’ after floating no. Memory required-32 bits(4 bytes) -231 to 231 -1 Eg:-float f = 3.14 32 bits 64 bits Float f=3.14f ix)double:- By default any floating no. in java are in double form. Memory required-64 bits(8 bytes) -263 to 263-1 User Defined/Custom Data types:Class is a way of implementing user defined data type. Class contains Both attributes(variable) and implementation of attributes(methods).Attributes & Methods are collectively known as members of the class. Using class only object can be created. Variables:-Variable are memory location name use to store data into the memory which may be change during runtime. How to declare variable:Syntex:-Datatype variable name=constant value; Where,data types can be either of primitive data type or it can be any class type(predefined/user defined) Eg:int x=10; char ch=’y’; primitive types float f=3.14f; String str=”Hello”; Class type Test l; Note:-If any variable is declared using any class. It is called reference variable because this variable can take the reference of any object of some class type. Keywords:Keywords are reserved words having special meaning.There are 50 keyboard in Java.Keyboard in Java.Keyboard are always completely in small letters.Commonly used keyword in java are- Byte else new import finally Short while void package static Int do public abstract Long for private final Float switch protected transient Double case class throw Boolean break interface throws Char default extends try If continue implements catch Note:-Any keywords cannot be used as an identifier name(i.e. as a classname,method name or variable name) Literals in Java(Constants):Constant value in java are called literals java supports following types of literals1)Character Literals:-If any single character is enclosed within single quotes they are called character literals. Eg:- ‘x’ , ‘y’ , ‘4’ , ‘\u0000’ , ‘\uffff’ Null character constant (not printable) 2)String literals:-If one or multiple characters are enclosed within double codes called String literals. Eg:“x” , “Hello” , “2” 3)Boolean literals(logical):True/false 4)Integer literals:-There are three types of integer literals. a)Decimal-10,15,100,………… b)Octal-07. c)Hexa-decimal-Oz0000,Oxffff 5)Floating literals:a)double format-3.14,5.6………….. b)float format-3.14f,5.6f………….. Scope of Variables(Life time) Scope decide variable accessibility i.e. has long variable is accessible is determined its scope. There are three types of scope1)Local variable(auto variable) 2)Static variable(class variable) 3)Non-static variable(instance variable / object) 1)Local variable:-If any variable is declared inside any method or passed as argument to any method are called variable.This is because variables value is local to that method means we cannot access that value from outside that method. Syntax:Return type method name(arg) { Datatype variable name=constant value; } Eg:-public static void main(String args[]) { int x=10; } Note:-Local variable must be initialize before use otherwise compilation fail with error. Error:-Variable “variable name” might not has been initialized. How to call local variable:Since we cannot call any local variable outside of that method in which it has been declared. So, variable can access directly. Eg:class local var { Public static void main(String arg[]) { int z=10; //local variable System.out println(“z=” +z); } } 2)Static Variable:-If variable is declared using static keyword just below class declaration above any method is called static variable. Static variable are also called class variable because variable scope belong to class itself.i.e. as long as class is accessible variable will be accessible. Syntax:- Class ClassName { Static datatype variable name=value; Return type method(args) { } } Note:-Value of static variables is shareable by all instance of the class. How to call static variable:There are three waysi)Directly using variable name but this is allowed only within same class. ii)Using className.Variablename; this is most widely used approach in java.It can be use from anywhere.i.e. from same class or from other classes. Eg:System.out-Here system is pre-defined class,defined in java.lang package and out is the static member of System class. iii)Since,static variable can be shared by all instances of the class.So, using object or instances we can call static variable. Objectref.variableName; How to create object:Object are instances of the class use to access members of the class.We can create any instance using keyword new and using constructor(at least default constructor). Syntax:className object=new className(); Memory allocate default constructor Eg:- Test t=new test( ); t.member(variables & methods( )); Eg:Class testvar { Static int z; { Class staticvar { Public static void main(String args[]) { Testvar sv=new testvar( ); System.out.println(“Direct access to z=” +z); //not allowed from other classes System.out.println(“Using classname.variable z=” + testvar.z); System.out.println(“Using objectref.variable z=” +sv.z); } } O/P:Using classname.variable z=0 Using objectref.variable z=0 3)Non-static variable:-If variable is declared without static keyword just below class declaration or above any method it is called non-static variable. Syntax:Class className { Datatype variable name=value; Return type method(args) { } } How to call non-static variable:There is one and only one way is allowed to access non-static variable i.e. using Objectref.variables Note:-Non-static variable cannot be reference from static context(methods) directly.It is allowed only with objectref.variable. Otherwise compilation fail with error “non-static variable variable name cannot referenced from static context. Eg:class textvar { Int z; } Class NonStaticVar { Public static void main(String arg[ ]) { Testvar sv=new testvar( ); //System.out.println(“Using className.variable z=” + testvar.z); //This is allowed only for static members. System.out.println(“Using className.variable z=” +sv.z); } } Default values of variables:In java local variable must be initialized explicitly while instance variable and class variable are initialized implicitly (automatically) using some default values according to datatypes. Datatype Default values Byte Short 0 Int Long Float 0.0 Double Boolean false Char no O/P(because of ‘\u0000’) Any class type(Eg.String) null Methods in Java:Methods are used to implement the attributes to produce some output,in java methods can be mainly of two types1)Static method(class method) 2)Non-static methodThere are four partsi)return type:-These part specify which type of value should be return back to the caller.Return type can be either of primitive type or it can be of class type also. If return type is not required then keyword void must be used.Otherwise compile time error-“return type required”. ii)Method name:-It can be any valid variable name i.e. method name should not be a keyword. iii)Arguments or parameter list:-The values pass to any method using ( ) are called arguments or parameter list. Method may or may not have arguments. Similar to return type arguments also can be either of primitive type or class type. iv)Method body:-Set of statements and expression written within { } is called method body. Method body may contain return statement to return the updated value(result) back to the caller. 1)Static method:-If method is defined using static keyword then it is called static method or class method because method scope belongs to class. Syntax:Class ClassName { Static returntype method name(arg) { Statements; Exp; [return statement]; Optional } } How to call static method:Similar to static variables,static method can be called in three waysi)Directly usingmethodName(args); but these is allowed only within same class. ii)UsingclassName methodName(args); These is most widely used approach in java to call static methods. iii)Since static members(variables & methods) are global for all instance,therefore using objectreference.methodName(args); 2)Non-Static method:-If a method is defined using without static keyword is called nonstatic or instance method. Syntax:Class className { Returntype methodName(args) { Statements; Exp; [return statements]; } } How to call non-static method:There is only one way allowed i.e. using objectreference.methodName(args) Eg:Class staticMethod { Static int z=20; //class variable Static void square() { Int r=z*z; System.out.println(“Square of” +z+”=” +r); } Static public void main(String xyz[]) { New staticMethod().square(); //calling method Or// staticMethod v =new staticMethod(); v.square( ); square(); //or StaticMethod.square(); } } Operators:Operators are specific symbols used to perform different operations likearithmetic,logical,relational etc. Java support following operations1) Arithmetic operators:+ , - , * , / , %(binary operator because two operands to operate) 2)Assignment operators:= , += , *= ,-= , %= Eg:-int x=5 X==15;(x=x+15) X=5+15; X=20; 3)Unary operators:++(Increment) --(Decrement) Since,this operators required single operands to operates therefore called Unary. The increment operator increase the operand value by 1.By decrement operator decrease the operand value by 1. There are two forms of Unary operatorPre Post Systax:Operator operand; Operator operand; ++a; a++; --a; --a; Eg:- Eg:- Int x=10; int x=10 Int y=++x; int y=x++; Int z=--x; int z=x--; Y=11 y=10 Z=10 z=11 X=10 x=10 4)comparision/Relational Operators:==(equal to) !=(not equal to) <(less than) <=(less than or equal to) >(greater than) >=(greater than or equal to) In java relational operators always produce the o/p in Boolean terms i.e. true and false while in case of C & C++ it was 0 & 1. 5)Logical Operators:&&(and) ||(or) Short circuit operator(quick decision) !(nor) & | normal operator all condition check Logical operator also produce the o/p in Boolean term i.e. true and false. 6)Bitwise operator:& bitwise and | bitwise or ~ bitwise complement ^ bitwise ex-or << bitwise left shift >> bitwise right shift >>>bitwise unsigned bitwise right shift. Since,this operator works according to bits, zero and one. Eg:1)int x=5; int y=x&2; Y=false=>0 2)int x=5; int y=x|2; Y=true=>7 3)int x=5; int y=x^2; Y=true=>7 Left shift:-(<<) Num*2n Where n is no. of bits value is to be shifted and num is the no.which value is to be shifted. int x=4; int y=x<<2; y=16 Right shift:-(>>) n/2n int x=4 int y=x>>2 int y=1 Unsigned bitwise right shift(>>>):These operator work similar to right shift operator if no. is positive but if no. is negative then we will get very large value because all lower bits value is shifted with higher bits.Therefore result is large value. 00000001 11111110 Type casting:-(Type conversion) It is the way of converting the value of one type into another type. There are two ways of type casting1)Implicit(automatic) 2)Explicit(manually) 1)Implicit:-These type of conversion is takes place only if destination type variable is larger than source type variable,but reverse is not allowed. Eg:-We can assign the addition of byte,short,int to long datatype anytime. Eg:Class implicitCast { Public static void main(String agrs[ ]) { Short a=10,b=20; int c=a+b; See error //short c=a+b;//there will be error. System.out.println(“Addition of”+a+” and “+b+” =” +c); } } 2)Explicit:-Implicit conversion is good but not applicable everywhere.. Eg:-we cannot assign the value of int type variable to byte or short type variable. Therefore we must have to use explicit or manual casting.This is also called narrowing conversion. There are three types of explicit castingi)typeCasting between primitive types ii)typeCasting between object to primitive or vice versa iii)typecasting between object i)Type Casting between primitive types:-If both source and destination type are of primitive datatype then we can use following syntaxDatatype variable=(datatype)variable or(exp); Destination source Eg:class explicitcast { public static void main(String args []) { short a=10.b=20; short c=(short) (a+b); Explicit casting System.out.println(“Addition of” +a +”and “ + b” + “=”+c); int x=280; byte bt=(byte)x; Explicit casting System.out.println(“x=” +x +”\n b=” +bt); int x=90; char ch=(char)n; System.out.println(“ch=” +ch+”n=”+n); } } O/P:-Addition of 10 and 20=30 X=280 B=24 (280-256=24) Ch=z n=90 2)TypeCasting between primitive to object & vice versa:Since object and primitive datatypes both are two different things therefore we cannot assign the value of one to another. Java provide set of pre-defined classes called wrapper classes.This classes provide set of constructor and methods using which we can typecast primitive value in an object or an object value in a primitive. Primitive types wrapper classes 1)byte Byte 2)short Short 3)long Long 4)int integer 5)float Float 6)double java.lang.Number class Double 7)Boolean Boolean 8)char Character sub classes Integer class:The integer class wraps a value of the primitive type int in an object.An object of type integer contains a single field whose type is int. In addition,this class provides several methods for converting an int to a Sring and a String to an int,as well as other constants and methods useful when dealing with an int. Constructor:i)Integer(int value) Constructs a newly allocated integer onject that represents the specified int value. Methods:i)static int passeInt(String s) Passes the string argument as a signed decimal integer. ii)static integer valueOf(int i) Returns an integer instance representing the specified int value. iii)static integer valueOf(String s) Returns an integer object holding the value of the specified String. iv)int intValue () Returns the value of this integer as an int. v)long longValue() Returns the value of this integer as a long. Note:-We cannot typecaste any value into Boolean type or any Boolean value to any other type. a)Primitive to object:int x=10; //primitive integer i=new integer(x); //object float f=3.14; //primitive float f=3.14f; //primitive float f1=new float (f); //object primitive to object b)object to primitive:String s1=”2”; String s2=”3”; String s3=51+52; O/P:-53=23 concatenation(This is drawback) Step1):int x=Integer.parseInt(s1); int y=Integer.parseInt(s2); Object to primitive int z=x+y; O/P:-z=5 parseInt is static method of Integer class. Step2):- as it for float,double,long etc int x=Integer.valueOf(s1).intValue(); Integer static Non static int y=Integer.valueOf(s2).intValue(); Or integer i=integer.valueOf(s1); int x=i.intValue(); Type Casting between object to object:We can assign the reference of one object to another object only if they are related with parent child relationship. Constructor:Constructor is special method use to initialize data(variable) of a class.Constructor has following characteristics. i)It must have same name as a class name. ii)Constructor has no return type even keyword void is also not used.But constructor can have zero or multiple arguments.Constructor having no argument is called default constructor while constructor containing one or multiple argument called parameterized constructor. iii)Constructor are called automatically(implicitly) whenever an object is created. iv)Constructor has similar accessibility as of its class i.e. if class is public then constructor is by default public. Eg:Public class test { Test() { } } v)Java provide default constructor for each and every class only if there is no other constructor available in class.If our class contain any constructor then using that constructor only object can be created. Syntax:Class ClassName class ClassName { { className() className(args) { { } } } } Constructor overloading:When class contain more than one constructor containing different types & different no. of arguments then it is called constructor overloading. It is used to implement static/compile/time/early binding polymorphism in java. The advantage of constructor overloading is that we can create different object for same class by passing different arguments. Eg:Class ClassName { className() { } className(arg1) { } className(arg1;arg2) { } } Note:-The arguments can be either of primitive type or it can be of any class type. How long we can overload constructor:i) constructor names must be similar & it must contain different types of arguments. ii) If datatype match than no. of parameter must be different. iii) If datatyoe and no. of parameter both are match then sequence(order) must be different. Eg:Class ConstructDemo { Int x,y; constructDemo() { X=10; Y=20; System.out.println(“Default constructor”); } ConstructDemo(int x1,int y1) { X=x1; Y=y1; System.out.println(“Parameterized constructor”); } ConstructDemo(constructDemo cd) { X=cd.x; Y=cd.y; System.out.println(“Constructor having class type arg”): } Void disp() { System.out.println(“x=” +x + “ andy=” +y); } Public static void main(String arg[]) { constructorDemo cd1=new consstructDemo(); cd1.disp(); constructDemo cd2=new constructDemo(40,60); cd2.disp(); constructDemo cd2=new constructDemo(cd1 or cd2); cd3.disp(); } } Method overloading:When more than one method are defined using same name but by passing different types & different no. of arguments it is called method overloading. It is used to implement static/compile/time polymorphism in java. Note:-Return type does not play any important role in method overloading. Syntax:Class ClassName { Returntype methodName() { } Returntype methodName(arg1) { } Returntype methodName(arg1,arg2) { } } Eg:-MethodOverloading.java Class MethodOverloading { Int x=10,y=20,z; Void add() { Z=x+y; } Void add(int x1,int y1) { X=x1; Y=y1; Z=x+y; } Void Display() { System.out.println(“Addition of” +x +”and “ +y+”=”+z); } Public static void main(String args[]) { MethodOverloading m1=new MethodOverloading(); M1.add(); M1.Display(); M1.add(40,50); M1.Display(); } } O/P:Addition of 10 and 20=30 Addition of 40 and 50=90 Use of “this”:Keyword “this” can be used to refer the current object of same class type.It is actually used to differentiate between local variables and instance variables. I.e. this.variable Refer the instance variable while direct reference to the variable it will refer the local variable not the instance variable. Eg:Class ThisDemo { Int x,y; //instance variables ThisDemo(int x,int y) { this.x=x; //x=x; this.y=y; //y=y System.out.println(“Parameterized constructor”); } Void add() { Int z=x+y; System.out.println(“Addition of” +x+”and “+y+”=”+z); } Public static void main(String args[]) { ThisDemo td=new ThisDemo(40,60); Td.add(); } } O/P:Without using “this’;Parameterized constructor Addition of 0 and 0=0 Using “this”:Parameterized constructor Addition of 40 and 60=100 Eg:Import java.io.*; Class UserInput { Pubic static void main(String args[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(“Enter no1”); Int x=Interger.parseInt(br.readLine()); System.out.println(“Enter No2”); Int y=Interger.parseInt(br.readLine()); Int z=x+y; System.out.println(“Addition of “+x+”and”+y+”=”+z); } } We have to use try-catch or throws Note:i)We have use import java.io.*; because this is predefined package which contain the definition of two predefined classes i.e. BufferReader and InputStreamReader. ii)We have use throws statement or try-catch. This is because readLine() method throws IO Exception.If exception is not handle either using throws or try-catch statement then we will get compile time error. Error:-Unreported exception java.io.IOException;must be caught or declared to be thrown. iii)We have use int x=Integer.parseInt(br.readLine()); to read the input and typecaste that input in integer primitive type. Control Flow Structure:The term flow of control refers to the order using which program statements are executed.Right from C every languages support three types of control flow structure. 1)Linear/Sequential flow structure 2)Conditional flow structure 3)Iterative/Repetitive control flow structure Note:-By default every program statements are executed line by line or sequentially i.e. control is flow only in one directly. Conditional flow structure:As the name suggest the flow of control will always depend on evaluation of certain condition i.e. if condition is match or true then control is flow to a specified way otherwise it flows to some alternative way. It is implemented usingi)if statement ii)if-else statement iii) if-else-if statement iv) switch-case statement Eg:-UserNum Class UserNum { Public static void main(String args[])throws Exception { BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(“Enter no”); Int x=Integer.parseInt(br.readLine()); If(x%2==0) System.out.println(x+”is even no”); else System.out.println(x+”is odd no”); } } Eg:-GreaterNum Class GreaterNum { Public static void main(String args[])throws Exception { BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(“Enter num1”); Int x=Integer.parseInt(br.readLine()); System.out.println(“Enter num2”); Int y=Integer.parseInt(br.readLine()); System.out.println(“Enter num3”); Int z=Integer.parseInt(br.readLine()); If(x>y && x>z) System.out.println(x +”is greater than”+y+”and+z); Else if(y>x && y>z) System.out.println(y+”is greater than”+x+”and+z); Else if(z>x && z>y) System.out.println(z +”is greater than”+y+”and+x); Else System.out.println(“All no. are equal”); } } We can pass only byte,short,int & char in switch-case. 3) switch-case Eg:import java.io.*; class CalcFunction { Public static void main(String args[]) throws Exception { BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(“1. Addition \n 2.Substraction \n 3.Division \n 4.Multiplication \n 5.Exit \n Enter your choice…………”); Int x=Integer.parseInt(br.readLine()); System.out.println(“Enter num1”); Int a=Integer.parseInt(br.readLine()); System.out.println(“Enter num2”); Int b=Integer.parseInt(br.readLine()); Int c=0; Switch(x) { Case1:c=a+b; System.out.println(“Addition of “+a+”and”+b+”=”+c); Break; Case2:c=a-b; System.out.println(“Substraction of “+a+”and”+b+”=”+c); Break; Case3:c=a*b; System.out.println(“Multiplication of “+a+”and”+b+”=”+c); Break; Case4:c=a/b; System.out.println(“Division of “+a+”and”+b+”=”+c); Break; Case5:system.exit(0); Break; Default:System.out.println(“Invalid choice”); } } } 3) Iterative/Repetitive control flow structure:Using this control flow structure it is possible to execute single statement or group of statements multiple times as long as condition remains true. This structure is implemented using loops.There are three types of loopsi)while loop ii)do……while loop iii)for loop In every loop there are mainly three partsa)Initialization of counter:It is used to initialize the variable using which is to be executed.In case of while loop & for loop initialization is must.but in do ………..which it is optional. b)Conidition:- This past consist of Boolean expression i.e. expression is evaluated as true then only body of the loop gets executed.If condition is fail/false then body will not execute and loop is terminated. c)Increment/Decrement of counter:This part is used to increase or decrease the value of counter variable.After increment/decrement of counter variable control is transfer to the condition part. Syntax:- i) While loop initialization; while(condition) { Statements; Exp; [increment/decrement]; } ii) do-while-loop initialization; do { Statements; Exp; [inc/dec]; } While(condition) iii) for loop for(init;condition;inc/dec) { Statements; Exp; } Eg:Import java.io.*; Class LoopStat { Public static void main(String agrs[])throws Exception { Char ch=’y’; While(ch==’y’ || ch==’Y’) { BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(“Enter a number”); Int x=Integer.parseInt(br.readLine()); Int i=1; While(i<=10) { Int j-x*i; System.out.println(x +”*”+i+”=”+j); i++; } System.out.println(“Enter y for continue”); Ch=(char)br.read(); } } } Use of break & continue:The break statement can be use inside switch case or looping statement.It is use to break the flow of control to come out of switch or loop i.e. break statement sent the control at bottom part. Continue sent the control at the beginning. Eg:For(int i=0;i<3;i++) { For(int j=3;j<6;j++) { If(j<4) { Break; } Else { System.out.println(“i=”+i+”j=”+j); } } } Eg:-BreakDemo.java Class BreakDemo { Public static void main(String args[]) { For(int i=0;i<3;i++) { For(int j=3;j<6;j++) { If(j>4) { Break; } Else { System.out.println(“i=”+i+”and j=”+j); } } } } } Eg:class ContinueDemo { Public static void main(String arg[]) { For(int i=0;i<3;i++) { For(int j=3;j<6;j++) { If(j>3) { Continue; } Else { System.out.println(“i=”+i+” and j=”+j); } } } } } In for loop ‘continue; statement sent the control to inc/dec part while inn ‘break’ statement sent to conditional operator part. Ternary or Conditional Operator:It consist of ? and :. Since it required three operand therefore called Ternary. Syntax:Exp1 ? exp2 : exp3 true False Expression1 always must be Boolean type if it return true then ‘exp2’ is executed,otherwise ‘exp3’ is executed.Since it is use to check the condition so also called conditional operator.It can be use as an alternative for ‘if….else’. Eg:- Class TernaryDemo { Public static void main(String args[]) { System.out.println((3<4)?”3 is greater”:”4 is greater”); } } Array:An array is collection of similar data items which are referred using common name but by using unique index.Index always begins with ‘O’ therefore index of last element will be less than size. Types of Array:1)single Dimension Array 2)multi Dimension Array 1)Single Dimension Array:An array which elements are referred using single index is called Single Dimension Array.In order to implement array we have to follow following stepsi)Declaration of Array ii)Construction of Array iii)Initialized of Array Since in java an Array is constructor using ‘new’ keyword as similar to object.So, it is also called(Arrays in object)object in java. i)Declaration of Array:Syntax:Datatype arrayname[]; Or Datatype [] arrayname; Where datatype can be either of primitive type or it can be of any class type. Eg:Int []arr; Char ch[]; ii)Construction of Array:Since,declaration part specify only two things arrayname & datatype but it is not cleared how many elements array will contain.So,in java array must be constructed before use. Syntax:Arrayname=new Datatype[size]; Eg:Arr=new int[4]; Ch=new char[3]; Str=new String[2]; Note:-We can combine both step(i) & (ii) in single step using following syntax:Datatype arrayname[]=new Datatype[size]; Or Datatype[] arrayname=new Datatype[size]; Eg:Int arr[]=new int[4]; Char ch[]=new char[5]; String str[]=new String[2]; iii)Initialization of Array:There are two ways to initialize an array element.They area)Implicit(Automatically) b)Explicit(Manually) a)Implicit:In java an array elements are initialize using the default value of specified datatype.i.e. byte short int 0 long float double 0.0 Boolean false char no O/P(because of null character constant ‘\u0000’) any classtype null eg-String Note:Java provide pre-define instance variable namelyLength-it can be use to fine out length of any array Syntax:int len=arrayName.length;(datatype always int) Eg:Class ArrayInit { public static void main(String arg[]) { Int arr[]=new int[4]; for(int i=0;i<arr.length;i++) { System.out.println(“arr[“+i+”]=” +arr[i]); } } } O/P:arr[0]=0 arr[1]= 0 arr[2]=0 arr[3]=0 b)Explicit(Manual) Initialization:There are three ways to initialize array explicitly. i)arrayname[index]=value; //inherited from C language Eg:arr[0]=10; arr[1]=20; arr[2]=30; ii)Datatype arrayname[]={value1,value2,……..}; Eg:Int arr[]={10,20,30,40}; Char ch[]={‘x’ , ‘y’ , ‘z’, ‘2’}; String str[]={“x”,”abc”,”xyz”) iii)Datatype arrayname[]=new datatype[] {value1,value2,………….}; Eg:int arr[]=new int[] {10,20,30,40}; char ch[]=new char[] {‘x’ ,’y’ , ‘z’}; Eg:-ArrayInit.java Import java.io.*; Class ArrayInit { Public static void main(String arg[]) throws Exception { Int x=0; Int arr[]=new int[5]; BufferReader br=new BufferReader(new InuputStreamReader(System.in)); System.out.println(“enter 5 no.”); for(int i=0;i<arr.length;i++) { arr[i]=Integer.parseInt(br.readLine()); x=x+arr[i]; } for(int i=0;i<arr.length;i++) { System.out.println(“arr[“+i+”]=” +arr[i]); } System.out.println(“Addition=” +x+” avg=”+(x/5)); } } Eg:-ArraySorting.java import java.io.*; class ArraySorting { public static void main(String arg[])throws Exception { int arr[]=new int[5]; BufferReader br=new BufferReader(new InuputStreamReader(System.in)); System.out.println(“enter 5 no.”); for(int i=0;i<arr.length;i++) { arr[i]=Integer.parseInt(br.readLine()); } System.out.println(“Before Sorting”); for(int i=0;i<arr.length;i++) { System.out.println(“arr[“+i+”]=”+arr[i]); } for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr.length;j++) { If(arr[i]>arr[j]) { Int t=arr[i]; arr[i]=arr[i]; arr[j]=t; } } } System.out.println(“After Sorting”); for(int i=0;i<arr.length;i++) { System.out.println(“arr[“+i+”]=”+arr[i]; } } } O/P:Before Sorting After sorting arr[0]=8 arr[0]=2 arr[1]=6 arr[2]=5 arr[2]=2 arr[2]=6 arr[3]=9 arr[3]=8 arr[4]=5 arr[4]=9 MultiDimesional Array:If an array elements are referred using multiple indexed they are called multidimensional array i.e. if an array element is referred by two indexes called 2-D array, similarly if an array is referred using 3-D array………….and so on. But java does not support multi dimensional array however this feature can be implemented using array of array. Implementing 2-D array in java:System:Datatype arrayName[] []=new datatype[size1] [size2]; In java size1 always must be specified, it represented size outer array.While size is optional.i.e. it may be or may not be used. If size1 and size2 both is specified then it represented element similar to 2-D array but if size2 is omitted then element of inner array can be equal or unequal. int A[] []=new A[2] [2]; int A[] []=new A[2] []; Eg:class ArrayOfArray { public static void main(String arg[]) { Int arr[] []=new int[2] []; arr[0]=new int [] {10,20}; arr[1]=new int[] {10,20,30,40,50}; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { System.out.println(arr[i][j]+”\t”); } System.out.println(); } } } O/P:10 20 10 20 30 40 50 Use of Math class:The class Math contains methods for performing basic numeric operation such as the elementary exponential, logarithmic, squarent and trigonometric function. Note:- Since all method of Math class are static methods therefore they can be called using following syntaxMath.method(args); className Constants of Math class:Static double PI The double value, this is closer than any other to PI,the ratio of the circumference of circle to its diameter. Methods:1) i)static double abs(double a) ii)static float abs(float a) iii)static int abs(int a) iv)static long abs(long a) Return the absolute value of the according to the arguments. 2) i)static double max(double a,double b) ii)static float max(float a,float b) iii)static int max(int a,int b) iv)static long max(long a,long b) Returns the maximum value according to arguments. 3) i)static double min(double a,double b) ii)static float min(float a,float b) iii)static int min(int a,int b) iv)static long min(long a,long b) Returns the smaller value according to argument. 4)static double pow(double a,double b) Return the value of the first argument reused to the power of the second argument. v)static double random() Return a double value will the sign greater than or equal to 0.0 and less than 1.0 vi)static long round() Return the closest long to the argument. Static int round() Return the closest int to the argument. vii)static double sqrt(double a) Return the correctly rounded positive square root of a double value. viii)static double todegrees(double angred) Convert an angle measured in degrees to an approximately equivalent angle measured in degree. ix)static double toRadius(double angdeg) Convert the angle measured in degrees to an approximately equivalent angle measured in radians. x)static double ceil(double a) Return the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. xi)static double floor(double a) Return the largest double value that is less than or equal to the argument and as equal to a mathematical integer. Eg:Class MathDemo { public static void main(String arg[]) { System.out.println(“SQRT(2)=”+Math.sqrt(2)); System.out.println(“pow(2)=”+Math.pow(2,3)); System.out.println(“abs(-12)=”+Math.abs(2)); System.out.println(“max(2,3)=”+Math.max(2,3)); System.out.println(“min(2,3)=”+Math.sqrt(2,3)); System.out.println(“A random num=”+Math.ramdom()); } } JCP exam Class Test1 { public static void main(String args[]) { System.out.println(Math.floor(Math.random()); } } String class:The String class represent character string.All String literal in java program,such as “abc” are implemented as a instance of the class. String are constant; their value cannot be changed after they are created. Constructor:1)String():-Initialized a newly created string object.So,that it represented an empty character sequence. 2)String(byte[] bytes):-Constructs a new string by decoding the specified array of bytes using the platforms. Default CharSet. 3)String(byte[]bytes,int offset,int length) Construct a new string by decoding the specified substring of bytes using the platform default charset. 4)String(string origina) Initialized the newly created string object so that it represented same sequence of character as the argument in other words,the newly created string is the copy of the argument string. 5)String(StringBuffer buffer) Allocates a new string that contain sequence of character currently contained in the string buffer argument. 6)String(StringBuilder builder) Allocates a new String that contains the sequence of character currently contained in the string builder argument. 7)String(char[] value) Allocates a new String.So that it represent the sequence of the character currently contained in the character array argument. Methods:A)Object creator Method:a)String concat(String str) Concatenates the specified string to the end of this string. b)String toLowerCase() Convert all of this character in this string to lower case using the rule of the default locate. c)String toUpperCase() Convert all the character in the string to lower case using the rule of default locate. d)String toString() The object is itself return. e)String trim() Return a copy of the string,with leading and trailing whitespace omitted. f)String substring(int beginInbox) Return a new string that is substring of the string. g)String substring(int beginInbox,int Endbox) Return a new String that is substring of the string. h)String replace(char old,char newchar) Return a new string resulting from replacing all occurrences of oldchar in this string with newChar. i)String replaceFirst(String regex,string replacement) Replace the first subString of the string that match the given regular expression with given replacement. j)String replaceAll(String regex,String replacement) Replace each substring of the string that match the given regular expression with the given replacement. B)Comparison Methods:a)Boolean equal(object suffix) Test if this string ends with specified suffix. b)Boolean equalIgnoreCase(String anotherString) Compare this string to another string, ignores case consideration. c)int compareTo(String anotherString) Compare to string lexicographically. d)int compareToIgnoreCase(String str) Compare two strings lexicographically,ignoring case difference e)Boolean startsWith(String prefix) Test if this string start with specified prefix. f)boolean endWith(String suffix) Test if this string end with specified suffix. C)General Purpose Method:a)int length() Return the length of the string. b)char charAt(int index) Return the char value at the specified index. Eg:Class StrConstruct { public static void main(String arg[]) { byte[] b={65,66,67,68,69,50}; char ch[]={‘x’ , ‘y’ , ‘z’ , ‘1’ , ‘2’}; String s1=new String(); String s2=new String(b); String s3=new String(b,0,3); String s4=new String(ch); String s5=new String(ch,2,2); String s6=new String(s2); System.out.println(“S1=” +s1); System.out.println(“S2=” +s2); System.out.println(“S3=” +s3); System.out.println(“S4=” +s4); System.out.println(“S5=” +s5); System.out.println(“S6=” +s6); } } O/P:S1= S2=ABCDE2 S3=ABC S4=xyz12 S5=z1 S6=ABCDE2 Eg:Class StrMathods { public static void main(String args[]) { String s1=new String(“Hello”); String s2=”hello”; System.out.println(“S1=” +s1); System.out.println(“S2=” +s2); System.out.println(“S1.length=”+s1.length()); System.out.println(“S2.length=”+s2.length()); System.out.println(“S1.toLowerCase=”+s1.toLowerCase()); System.out.println(“S1.toUpperCase=”+s1.toUpperCase()); System.out.println(“S1.equals(s2)=”+s1.equals(52)); System.out.println(“S1.equalsIgnoreCase(52)=”s1.equalsIgnoreCase(52)); System.out.println(“S1.CompareTo(52)=”s1.CompareTo(52)); System.out.println(“S1.Concat(52)=”+s1.Concat(52)); } } Class StringBuffer:A thread-safe, mutable sequence of characters.A string buffer is like a String,but can be modified. At any point in time it contains some particular sequence of character,bur the length & content of the sequence can be changed through certain method calls. Constructor:StringBuffer() Constructs a String buffer with no character in it and an initial capacity of 16 character. StringBuffer(int capacity) Constructs a String buffer with no character in it and the specified initial capacity. StringBuffer(String str) Constructs a String Buffer initialized to the contents of the specified String. Methods:StringBuffer append(int i) Appends the string representation of the int argument to this sequence. StringBuffer append(String str) Appends the String representation of the int argument to this sequence. StringBuffer append(String str) Appends the specified string to this character sequence. StringBuffer insert(int offset,int i) Insert the String representation of the second int argument into this sequence. StringBuffer insert(int offset,String str) Insert into this string into this character sequence. StringBuffer reverse() Courses this character sequence to be replaced by the reverse of the sequence. StringBuffer replace(int start,int end,String str) Replace the character in a substring of this sequence with character in the specified String. int capacity() Return the current capacity. int length() Returns the length(character count). String toString() Returns a String representing the data in this sequence. Eg:-StrBuffer.java class StrBuffer { public static void main(String arg[]) { StringBuffer s1=new StringBuffer(“Hello”); System.out.println(“s1=”+s1); s1.append(“Friend”); s1.append(123); s1.append(‘x’); System.out.println(“Again s1=”+s1); S1.reverse(); System.out.println(“In reverse s1=”+s1); } } O/P S1=Hello Again s1=Hello friends 123 x In reverse s1=x 321 sdneirf olleH Inheritance:It is use to reuse code of an existing class into another classes.The existing class is called Parent/Base/Super white the newly created class iss called Child/Derived/Sub. Advantages: Reusability of existing code. Reduce code redundancy Save the memory space because same code can be reuse. It same the limiting to rewrite same code. Type of Inheritance:1)Single Inheritance 2)Multilevel Inheritance 3)Multiple Inheritance(Not Supported by java) 4)Hierarchical Inheritance 5)Hybrid Inheritance 1)Single Inheritance:class 1 Attributes & Methods In UML(Unified Modeling Language the arrow is upside) class 2 Attributes & Methods of own If subclass is created using only one super class,this type of inheritance is called Single Inheritance. The sub class can access the attributes & method of its own as well as attributes & method of its Super Class except private attributes & private methods of Super class. In order to create an object we should create the object of Sub class because using object of sub class we can access the members of both subclasss & Superclass. Syntax:Class Class1 { } class Class2 extends Class1 { } Note:-Here extends is keyword in java use to refer the super class name. Access Specifier/Access Modifier:There are four types of access Specifier in java they arei)private ii)protected iii)public iv)default/package level i)private:-Private members of any class cannot be access from outside of that class.So,this is most restricted type of access Specifier. ii)protected:-protected members of a class can be use either within same class or from any Subclasses. iii)public:-public members of a class is accessible from anywhere i.e. public members can be use by any classes of some package or any other package. This is most widely accessiable specifier. iv)default/package level:-If neither private nor protected not private keyword are used than accessibility is default means default members can be use by any class bur within same package. Eg:-SingleInheritance.java Class AddDemo { Int x,y; void getData(int x1,int y1) { x=x1; y=y1; } void add() { int z=x+y; System.out.println(“Addition of”+x+”and”+y+”=”+z); } class SubDemo extends AddDemo { void Sub() { int z=x-y; System.out.println(“Subtraction of”+x+” and “+y+”=”+z); } } class SingleInheritance { public static void main(String args[]) { subDemo sd=new SubDemo(); sd.getData(20,10); sd.add(); sd.sub(); } } B)Multilevel Inheritance:Class1 (grandfather) Top level super class Class2 (father) Intermediates super class subclass Class3 (chtild) If subclass is created using an existing Sub class.This type of inheritance is called Multilevel Inheritance. The existing sub class is called Intermediates Superclass.The sub class can access the members of its own and members of intermediates super class and members of Top level super class. Eg:class AddDemo { int x,y; void getData(int x1,int y1) { x=x1; y=y1; } void add() { int z=x+y; System.out.println(“Addition is”+z); } class SubDemo extends AddDemo { Void sub() { int z=x=y; System.out.println(“Subtraction is”+z); } } class MultiDemo extends SubDemo { Void mul() { int z=x+y; System.out.println(“Multiplication is”+z); } } } class MultiInherit { public static void main(String args[]) { MultiDemo md=new MultiDemo(); md.getData(85,15); md.add(); md.sub(); md.mult(); } } 3)Hierarchical Inheritance:Class1 Class3 class2 Syntax:class Class1 { } class Class2 extends Class1 { } class Class3 extends Class1 { } If more than one subclasses are created using same Super class,this type of inheritance is called Hierarchical Inheritance. We must have to create the objects of all sub classes individually because using object of one subclass we cannot call the members of another subclass. Eg:-Result.java class Student { int r; String n; void getInfo(int roll,String name) { r=roll; n=name; } void getData(int roll,String name) { r=roll; n=name; } Void display() { System.out.println(“Name:”+n +”\n Roll No:”+r +”\n”); } } class Test1 extends Student { int s1,s2; int getMark(int sub1,int sub2) { s1=sub1; s2=sub2; System.out.println(“Subject1:”+s1+”Subject2:”+s2); int z=s1+s2; return z; } } class Test2 extends Student { int s3,s4; int getMark(int sub3,sub4) { s3=sub3; s4=sub4; System.out.println(“Subject3:”+s3+”Subject4:”+s4); int z1=s3+s4; return z1; } } class Result { public static void main(String arg[]) { Test1 t1=new Test1(); Test2 t2=new Test2(); t1.getData(1,”abc”); t1.display(); int z=t1.getMark(75,70); int z1=t2.getMark(66,65); int sum=z+z1; System.out.println(“\n Total Marks=”+sum); int avg=sum/5; System.out.println(“\n Average is=”+avg); } } Multiple Inheritance:class1 class2 class3 If sub class is created using more than one super classes,this type of inheritance is called Multiple Inheritance. But java does not support multiple inheritance i.e. It is not possible to create sub class which is begin inherited from multiple classes. However Interfaces are use to implement multiple interfaces in same class. Calling Variable of Super class:Java provide pre-define keywords namely ‘super’ this is use to differentiate between variable of sub class ‘flooth’ having same name. Eg:-super.variable; It will call the variable of super class. variable or It will call the variable of same class. this.variable Eg:class class1 { int x=10; } class Class2 extends Class1 { int x=20; void add() { int z=super.x+x; //super x+this.x; System.out.println(“Addition of”+super.x+”and”+x+”=”+z); } class SuperVar { public static void main(String arg[]) { Class2.c2=new Class2(); C2.add(); } } O/P:Addition of 10 and 20=30 Without super o/p will be Addition of 20 and 20=40 Calling Constructor of super class:All sub classes make use of super(); implicitly call the default constructor of super class. Similarly,by using super(args); we can explicitly call parameterized constructor of super class. Note:1)Call to super must be the first statement in sub class constructor body otherwise compilation fail with error- “Call to super must be the first statement…….” 2)If super class contains parameterized constructor then it must contain default constructor also because any constructor of sub class(default or parameterized) implicitly call the default constructor of super class. Eg:class Class1 { int x=10; Class1() { System.out.println(“This is default constructor of super class x=”+x); } class1(int x1) { x=x1; System.out.println(“This is parameterized constructor of super class=”+x); } } class Class2 extends Class1 { int x=20; Class2() } Super(); //if do not write super O/P same. System.out.println(“This is default constructor of sub class x=”+x); } Class2(int x1) { super(x1); // do not give args & do not write super. System.out.println(“This is parameterized constructor of sub class x=”+x); } } class Superconstruct { public static void main(String arg[]) { Class2 c2=new Class2; Class2 c3=new Class2(60); //c2.Class2(60); } } O/P:This is default constructor of super class x=10 This is default constructor of sub class x=20 This is parameterized constructor of super class x=60 This is parameterized constructor of sub class x=60 Method Over riding:If method of super class is redefine by sub class using exact signature i.e. method accessibility,return type,method name,types of srguments,no.of argument & sequence of arguments all must be same.This is called Method Over riding. It is use to implement dynamic/run time/late binding polymorphism in java.i.e. method of super class is Re-define in sub class to hide the implementation details of super class method in sub class. Syntax:- class Class1 { Returntype method(args) { } } class Class2 extends Class1 { Returntype method(args) { } } Eg:class Rectangle { int w,h; void getData(int w,int h) { this .w=w; this.h=h; } void area() { int a=w*h; System.out.println(“Width=”+w+” and height=”+h+”\n Area of Rectangle=”+a); } class Triangle extends Rectangle { void area() { float a=(w*h)/2; System.out.println(“Width=”+w+” and height=”+h+”\n Area of Triangle=”+a); } } class MethodOverride { public static void main(String args[]) { Rectangle obj; obj=new Rectangle(); //assigning the reference of super class type object. obj.getData(30,20); obj.area(); obj=new Triangle(); //assigning the reference of sub class type object. obj.getData(40,35); obj.area(); } } Interface:Interface is similar to a class except that is does not contain any implementation i.e. interface are 100% abstract. 1)[public static final]Datatype variable:value; 2)[public abstract] returntype method(args); i.e. members(variables & methods) of interface are by default public.The interface service(methods)can be over ride or use by any classes. How to declare interface:The keyword interface is used to declare any interface. Syntax:[Access Modifier] interface InterfaceName { [public static final] Datatype variable=value; [public abstract]returntype method(args); } Value of access modifier can be either public or default.If it is public then interface must be save separately using- InterfaceName.java If it is not public then we can define the implementer class at the same location. How to use the interface:The keyword implements is used to implement the interfaces i.e. one class can implements multiple interfaces if needed. Syntax:class ClassName(extends superClassName)implements InterfaceName { } The implementer class must have to over ride all methods of implementing interface because all methods are abstract. Similarly we can implements multiple interface using following syntaxclass ClassName extends SuperClassName implements InterfaceName1, InterfaceName2 { } Here the implementer class must have to over ride all methods of all implementing interfaces. Difference between abstract & interfaces:abstract classes interfaces 1)Abstract classes can contains with non- While interface can contain only abstract abstract as well as abstract method. methods. 2)Services of abstract class can be use While services of an interface can be use by Only by sub-classes(i.e. inherited from any class. sub class. 3)One class can be inherited from only one One class can implements multiple interface. abstract class because java support only single inheritance. 4)By default members of an abstract class By default members of interface are public. has default accessibility(package level accessibility). Step1:public interface AddDemo { int x=10,y=20; void Add(); } Step2:class InterfaceImpl implement AddDemo { public void Add() { int z=x+y; System.out.println(“Addition of”+x+” and “+y+”=”+z); } public static void main(String args[]) { InterfaceImpl in=new InterfaceImpl(); in.Add(); } } Using multiple interface public interface AddDemo { int x=10, y=20; void Add(); } public interface SubDemo { void sub(int a,int b) void sub(float a,float b); } class InterfaceImplMulti implements AddDemo,SubDemo { public void Add() { int z=x+y; System.out.println(“Addition of”+x+”and “+y+”=”+z); } public void sub(int x,int y) { System.out.println(“Substraction of”+x+”and “+y+”=”+z); public void suv(float x,float y) { float z=x+y; System.out.println(“Substraction of”+x+”and “+y+”=”+z); } public static void main(String args[]) { InterfaceImplMulti in=new InterfaceImplMulti(); in.Add(); in.sub(12,9); in.sub(6.6f,7.5f); } } } Using more than one interface(Relation between interface):One interface can extends another interface but one interface never implements another interface i.e. between two interfaces the relation of inheritance is possible.The existing is called super interface while the newly created interface is called subinterface. The implementer class need to implements only sub interface because super interface will be implicitly available. interface Interface1 { } interface Interface2 extends Interface1 { } Eg:interface MultiInterface { void multi(int a,int b) { interface DivInterface extends MultiInterface { void div(int a,int b) { class InterfaceInherit implements DivInterface { public void multi(int x,int y) { int y=x+y; System.out.println(“Multiplication of”+x+”and”+y+”=”+z); } public void div(int x,int y) { int z=x/y; System.out.println(“Division of”+x+”and”+y+”=”+z); } public static void main(String args[]) { InterfaceInherit i=new InterfaceInherit(); i.multi(20,17); i.div(564,4); } } } } } } Packages:Package are containers for classes & interfaces.Packaage keep the classes & interfaces unique from the classes & interfaces of other package. There are two types of package1)Pre-defined/built in packages 2)User-defined/custom packages 1)Pre-define packages Java define set of pre-define packages use for different purpose i.e. all classes for interface in java has been defined in some files.Commanly used packages in javai)java.lang:This package contains all the fundamental/basic classes in java likeSystem String StringBuffered Thread Exception WrapperClasses(Integer,float,….) Note:Java.lang packagae is by default available in everywhere.i.e. we can use any classes without import java.lang package.This is most widely used package in java. ii)java.io:This package provides set of classes required to perform input/output operation either using console or file or network. iii)java.util:This package provide collection herrer key to represent the group o objects as a elements as well as this package also provide date and calendar classes. iv)java.applet:This package provide the facility(classes & interfaces) to do the applet programming in java. v)java.awt:This package is responciable for creating any GUI application. vi)java.net:This package provide the facility to implement the networking between java appli cation. vii)java.sql:Using this package we can execute any sql statements(Insert,update,delete,create)using java applications. 2)User defined package:Since all pre-defined packages has specified meaning therefore java provide the facility.So,that user can create their own package as per requirement. Java provide keyword package using which we can create any packages or sub package.package & sub package name are defined using or used using dots. Steps to be followed:1)use package packagename; Main package This statement must be the first statement in java source code. 2)Create classes and interfaces and save them in package directory(i.e. create folders having name as a package name,inside that folder save the classes & interfaces.) Note:-In order to access classes & their methods as well as interface from other package,their accessibility must be public.Otherwise we cannot them from other package. 3)In order to create sub package use package packagename.packagename main package sub package save them into sub package directory(i.e. create folder inside main package folder.) How to use the classes & Interfaces of the package. Use the import statement to import the packages.i.e. we must have to import the main package & sub package individually. import mainpackage.*; import mainpackage.subpackage.*; root c:\abc mainpkg (main package) filename.java filename.java subpkg; filename.java filename.java Note:-Classpath environment variable must be set properly if code is not compile. Eg:-package mainpkg; Step1:public class TestSuper { public void demo() { System.out.println(“Hello from mainpackage class”); } } Step2:Package mainpkg.subpkg; public class TestSub { public void demo1() { System.out.println(“Hello from subpackage class”); } } Save as C:\javaprog\mainpkg\subpkg\TestSub.java Step3:Import mainpkg.*; Import mainpkg.subpkg.*; Class Testpkg { public static void main(String args[]) { TestSuper s1=new.TestSuper(); TestSub s2=new.TestSub(); s1.demo(); s2.demo1(); } } Save as c:\javaprog\Testpkg.java File Handling Java.io File:-An abstract representation of file and directory path names. i.e. in java both file & directory are represented using file class. Difference between files & directory Directory file 1)Directory can contain set of file as well as File contains only Data/information. Set of directories. 2)Directory does not contain any extension. File always contain some extension Like-.txt,.pmp,.java. Note:-In java either/or \\ is use as a path separator. C:\abc\xyz.txt allowed in windows. C:\\abc\\xyz.txt C:\abc\xyz.txtallowed in both java & linux,unix Constructor of file_class 1)File(String pathname) Creates a new File instance by converting the given pathname string into an abstract a 2)File(String parent,String child) Create a new File instance from a parent pathname string and a child pathname string. 3)File(File parent,String child) Creates a new File instance from a parent abstract pathname and a child pathname string. Eg1:-File f1=new File(“c:/abc/xyz.txt”); Eg2:-File f2=new File(“c:/abc”,”xyz.txt”); Eg3:-File f3=new File(new File(“c:/abc”),(“xyz.txt”); Methods:1)Boolean createNewFile() Automatically creates a new empty file and named by this abstract pathname if and if a file with this name does not get exist. 2)String getParent() Returns the pathname string of this abstract pathname’s parent,or null if this pathname does not name a parent directory. 3)String getName() Returns the name of the file or directory denoted by this abstract pathname. 4)String getAbsolutePath() Returns the absolute pathname string of this abstract pathname. 5)String getPath() Converts this abstract pathname into a pathname String. 6)String length() Returns the length of the file denoted by this abstract pathname. 7)Boolean canRead() Tests whether the application can read the file denoted by this abstract pathname. 8)Boolean cannWrite() Tests whether the application can modify the file denoted by this abstract pathname. 9)Boolean isHidden() Tests whether the file named by this abstract pathname is a hidden file. 10)Boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file. 11)Boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. 12)Boolean mkdir() Creates the directory named by this abstract pathname. 13)Boolean mkdirs() Creates the directory named by this abstract pathname including any necessary but non-existent parent directories. 14)String[] list() Returns an array of String naming the files and directories in the directory denoted by this abstract pathname. Eg:import java.io.*; class FileListDemo { public static void main(String arg[]) { File f=new File(“c:/mkjava”); String[] str=f.list(); for(int i=0;i<str.length;i++) { File f2=new File(f.str[i]); if(f2.isDirectory()) { System.out.println(f2.getName()+”is Directory”); } else if(f2.isFile()) { System.out.println(f2.getName()+”is File”); } } } } O/P:machine specific How to read and write the data:The File class provide the facility only to check File path,File permission as well as to create a blank file but if does not provide any facility how to read or write data using File. Therefore,Stream oriented classes are used.All stream classes has been defined in java.io.*; package Stream It is continuous flow of data from one source to another source.The source from where we read the data is called InputStream. Similarly another sources where we write the data is called OutputStream.The Stream oriented classes can be categories into two category. 1)byte-oriented 2)char-oriented byte-oriented char-Oriented InputStream (abstract class) Reader FileInputStream FileReader Etc BufferedReader InputStreamReader etc OutputStream FileOutputStream PrintStream Etc Writer FileWriter PrintWrite etc byte-oriented classes accept arguments as a single byte.byte array or byte sub-array in case of Reading. Similarly, it also take oriented data white Writing. InputStream and OutputStream are abstract super classes for,Reading or Writing byte oriented data. Similarly Reader & Writer are abstract super Classes for reading or writing(char oriented)data. FileInputStream:A FileInputStream obtains input bytes from a File in a file System.What files are available,depends on the host enviorment. FileInputStream is meant for reading streams of low bytes such as image data. Constructor:i)FileInputStream(File file) Creates a FileInputStream by opening a connection to an actual file,the file named by the File object file in the file system. ii)FileInputStream(String name) Creates a FileInputStream by opening a connection to an actual file,the named by the path name, name in the file system. Methods:i)int read() Read a byte of data from this input stream. ii)int read(byte[] b) Reads upto b.length bytes of data from this i/p stream into an array of bytes. iii)int read(byte []b,int off,int len) Reads upto len bytes of data from this i/p stream into an array of bytes. iv)long skip(long n) Skips over and discards n bytes of data from the i/p stream. v)int available() Returns the no. of bytes that can be read from this file i/p stream without blocking. vi)void close() Closes this file i/p stream and releases any system resources associated with the stream. Note:1)In case of Reading a file it must be in existence otherwise run time error(Exception)is thrown. FileNotFoundException All read() throws IOException therefore we must have to use either try-catch or throws statement to handle the exception. 2)read() method return -1 if EOF i.e. End Of File is reached means complete data is read. Eg:-FISDemo.java import java.io.*; public class FISDemo { public static void main(String args[]) { try { FileInputStream fis=new FileInputStream(“FISDemo.java”); int b=0; while((b=fis.read()))!=-1) //read byte one by one { System.out.println((char)b); //remove char and sec o/p } fis.cloose(); }catch(Exception e) { System.out.println(“Error in path”+e); } } } Class FileOutputStream:A file output stream is an output stream for writing data to a File or to a FileDescripitor.Whether or not a file is available or may be treated depends upon the underlying platform. FileOutputStream is meant fo writing stream of raw bytes such as image data. Constructor:1)FileInputStream(File file) Creates a file output stream to write to the file represented by the specified file object. 2)FileOutputStream(File file,boolean append) Creates a file output stream to write to the file represented by the specified File object. 3)FileOutputStream(String name) Creates an output file stream to write to the file with the specified name. Methods:1)void write(int b) Writes the specified byte the file output stream. 2)void write(byte [] b) Write b.length bytes from the specified byte array to this file output stream. 3)void write(byte[] b,int off,int len) Write len bytes from the specified byte array starting at offset off to this file output stream. 4)void close() Close this file output stream and releases any system resources associated with this stream. Eg:import java.io.*; class FOSDemo { public static void main(String args[]) { try{ BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); System.out.println(“Enter data to be written”); String str=br.readLine(); str=str+”\n”; FileOutputStream fos=new FileOutputStream(“c”\xyz.txt”,true); byte b[]=str.getBytes(); fos.write(b); fos.close(); System.out.println(“Data is written”); }catch(Exception io) { System.out.println(“error is”+io); } } } Class FileReader:-Convenience class for reading character files.FileReader is meant for reading Stream of character. Constructor :i)FileReader(String filename) Create a new FileReader,given the File to read from. ii)FileReader(String filename) Create a new fileReader,given the name of the file to read from. Methods:i)int read() Read a single character. ii)read(char[] cbuf) Read character into a portion of an array. iii)abstract int read(char[] cbuf,int off,int len) Read character into a portion of an array. iv)abstract void close() close the stream. Class FileWriter:Convenience class for character files. Whether or not a files is available or may be created depends upon the underlying platform. Constructor: FileWriter(File file) FileWriter(File file,boolean append) FileWriter(String filename) FileWriter(String filename,boolean append) Methods: Void write(char[] cbuf) Abstract void write(char[] cbuf,int off,int len) Void write(int c) Void writeString str) Void write(String str,int off,int len) Eg:import java.io.*; class FileWritDemo { public static void main(String arg[]) { try { BufferReader br=new BufferReader(new InputStreamReader(System.in)); System.out.println(“Enter data”); String str=br readLine(); str=str+”\n”; FileWrite fw=new FileWriter(“c:\\xyz.txt”,true); fw.write(str); }catch(Exception io) { System.out.println(“Error is”+io); } } } } Eg:-FileReaderDemo.java Import java.io.*; class FileReaderDemo { public static void main(String args[]) { FileReader fr=new FileReader(“c\\xyz.txt”); BufferedReader br=new BufferedReader(fr); String data=” “; While((data=br.readLine()!=null) { System.out.println(Data); } Fr.close(); }catch(Exception io) { System.out.println(“Error is”+io); } } } Class PrintWriter:Print formatted representation of objects to a text-output stream.This class implements all the print methods found in PrintStream.It does not conatin methods for writing raw bytes,for which a program should use non coded byte streams. Note:Methods in this class never throws I/O Exception. i)PrintWriter(OutputStrem out) Create a new PrintWriter,writer automatic line flushing. ii)PrintWriter(OutputStream out,boolean autoFlush) Create a new PrintWriter from an existing OutPutStream. iii)PrintWriter(Writer out) Create a new PrintWriter,without automatic line flushing. iv)PrintWriter(Write out,boolean autoFlush) Create a new PrintWriter. Methods:i)void print(boolean b) Print a boolean value. ii)void print(char c) Print a character. iii)void Println() Terminate the current line by writing the line separator string. iv)void println(char[] x) Print an array of character and then terminate the line. v)void close() close the stream. vi)vois flush() flush the stream. Eg:-PWDemo.java import java.io.*; class PWDemo { public static void main(String args[]) { PrintWriter pw=new PrintWriter(System.out,true); Pw.println(“Hello friends”); //pw.close(): //pw.flush(); } } Eg:-PWDemo1.java import java.io.*; class PWDemo1 { public static void main(String args[]) { try{ PrintWriter pw=new PrintWriter(new FileWriter(“xx.txt”,true)true); pw=println(“Hello friends”); //pw.close(); //pw.flush(); }catch(Exception e) { System.out.println(“Error is”+e); } } } Exception Handling In java there can be two types of error1)Compile time 2)Run time 1)Compile time:-This type of error generated by compiler due o syntactical promble.This type of error can be avoided by following proper syntax2)Run time:-Some times code gets compiled successfully but at run time program is executed & some errors are generated.These errors are called Exceptions. Java provide set of pre-define classes to describe different types of errors. All classes has been inherited from Exception classes.This class is defined in java.lang package. Java.lang.object Throwable Exception IOException Error RuntimeException FileNotFoundExcep OutOfMomoryError Assertion Error ArithmeticExp EOFExp VirtualMachineError StockOverFlowError NullPointerExp NumberFormatExp IndexOutOfBoundExp ArrayIndexOutOfBoundException Exception can be categorized into two categorized1)Checked Exception 2)Unchecked Exception Unchecked Exception Exception inherited from Run time are called Unchecked Exception.Unchecked Exceptions might arrives from the condition that represented bugs i.e. the situation that are too difficult for program to handle they are called unchecked exception because if they occurs we need not to do anything. Other than RuntimeException are called checked Exception i.e. checked exception are those exceptions that programmer expected to handle in the program.They always force to handle them otherwise program is terminated. Some situation of Exception ossurance:i)Trying to read a file which is not in existence-FileNotFoundException ii)Trying to read more data after reading complete data of the File-EndOfFileException iii)Trying to divide a no. by zero-ArithmeticException iv)Trying to use an object attributes or methods without constructing the objectNullPointerException v)Trying to typecast invalid number.(Eg:-Alphabet to number)-NumberFormatException vi)Trying to get or display an array elements beyond its limitArrayIndexOutOfBoundException There are two ways handling exception1)Implicit(automatic/default handling) 2)Explicit(manually) 1)Implicit:-Unchecked exception are implicitly or automatically handled by JRE(Java Runtime Environment) therefore JRE is called default handler of exception. JRE display string message to describe the detail of the exception i.e. cause line of occurance,program name etc. Eg:-DefaultHand.java class DefaultHand { public static void main(String args[]) { int x=10,y=0; System.out.println(“arr[s]=”+arr[s]); System.out.println(“x=”+x+”y=”+y); int z=x+y; System.out.println(“z=”+z); } } O/P:Exception in thread “main” java.lang.ArrayIndexOfBoundException:5 at DefaultHnd.main(DefaultHand.java:7) 2)Explicit Handling of Exception:Java provides five keywords namely1)try 2)catch 3)throw 4)throws 5)finally They can be use to handle the exception manually Use of try-catch:try { Code block to be monitor for exception }catch(Exception or subclass obj) { statements: } Where is possibility of occurring any exception that code block should be kept inside try block.If an exception is occurs,implicitly an object of exception class or one of its subclass type is created and thrown. The object thrown from try-block is compared with catch block.If matching is found then catch block(statements of catch block) gets executed.If no matching is found then control is transferred to JRE(default handler) and program is terminated.JRE display string message to give details about exception. Use of Multi try-catch:In same source code we can apply no. of try catch statement to separate one operation from another operation so that if operation1 is fail then remaining operation should be perform. Because if multiple operation are kept in single try block and if operation1 is failed then remaining all operation will also failed. Eg:-Multitrycatch.java class Multitrycatch { public static void main(String arg[]) { try{ int x=10,y=0; System.out.println(“x=”+x+”y=”+y); int z=x/y; }catch(ArithmeticException ae) { System.out.println(“Error in first operation is”+ae); } try{ int arr[]=new int[4]; System.out.println(“arr[4]=”+arr[4]); //change arr[4] to arr[3]then o/p is right) }catch(Exception e) { System.out.println(“Error in second operation is”+e); } System.out.println(“Hello”); //tp check control } } Use of Multicatch:Syntax:try{ { catch(subclass obj) { } catch(subclass obj) { } catch(Exception obj) { } Catch(Exception obj) { } while using multiple catch same try-block the only care must be taken that all subclasses has been before any super classes used. This is because if super class is used first then it can handle any exception of any subclass type and subclass exception part will be executed because it will never receive the control. Eg:MultiCatch.java)(last page) Use of finally:try { }catch(…….) { } Finally { } try{ }finally { } try-block can have either catch block or it can have finally block or it can have both. As we know that catch block is executed only if exception is thrown & matching is found. If no matching is found is found then control is transferred to JRE. Finally block is always executed it does not matter whether exception has been occurred or not.If exception is generated and catch block is not matching then finally block is always get executed before control is transferd to JRE. Actually finally is used to perform certain activity like cloriy database connection, cloriy file object………… Use of throw:Throw statement can be used either inside try block or catch to throw an exception explicitly throw statement can be based on certain condition it can be without also. Syntax:try{ throw new Exception() or Subclass(); }catch(Exception or subclass obj) { Statements; [throw obj] } Eg:class ThrowDemo { try{ if(n<0) { throw new Exception(); } else { int r=n*n; System.out.println(“Square of “+n+”=”+r); } }catch { System.out.println(“Error is handled in Method itself”+e); } } public static void main(String arg[]) { ThrowDemo td=new ThrowDemo(); td.square(10); td.square(5); } O/P:square of 10=100 Error is handled in Method itself java.lang.exception java.lang.Exception at ThrowDemo.sqaure(ThrowDemo.java:8) at ThrowDemo.main(ThrowDemo.java:36) Use of throw:Syntaz:Returntype method(args)throws Exception,…….. { throw new Exception(); } As we know that throw statement can be used only inside the method to throw an exception explicitly but in order to throw exception outside of method we must have to use throws statement. Throws statement always use along with method.It can be also use as an alternative for try-catch. Note:If any method signature has been defined using throws statement then method must be called from try-catch before or throws statement must be used otherwise compilation fail with an errorError:-“unreported exception exception name must be caught or declared to be thrown. Eg:class ThrowsDemo { void square(int n)throws Exception { if(n<0) { throw new Exception(); } else { int r=n*n; System.out.println(“Square of”+n+”=”+r); } } public static void main(String arg[]) { //try{ ThrowsDemo td=new ThrowDemo(); td.square(10); td.square(-5); /* }catch(Exception e) { System.out.println(“Error is handled in main method itself”+e); e.printStackTrace(); } */ } } User Defined Exception:Java provides the facility so that developer can create domain specific exception as per requirement. Using user defined exception more readable forms of exception can be created. We have to following stepsi)Create sub class of exception class or sub class of any exception sub class. ii)Overload some constructors at least a default constructor. iii)Override public String toString() { return “message to be return”; } This is pre-defined method defined in object class therefore it can be used in any classes because object class is the super class for all classes in java.Method accessibility mut be public. Note:Once we have created user defined exception it can be use very similar to pre-defined exception. Eg:-1) class LessBalEception extends Exception { int amt; LessBalanceExcpetion() { System.out.println(“Default constructor is called”); } LessBalanceExcpetion(int amt) { this.amt=amt; System.out.println(“Parameterised constructor is called:”+amt); } public String toString() { return “Your balance is not sufficient:”+amt; } } 2) import java.io.*; class Banking { int bal; void deposit(int amt) { bal+=amt; } void withdraw(int amt) throws LessBalanceException { If(bal-amt<500) { throw new LessBalanceException(amt); } else { bal-=amt; } } int getBalance() { return bal; } public static void main(String arg[]) { Banking b=new Banking(); try{ char ch=’y’; while(ch==’y’ || ch==’Y’) { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println(“1.Deposit \n 2.Withdrawl \n 3.Check Balance \n Enter your choice \n choice=”); int c=Interger.parseInt(br.readLine()); int amt=0; if(c<3) || if(c>1) { System.out.printl(“enter amount”); amt =Integer.parseInt(br.readLine()); } switch(c) { case1:b.deposit(amt); break; case2:b.withdrawl(amt); break; case3:int b1=b.getBalance(); System.out.println(“After transaction your balance=”+b1); break; default: System.out.println(“Invalid choice”); } System.out.println(“Do you wish to continue?Y/N”); ch=(char)br.read(); } }catch(Exception e) { System.out.println(“Error is”+e); } } Applet Programming awt(Abstract Window Toolkit) java.applet java.awt An Applet is small java program which is always dependent on webpage(HTML).It is interpreted through Web brower i.e. Applet runs under the control of WebBrowsers. Packages required for Applet-java.applet,java.awt. java.applet package provide pre-defined class namely Applet.Which can be use to create any user defined applet.We have to follow following steps to create an applet.(user define) Step1:import java.applet.*; import java.awt.*;(Abstract Window Toolkit) Step2:Create public Subclass of Applet class Step3:Override Life cycle method like 1)public void init() Called by the browser or applet viewer to inform this applet that it has been loaded into the system. 2)public void start() Called by the browser or applet viewer to inform this applet that it should start its exception. 3)public void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution. It is called again & again. 4)public void destroy() Called by the browser or applet viewer to inform this applet it is being reclaimed and that it should destroy any resources that it has allocated. Before destroying an applet stop() method is called implicitly to stop applet execution. Step4:In order to display anything(text, graphics, audio………)on applet screen override 1)public void paint(Graphics g) Paint this component It is method of awt.component class Eg:import java.applet.*; import java.awt.*; public class MyApplet extends Applet { public void init() { System.out.println(“Applet Initialized”); } public void start() { System.out.println(“Applet started”); } public void stop { System.out.println(“Applet stoped”); } public void destroy() { System.out.println(“Applet destroy”); } public void paint(Graphics g) { showStatus(“This is status bar”); System.out.println(“Applet painted”); g.drawString(“Hello friends this is my first Applet”,50,50); g.drawString(“This is another line”,150,80); } } How to compile & Run using Textpad:Ctrl+1to compile Ctrl+3to Run How to Run using HTML:Create separate .html file.This file must contain pre-defined tag namely. <applet……..> </applet> Attributes of <applet> tag 1)code=”className.class” 2)codebase=”path of .class file” //optional This attribute is used when .java file & .html file are saved separately(different drives).otherwise not required. 3)width=”value in pixel” 4)height=”value in pixel” Eg:<html> <body bgcolor=”Red”> <Applet code=”MyApplet.class” width=400 height=300> </Applet> </body> </html> 0 How to run using command prompt:We can also run the applet using command prompt open command prompt & go to the location where applet iis stored then we can use following commands. C:\abcjava>javac.filename.java i) C:\abcjava>appletviewer filename.html (if a separate .html file has been created must contain <applet> </applet>) Or ii) C:\abcjava>appletviewer filename.java (only when source code i.e. java file contains <applet> </applet> tag inside java comment) Add applet code in file Eg:import java.applet.*; import java.awt.*; /* <applet code=”MyApplet.class” width=400 height=300> </applet> */ MyApplet.java file as it is. Now run from command prompt using 2nd method. Some other Methods of Applet: Void resize(int width,int height) Request that this applet be resized. URL getCodeBase() Gets the base URL. URL getDocumentBase Gets the URL of the document in which this applet is embedded. abstract void fillRect(int x,int y,int width,int height) Draws the outline of an oval. abstract void fillOval(int x,int y,int width,int height) fills an oval bounded by the specified rectangle with the current color. abstract void drawPolygon(int [] xpoint,int [] tpoint,int n points) Draws a closed polygon defined by array of x & y coordinate. abstract void fillPolygon(int [] xpoint,int [] tpoint,int n points) Fills a closed polygon defined by arrays of x &y coordinates. abstract void drawArc(int x,int y,int width,int height,int startangle,int arcAngle.) Draws the outline of a circular or elliptical are covering the specified rectangle. The resulting are begins at start Angle and extends for arc Angle degrees,using the current color.Angle are interpreted such that 0 degrees is at the 3 o’clock position.A position value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation. The center of the arc is the center of the rectangle whose origin is(x,y) and whose size is specified by the width and height arguments. abstract void fillArc(int x,int y,int width,int height,int startangle,int arcAngle.) fills a circular or elliptical arc covering the specified rectangle. Eg:-GraphicsDemo.java import java.applet.*; import java.awt.*; public class GraphicsDemo extends Appler { public void paint(Graphics g) { g.drawLine(100,100,300,100); g.drawLine(300,100,300,300); g.drawLine(300,300,300,300); g.drawLine(100,300,100,100); g.fillRect(130,120,150,150); } } Eg:-DrawGraphicsDemo.java import java.applet.*; import java.awt.*; public class DrawGraphicsDemo { public void paint(Graphics g) { g.drawOval(120,120,200,200); g.fillOval(120,120,200,200); g.drawArc(220,220,400,400,0,90); g.drawOval(220,220,400,400,0,90); int x[]={100,250,400,400,100}; int y[]={250,100,250,400,400,100}; g.drawPolygon(x,y,5); g.fillPolygon(x,y,5); } } Eg:GraphicsDemo1.java import java.applet.*; import java.awt.*; public class GraphicsDemo1 extends Applet { public void paint(Graphics g) { int x[]={100,250,400,400,100}; int y[]={250,100,250,500,500}; g.drawPolygon(x,y,5); g.drawLine(100,250,400,250); g.drawRect(100,250,80,70); g.drawRect(320,250,80,70); g.drawLine(120,250,120,320); g.drawLine(160,250,160,320); g.drawLine(340,250,340,320); g.drawLine(200,400,100,100); g.drawRect(200,400,100,100); g.drawLine(250,100,250,100); } } How to display an Image:We have to follow two steps:Step1:-Take the reference of the image to be display using Image getImage(Url url) Image getImage(Url url,String name) This are methods of Applet class. Step2:-Once we get the reference image object we can display it using. void drawImage(Image img,int x,int y,ImageObserver obj) void drawImage(Image img,int x,int y,int w,int h,ImageObserver obj) This are methods of Graphics class in 1st version Image size will be default in 2nd version we can specify the display area using width or height. ImageObserver,this is pre-defined interface define in java.awt.image package this interface is implemented by Applet class.It is update interface which receive the notification about the image information when image is constructed. We can pass the keyboard ‘this’ as a reference of ImageObserver. Note:-copy image file into the current folder where the java file is store. Eg:-//display image import java.applet.*; import java.awt.*; public class ImgApplet extends Applet { Image img; public void init(); { img=getImage(getCodeBase(),”300H.Desk.jpg”); } public void paint(Graphics g) { g.drawImage(img,40,50,300,200,this); } } How to pass Parameter to an Applet:We can use pre-define tag namely <param> this is supporting tag of <Applet> tag it contain two attribute namely. Name:-Specify the parameter name. Value:-Specify the parameter value. Note:Name and value both will be in String format. Syntax:<applet code=”ClassName.class” width=”Num” height=”num”> <param name=”paramName” value=”ParamValue”> </applet> How to Read the Parameter:We can use the getParameter() of Applet class this method take parameter name as an argument while return the parameter value. Syntax:String getParameter(String name) Eg:Step1:import java.applet.*; import java.awt.*; public class AppletParam extends Applet { public void paints(Graphics g) { public void paints(Graphics g) { g.drawString(getParameter(“PI”),40,50); } } } Step2:<html> <body> <applet code=”AppletParam” width=”300” height=”300”> <param name=”PI” value=”Hello friends”> </applet> </body> </html> Note:Only compile the source code using java compiler but run using HTML file. Using Color Class:Color is predefined class define in java.awt package.The object of this class can be dealing with different color either as background or foreground. Color class provide colorName as predefine constant. 1)static Color black The Color black 2)static Color BLACK The color Black When we use following syntax:Color.colorName; Eg:-color.red; Then implicitly an object of color class type is created.We can also create color explicitly by using one of Constructor it can be. Constructor:1)Color(float r,float g,float h) Create an opaque SRGB color with specified red,green,blue,value in the range(0.0-1.0) 2)Color(int r,int g,int b) Create an apaque SRGB color with the specified red,green and blue value in the range(0-255) How to change Background & foreground color:Component class provide following method using which we can change the background and foreground color of any component. Component class is an abstract super class defined in java.awt.package. Methods: void setBackground(Color c) sets the background color of this component. void setForeground(color c) Sets the foreground color of this component. Color getBackground() Gets the background color of this component. Color getForeground() How to change Drawing color:Graphics is also pre-defined abstract class defined is java.awt package,this class provide following methods. Method:abstract void setColor(Color c) Sets this graphics contexts current color to the specified color. abstract color getColor() gets this graphics contexts current color. Eg:-AppletParam.java import java.applet.*; import java.awt.*; public class AppletParam extends Applet { Color c; public void init() { C=new Color((float)Math.random(),(float)Math.random,(float)Math.random()); } public void paint(Graphics g) { setBackground(Color.white); setForeground(Color.blue); g.fillOval(50,150,200,200); g.setColor(c); g.fillRect(300,150,200,100); g.setColor(Color.red); g.fillArc(300,350,200,100,0,180); } } Font class:This is pre-defined class defined in java.awt package the object of font class can be used to dealing with different font,size & font style. Constructor:- Font(String name,int style,int size) Creates a new Font from the specified name,style & point size. Methods:- String getFamily() Returns the family name of this Font. String getFontName() Returns the font face name of this font. int getSize() Returns the point size of this font,rounded to an integer. String getName() Returns the logical name of this font. int getStyle() Returns the style of this Font .It return 0(zero) if font style is plain.1 if Bold.2 if italic.3 if bold & italic Field:static int BOLD The bold style constant. static int ITALIC The italicized style constant. Static int PLAIN The plain style constant. How to change Font:We can use methods of component class as well as Graphics class to get or set Font. Font getFont() Gets the font of this component. void setFont(Font f) Sets the font of this component. Eg:import java.awt.*; import java.applet.*; public class FontDemo extends Applet { Font f; public void init() { f=new Font(“Verdana”,Font.BOLD+Font.ITALIC,20); } public void paint(Graphics g) { g.drawString(“This is demo of default font”,20,20); Font f1=g.getFont(); g.drawString(“Font family=”+f1.getFamily(),20,40); g.drawString(“Font name=”+f1.getFontName(),20,60); g.drawString(“Fomt style=’f1.getStyle(),20,80); g.drawString(“Font size=”+f1.getSize(),20,100); g.setFont(f); g.drawString(“This is demo of custom font”,20,120); Font f2=g.getFont(); g.drawString(“Font family=”+f2.getFamily(),20,40); g.drawString(“Font name=”+f2.getFontName(),20,60); g.drawString(“Fomt style=”f2.getStyle(),20,80); g.drawString(“Font size=”+f2.getSize(),20,100); } } Creating GUI Application:-Java.awt package set of pre-define classes using which we can create any GUI application in java.GUI application contain GUI components like,lable,Textfield,CheckBox………etc GUI application can be used to take some input from the user and display some output to the user. Class Hierarchy:Java.lang.objcet java.awt.component Lable TextField Button CheckBox TextField List Choice TextArea Panel Applet Frame Container Window Dialogue FileDialogue Component Class:- It is an abstract super class for GUI components like Label,TextFireld,TextArea…….using which any GUI application can be created. Since,it is an abstract class therefore we cannot create object of this class can be used by any sub classes.Most commonly used methods areMethods: void setBounds(int x,int y,int width,int height) Moves and Resized the component. void setVisible(boolean b) Shows or hides the component depending on the value of parameter b. void setSize(int width,int height) Resize that the component that it has width width and height height. void setLocation(int length,int height) Moves this component into new location. Container Class:Container are also component which may contain other component including other container also.Container can be mainly of two type1)Toplevel container 2)Sub container 1)Toplevel Container:Using toplevel container only,any GUI application can be created.Frame & Applet are used as toplevel container .Toplevel container can contain also contain other component as well as container also. 2)Sub Container:Panel class is used as sub container i.e. we can add the GUI component to panel then finally the panel can be added to Frame and Applet. Frame class:It is used as a toplevel container which may contain any GUI component including sub container also. Frame() It is used as a toplevel container which may contain any GUI component including sub container also. Frame(String title,Graphicsconfiguration gc) Constructs a new initially invisible Frame object with specified title a GraphicsConfiguration. Methods: void setTitle(String title) Sets the title for this frame to the specified String. void Resizable(boolean resizable) Sets whether this frame is resizable by the user. void setMenuBar(MenuBar mb) Sets the menu bar for this frame to the specified menubar. void setIconImage(Image image) Sets the image to be displayed in the minimized icon for the frame. void setExtendedState(int state) States the state of this frame.The state represented as bitwise mark. i)Normal Indicates that no state bits are set. ii)ICONIFIED iii)MAXIMIZED-HORIZ iv)MAXIMIZED-VERT v)MAXIMIZED-BOTH Concatinates MAXIMIZED-HORIZ and MAXIMIZED-VERT. Steps to be followed to create GUI applicationFrame(7 steps) 1)import java.awt.*; Applet(5 steps) ---- import java.awt.*; import java.applet.*; 2)Create public subclass to Frame class. class. ---- Create public subclass to Applet 3)Declared all GUI component like label ---- Declared all GUI component like TextField……..using which application application is Label,TextFile……using which is to be created(optional). To be created(optional). 4)Use constructor of our own inside ---- Use public voi init() to construct all the Construct body construct all the declared the declared comaddponent by using Component by using there construction. Constructor. 5)After construction of the component add After construction of the component Add them to the container using – them to the container comp) i)Component add(Component comp) comp) ii)void add(component comp,object constraints) 6)Since Frame is initially invisible as well As its size and location is also default therefore We can used following methods. i)setTitle(“Title”); ii)setBound(int x,int y,int width,int height) iii)setVisible(true) 7)Use public static void main(String a[]) to create an object of our class. Eg:-//creating blank Frame:import java.awt.*; public class MyFrame extends Frame { MyFrame() i)component add(Component ii)void add(component comp,object constraints) { setTitle(“Frame Demo”); // sets specified title setBound(150,100,400,300); setVisible(true); setExtendsState(Frame.MAXIMIZED.BOTH); } public static void main(String arg[]) { new MyFrame(); } } Label Class:A Label object is a component for placing text in a container.A Label display a single line of read-only text.The text can be change by the application but user cannot edit it directly. Constructor:i)Label() Constructs a empty Label. ii)Label(String text) Constructor an new label with specified string of text,left justified. iii)Label(String text,int alignment) Constructs a new label that present the specified string of text with the specified alignment. Alignment areLabel.LEFT ,Label.RIGHT ,Label.CENTER Methods:- 1)String getText() Get the text of this Label. 2)void setText(String text) Set the text for this Label to the specified text. Class TextField:A TextField object is text component that for the editing of a line of text. Constructor:1)TextField() Constructs a new TextField. 2)TextField(int Columns) Constructs a new empty text field with specified number of columns. 3)TextField(String text) Constructs a new text field initialized with specified text. 4)TextField(String text,int Columns) Constructs a new text field initialized with specified text to be display, and wide enough to hold the specified number of columns. Methods:1)void setText(String t) sets the text that is presented by this text component to be the specified text. 2)public String getText() Return the text this is presented by this component.By default,this is an empty String. Class TextArea:A TextArea object is a multi-line region that display text.It can be set to editing or to be read-only. Constructor:1)TextArea() Constructs a new text area with the empty string as text. 2)TextArea(int rows,int columns) Constructs a new text area with the specified number of rows & columns and the empty string as a text. 3)TextArea(String text) Constructs a new text area with the specified text. 4)TextArea(String text,int rows,int columns) Constructs a new text area with the specified text and with the specified number of rows & columns. Methods:1)void append(String str) Appends the given text to the text area correct text. 2)getText Public String getText() Returns the text that is presented by this text component. 3)setText Public void setText(String t) Sets the text this is presented by this text component to be the specified text. Class Button:The Button is create a Label button.The application can cause some action when button is push. Constructor:1)Button() Constructs a button with an empty String for its Label. 2)Button(String Label) Constructs a button with the specified Label. Methods:1)void addActionListener(ActionListener 1) Adds the specified action listener to receive action events from this button. 2)String getLabel() Gets the label of this button. 3)void setLabel(String label) Sets the button Label to the to be specified String. Eg:-//using Applet import java.awt.*; import java.apple.*; public class LabelTextApplet extends Applet { Label l1,l2; TextField t1,t2; public void init() { //Declaration of component l1=new Label(“Num”); l2=new Label(“Square”); t1=new TextField(30); t2=new TextField(30); //adding component to container add(l1); add(t1); add(l2); add(t2); } } Eg:- //using Frame import java.awt.*; public class LabelTextFrame extends Frame { //declaration of component Label l1,l2; TextField t1,t2; LabelTextFrame(); { //construction of declared component l1=new Label(“Num”); l2=new Label(“Square”); t1=new TextField(30); t2=new TextField(30); //adding component to container by //set Layout(new FlowLayout()); add(l1); add(t1); add(l2); add(t2); SetTitle(“Label Text Frame”); SetBound(100,100,400,400); SetVisible(true); } public static void main(String arg[]) { new LabelTextFrame(); } } LayOutManager class:Java.awt package provide set of pre-defined classes called lay-out manager classes.They are use to control the visibility status of awt component within container. Commonly used lay-out manager classes are1)FlowLayout 2)BorderLayout 3)GridLayout 4)GridBagLayout 5)CardLayout 1)FlowLayout:A FlowLayout arranges components in a directional flow,much like lines of text in a paragraph. Constructor: FlowLayout() Constructs a new FlowLayout with a centered alignment & a default 5-unit horizontal and vertical gap. FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align,int hgap,int vgap) Creates a new FlowLayout manager with thw indicated alignment and the indicated horizontal & vertical gap. FlowLayout Note:-FlowLayout is byd default available in Applet & Panel. 2)BorderLayout:A border layout lays out a container,arranging & resizing its components to fit in five regions: north,south,west,east and center.Each region may contain no more than one component and is identified by a corresponding constant: NORTH,SOUTH,EAST,WEST & CENTER. Constructor: BorderLayout() Constructs a new BorderLayout with no gaps between components. BorderLayout(int hgap,int vgap) Constructs a BorderLayout with the specified gaps between component. BorderLayout North West CENTER East South Note:-It is by default available in Frame,Window & Dialogue. 3)GridLayout:-The GridLayout class is a Layout manager that lays out a container’s components in a rectangular grid.The container is divided into equal-sized rectangular ,and one component is placed in each rectangle. Constructor:GridLayout() The GridLayout with a default of one column per component in a single row. GridLayout(int rows,int cols) Creates a grid layout with the specified number of rows and columns. GridLayout(int rows,int cols,int hgap,int vgap() Creates a grid layout with the specified number of rows and columns. cols GridLayout(2x2) rows Note:-In order to change the layout setting we have to use void SetLayout(LayoutManager mgr) method. Eg:setLayout(new FlowLayout()); or setLayout(new BorderLayout()); or setLayout(new GridLayout(2,3)); Panel Class:Panel is the simplest container class.A panel provides space in which an application can attach any after component,including other panels. The default Layout Manager for a panel is the FlowLayout Layout Manager. Constructor: Panel() Creates a new panel using the default layout manager. Panel(LayoutManager layout) Creates a new panel with the specified layout manager. How to arrange Components in Container in proper order? There are two waysi)Using setBounds(int x,int y,int w,int h)-method of Component class. ii)Using LayoutManager classes x panel class. i)Using detBounds():This is pre-defined method defined in component class,which is Super class for all awt Component like,Label, TextField,Button…………etc. Before using setBounds() method we must have to cancel setting of default layout manager usingsetLayout(null); Then we can use the setBounds() method for each and every Component. Eg:import java.awt.*; public class LabelTextDemo1 extends Frame { //declaration of Components Label lb1,lb2; TextField tf1,tf2; LabelTextDemo1() //public void init()-For Applet { //Construction of Declared Components lb1=new Label(“Num”); lb2=new Label(“Square”); tf1=new TextField(30); tf2=new TextField(30); //adding Component to Container setLayout(null); lb1.setBounds(50,50,80,20); lb2.setBounds(50,90,80,20); tf1.setBounds(150,50,80,20); tf2.setBounds(150,90,80,20); add(lb1); add(lb2); add(tf1); add(tf2); setLocation(200,200); //specify the location //setResizable(false); //Restrict maximization setTitle(“LableTextDemo”); //set specified title steSize(400,400); //set with height } public static void main(String arg[]) { New LabelTextDemo1(); } } Using Panel:- Num p1 Square p2 Main Panel Eg:import java.awt.*; public class LabelTextPanel extends Frame { Label lbl,lb2; TextField tf1,tf2; Panel p1,p2,mainPanel; LabelTextPanel() { lb1=new Label(“Num”); lb2=new Label(“Square”); tf1=new Label(30); tf2=new Label(30); p1=new Panel(); p2=new Panel(); mainPanel=new Panel(new GridLayout(2,1)); p1.add(lb1); p1.add(tf1); p2.add(lb2); p2.add(tf2); mainPanel.add(p1); mainPanel.add(p2); add(mainPanel); setResizable(false); setTitle(“LabelTextPanel”); setBounds(100,100,400,200); setVizible(true); } public static void main(String args[]) { new LabelTextPanel(); } } Using Frame:Eg:import java.awt.*; public class LabelTextFrame extends Frame { Label l1,l2,l3; TextField t1,t2,t3; Button b1,b2,b3,b4; Panel p1,p2,p3,p4,mp; LabelTextFrame() { l1=new Label(“Num1”); l2=new Label(“Num2”); l3=new Label(“Result”); t1=new TextField(30); t2=new TextField(30); t3=new TextField(30); b1=new Button(“+”); b2=new Button(“-”); b3=new Button(“*”); b4=new Button(“/”); p1=new Panel(); p2=new Panel(); p3=new Panel(); p4=new Panel(); mp=new Panel(new GridLayout(4,1)); p1.add(l1); p1.add(t1); p2.add(l2); p2.add(t2); p3.add(l3); p3.add(t3); p4.add(b1); p4.add(b2); p4.add(b3); p4.add(b4); mp.add(p1); mp.add(p2); mp.add(p3); mp.add(p4); add(mp); setBounds(100,100,400,400); setVisible(true); setResizable(true); setTitle(“LabelTextFrame”); } public static void main(String arg[]) { new LabelTextFrame(); } } } Eg:-Using Applet import java.applet.*; import java.awt.*; public class LabelTextApplet extends Applet { Label l1,l2,l3; TextField t1,t2,t3; Button b1,b2,b3,b4; Panel p1,p2,p3,,p4,mp; public void init() { l1=new Label(“Num1”); l2=new Label(“Num2”); l3=new Label(“Result”); t1=new TextField(30); t2=new TextField(30); t3=new TextField(30); b1=new Button(“+”); b2=new Button(“-”); b3=new Button(“*”); b4=new Button(“/”); p1=new Panel(); p2=new Panel(); p3=new Panel(); p4=new Panel(); mp=new Panel(new GridLayout(4,1)); p1=add(l1); p1=add(t1); p2=add(l2); p2=add(t2); p3=add(l3); p3=add(t3); p4=add(b1); p4=add(b2); p4=add(b3); p4=add(b4); mp=add(p1); mp=add(p2); mp=add(p3); mp=add(p4); add(mp); }} Class Checkbox:A checkbox is a graphical component that can be in either an “on” (true) or “off”(false) state.Clickig on a checkbox changes its state from “on” to “off” or from “off’ to “on”. Constructor: CheckBox() Creates a check box with on empty String for its label. Checkbox(String Label) Label Create a chech box with the specified label. Checkbox(String label,boolean State) Label Creates a check box with the specified label and sets the specified state. Checkbox(String Label,boolean State,CheckboxGroup group) o Label Constructs a Checkbox with the specified label,set to the specified state, and in the specified check box group. Methods:void addItemListener(ItemListener l) Adds the specified item listener to receive item events from this checkbox. String getLabel() Gets the label of this checkbox. void steLabel(String Label) Sets this check box’s label to the String argument. boolean getState() Determines whether this check box is in the “on” or “off” state. void setState(boolean state) Sets the state of this checkbox to the specified state. Eg:P1 P2 P3 Operating Systems Win98 Win2000 WinXP Vista Your Favorite Operating System is Color P4 P5 oRed oGreen oBlue oYellow Yours Favorite Color is:- Eg:-using Applet import java.Applet.*; import java.awt.*; public class checkBoxDemo extends Applet { CheckBox c1,c2,c3,c4,r,g,b,y; TextField t1,t2; Label l1,l2,l3,l4; Panel p1,p2,p3,p4,p5,mp; public void init() { l1=new Label(“Operating Systems”); l2=new Label(“Your Favorite Operating Sytems is”); l3=new Label(“Color”); l4=new Label(“Your Favorite Color is”); t1=new TextField(300); t2=new TextField(100); c1=new CheckBox(“Win98”); c2=new CheckBox(“Win2000”); c3=new CheckBox(“WinXP”); c4=new CheckBox(“Vista”); CheckboxGroup cg=new CheckboxGroup(); r=new Checkbox(“Red”,false,cg); g=new Checkbox(“Green”,false,cg): b=new Checkbox(“Blue”,false,cg): y=new Checkbox(“Yellow”,false,cg): p1=new Panel(); p2=new Panel(); p3=new Panel(new GridLayout(3,1)); p4=new Panel(); p5=new Panel(new GridLayout(2,1)); mp=new Panel( new GridLayout(5,1)); p1.add(l1); p1.add(c1); p2.add(c2); p2.add(c4); p3.add(t2); p3.add(t7); p3.add(l3); p4.add(r); p4.add(g); p4.add(b); p4.add(y); p5.add(l4); p5.add(t2); mp.add(p1); mp.add(p2); mp.add(p3); mp.add(p4); mp.add(p5); add(mp); setBounds(100,100,400,400); setTitle(“CheckboxFrame”); setVisible(true); setResizable(true); } public static void main(String a[]) { new CheckboxFrame(); } } Class List:The List component presents the user with a scrolling list of text items.The list can be set up so that the user can choose one item or multiple items. Constructor: List() Creates a new scrolling list. List(int rows) Creates a new scrolling list initialized with the specified no. of visible lines. List(int rows,int boolean MultipleMode) Creates anew scrolling list initialized to display the specified no. of rows. Methods:void addItemListener(ItemListener l) Adds the specified item listener to receive item events from this list. void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this list. void addd(String item) Adds the specified item to the end of scrolling list. String getItem(int index) Gets the item associated with the specified index. int getItemCount() Gets the no. of items in the list. int getSelectedIndex() Gets the index of the selected item on the list. int [] getSelectedIndexes() Gets the selected indexes on the list. String getSelectedItem() Gets the selected item on the scrolling list. String []getSelectedItem() Gets the selected items on this scrolling list. void select(int index) Selects the item at the specified index in the scrolling list. Class Choice:The choice class presents a pop-up menu of choices.The current choice is displayed as the title of the menu. Constructor: Choice() Creates a new Choice menu. Methods: add() addItem(String item) addItemListener(ItemListerner l) String getItem(int index) int getItemCount() int getSelectedIndex() String getSelectedItem() Eg:ch=new choice(); ch.add(“CPU”); lst=new Lsit(); lst.add(“4000”); Method categories and Interfaces:Category Interface Name Methods Action ActionListerner actionPerformed(ActionEvnet) Item ItemListener itemStateChanged(ItemEvent) Mouse MouseMotionListener mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mouseClicked(MouseEvent) MouseMotion MouseMotionListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) Key KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) Focus FocusListener focusGained(FocusEvent) focusLost(FocusEvent) Adjustment AdjustmentListener adjustmentValueChanged (AdjustmentEvent) Component ComponentListener componentMoved(ComponentEvent) componentHidden(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) Windows WindowsListener windowsClosing(WindowsEvent) windowsOpened(WindowsEvent) windowsIconified(WindowsEvent) windowsDeiconifeied(WindowsEvent) windowsClosed(WindowsEvent) windowsActivated(WindowsEvent) windowsDeactiveted(WindowsEvent) Container ContainerListener componentAdded(ContainerEvent) componentRemoved(ContainerEvent) Text TextListener WindowState WindowStateListener windowStateChanged(WindowEvent e) textValueChanged(TextEvent) WindowFocus WindowFocusListener windowGainedFocus(WindowsEvent e) windowLostFocus(WindowsEvent e) MouseWheel MouseWheelListener mouseWheelMoved(MouseWheelEvent e) Input methods InputMethodListener createPositionChanged (InputMethodEvent e) Hierarchy e) HierarchyBoundsListener hierarchyChange(HierarchyEvent Hierarchy e) HierarchyBoundsListener ancestorMoved(HierarchyEvent ancestorResized(HierarchyEvent e) AWT AWTEventListener eventDispatched(AWTEvent e) Event Handing 1)Event:If user interact with any GUI application in any way either by clicking button,mouse or by clicking any key some events gets generated. Java.awt.event.*; package set of predefined classes called Event classes.All event classes has been inherired from java.util.EventObject class. EventObject ActionEvent KeyEvent ItemEvent 2)EventSource:- MouseEvent FocusEvent WindowEvent EventSource is also Object in java.Which generates the event.The EventSource can be awt component using which GUI application can be created like Button,TextField,Checkbox………..etc. EventListener interfaces:Java.awt.event package provides set of pre-defined interfaces called EventListener interfaces.Each interface define method or set of methods that need to be override in order to handle the event. Commanly used Listener Interfaces areNote:1)The classes which implements Listener Interfaces are called EventListener because when any Events is generated from any EventSource a notification is send to the class which implement Listener interface. 2)The EventSource must be registerd with specific Listener interface using <Syntax>:-ObjOfEventSource.addxxxxListener(this or ObjectOfListener Class) Where xxx value can be Action,Item,Window,Mouse,Key,Focus……………etc. Eg:-b1.addListener(this); Indicates currect class is ListenerClass.If it is separate class then object of that should be passed usingb1.add(ActionListener(new ClassName()); ch1.addItem listener(this); step1import java.aawt.event.*; step2:implements required Listener Interface.One Class can implements multiple interface if needed. Step3:Registered the EventSource using ObjOfEventSource.addxxxListener(); Step4:Since methods of an interface are 100%(completely) abstract So we must have to override all methods of all implementing Listener interface otherwise compilation fail with error:“ClassName is not abstract and doesnot override methodName(arg). Note:Since EventObject is super class of all events.This class provide pre-defined methods. (package)Java.util package (class) EventObject Method: Object getSource() The object on which the Event initially occurred. It can be used with any Event. Eg:import java.awt.*; import java.awt.event.*; public class LabelTextEvent extends Frame implements FocusListener { //declaration of Components Label l1,l2; TextField t1,t2; LabelTextEvent() { //Construction of declared components l1=new Label(“Num”); l2=new Label(“Square”); t1=new TextField(30); t2=new TextField(30); //adding Listener to EventSource t1.addFouceListener(this); //3 //adding components to container setLayout(null); l1.setBounds(50,50,80,20); l2.setBounds(50,90,80,20); t1.setBounds(150,50,80,20); t2.setBounds(150,90,80,20); add(l1); add(l2); add(t1): add(t2); setLocation(200,200); //set Location where frame will be displayed setTitle(“LabelTextDemo”); setSize(400,400); //set width height setVisible(true); addWindowsListener(this); } public void windowClosing(WindowEvent we) { System.exit(0); } public void windowClosed(WindowEvent we) { } public void windowClosed(WindowEvent we) { } public void windowOpened(WindowEvent we) { } public void windowActivated(WindowEvent we) { } public void windowDeactived(WindowEvent we) { } public void windowIconified(WindowEvent we) { } public void windowDeiconified(WindowEvent we) { } public void focusGained(FocusEvent fe) //4 { } public void focusLost(FocusEvent fe) { int x=Interger.parseInt(t1.getText()); int y=x*x; t2.setText(“ “ +y); } public static void main(String args[]) { New LabelTextEvent(); } } Eg:import java.applet.*; import java.awt.*; import java.awt.event.*; public class LabelTextEvent1 extends Applet implements ActionListener { Label l1,l2,l3; TextField t1,t2,t3; Button b1,b2,b3,b4; Panel p1,p2,p3,p4,mp; public void init() { l1=new Label(“Num1”); l2=new Label(“Num2”); l3=new Label(“Result”); t1=new TextField(30); t2=new TextField(30); t3=new TextField(30); b1=new Button(“+”); b2=new Button(“-“); b3=new Button(“*”); b4=new Button(“/”); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); p1=new Panel(); p2=new Panel(); p3=new Panel(); p4=new Panel(); mp=new Panel(new GridLayout(4,1)); p1.add(l1); p1.add(t1); p2.add(t2); p2.add(t2); p3.add(l3); p3.add(t3); p4.add(b1); p4.add(b2); p4.add(b3); p4.add(b4); mp.add(p1); mp.add(p2); mp.add(p3); mp.add(p4); add(mp); } public void actionPerformed(ActionEvent ae) { try{ int a=Integer.parseInt(t1.getText()); int b=Interger.parseInt(t2.getText()); if(ae.getSource()==b1) { int c=a+b; t3..setText(“ “+c); } if(ae.getSource()==b2) { int c=a-b; t3.setText(“ “+c); } if(ae.getSource()==b3) { int c=a*b; t3.setText(“ “+c); } if(ae.getSource()==b4) { int c=(float)a/b; t3.setText(“ “+c); }catch(Exception e){ } } } Component SupportedListener Button ActionListener MenuItem ActionListener Checkbox List ItemListener Choice ActionListener(only for List) TextField FocusListener, KeyListener Eg:import java.awt.event.*; import java.awt.*; import java.applet.*; public class CheckboxDemo extends Applet implements ItemListener { Checkbox c1,c2,c3,c4,r,g,b,y; TextField t1,t2; Label l1,l2,l3,l4; Panel p1,p2,p3,p4,mp; public void init() { l1=new Label(“Operating System”); l2=new Label(“Favourite Operating System”); l3=new Label(“Color”);; l4=new Label(“Favourite color”); t1=new Label(30); t2=new TextField(30); c1=new Checkbox(“Win98”); c2=new Checkbox(“Win2000”); c3=new Checkbox(“WinXP”); c4=new Checkbox(“Vista”); CheckboxGroup eg=new CheckboxGroup(); r=new Checkbox(“Redd”,false.cg); g=new Checkbox(“Green”,false.cg); b=new Checkbox(“Blue”,false.cg); y=new Checkbox(“Yellow”,false.cg); p1=new Panel(); p2=new Panel(); p3=new Panel(new GridLayout(3,1)); p4=new Panel(); p5=new Panel(new GridLayout(2,1)); mp=new Panel(new GridLayout(5,1)); p1.add(l1); p2.add(c1); p2.add(c2); p2.add(c3); p2.add(c4); p3.add(l2); p3.add(t1); p3.add(t3); p4.add(r); p4.add(g); p4.add(b); p4.add(y); p5.add(l4); p5.add(t2); mp.add(p1); mp.add(p2); mp.add(p3); mp.add(p4); mp.add(p5); add(mp); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); c4.addItemListener(this); r.addItemListener(this); g.addItemListener(this); b.addItemListener(this); y.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { t1.setText(“ “); if(c1.getState()) { t1.setText(t1.getText() +” “ +c1.getLabel()); } if(c2.getState()) { t1.setText(t1.getText() +” “ c2.getLabel()); } if(c3.getState()) { t1.setText(t1.getText() +” “ c3.getLabel()); } if(c4.getState()) { t1.setText(t1.getText() +” “ c4.getLabel()); } if(r.getState()) { t2.setText(r.getLabel()); t2.setBackground(Color.red); } if(g.getState()) { t2.setText(g.getLabel()); t2.setBackground(Color.green); } if(b.getState()) { t2.setText(b.getLabel()); t2.setBackground(Color.blue); } if(y.getState()) { t2.setText(y.getLabel()); t2.setBackground(Color.yellow); } } } O/P:- Operating System Win98 Win2000 WinXP Vista Favourite Opeating System Color oRed oGreen oBlue Favourite Color Eg:Product Name Quantity Price oYellow Total Calculate import java.awt.*; import java.awt.event.*; public class ChoiceItemDemo extends Frame implements ItemListener ActionListener { Label l1,l2,l3,l4; TextField t1,t2; List l; Choice ch; Panel p1,p2,mp; ChoiceItemDemo() { l1=new Label(“Product Name”); l2=new Label(“Quantity”); l3=new Label(“Total”); l4=new Label(“Price”); t1=new Textfield(30); t2=new TextField(30); b1=new Button(“Calculate”); ch=new Choice(); ch.add(“CPU”); ch.add(“Mouse”); ch.add(“RAM”); ch.add(“HardDisk”); ch.add(“Moniter”); l=new List(); l.add(“3000”); l.add(“200”); l.add(“1500”); l.add(“3500”); l.add(“4500”); p1=new Panel(new GridLayout(7,1)); p1.add(l1); p1.add(ch); p1.add(l2); p1.add(t1); p1.add(l3); p1.add(t2); p1.add(b1); p2=new Panel(new GridLayout(2,1)); p2.add(l4); p2.add(l); mp=new Panel(); mp.add(p1); mp.add(p2); add(mp); ch.addItemLisstener(this); b1.addActionListener(this); setTitle(“Choice Demo”); setSize(400,400); setVisible(true); setExtendedState(frame.MAXIMISED_BOTH); } public void itemStateChanged(ItemmEvent ie) { int p=Interger.parseInt(l.getSelectedItem()); int q=Integer.parseInt(t1.getText()); int t=p*q; t2.setText(“ “+t); t2=setEditable(false); } public static void main(String arg[]) { New ChoiceItemDemo(); } } Creating Menu Java.awt package provide set of pre-define classes1)MenuBar 2)Menu 3)MenuItem Using this classes we can implement menu system in awt application.Menu can be added only to Frame not to any Applet. 1)MenuBar:The MenuBar class encapsulates the platform concept of a menu bar bound to a frame.In order to accociate with the menu bar with a frame object,call the frame setMenuBar() method. Constructor:- 1)MenuBar() add(File); Create a new munubar. Methods:1)Menu add(Menu m); Add the specified menu to the menubar. 2)Menu:A menu object is a pull down menu component that is depended from a menubar. Constructor:1)Menu() Constructs a new menu with sn empty label. 2)Menu(String label) Constructs a new menu with the specified label. Methods :1)MenuItem add(MenuItem mi) Add the specified menu item to this menu. 2)void addSeperator() Add a sepetator line,or a hypen to the menu at the current position. 3)MenuItem All item in a menu must belong to a class MenuItem or one of its subclass. Constructor:1)MenuItem() Constructs a new MenuItem with an empty label and an keyboard shortcut. 2)MenuItem(String label) Constructs a new MenuItem with the specified label and or keyboard shortcut. 3)MenuItem(String label,MenuShortcut s) Create a menu item with associated keyboard shortcut. Methods:1)void addActionListener(ActionListener l) Add the specified ActionListener to receive action event from this menu item. Title File - Edit New ctrl+N Open ctrl+O Save ctrl+S Exit Alt+f4 Steps to be followed:1)Create an object of MenuBar class and attach it to the frame using following method of Frame classvoid setMenuBar(MenuBar mb) Set the MenuBar for the frame to be specified menubar. Eg:mb=new MenuBar(); setMenuBar(); 2)Create some object of Menu class and other than to be menu bar using add() method of MenuBar class. Eg:fmenu=new Menu(“File”); emenu=new Menu(“Edit”); mb.add(fmenu); mb.add(emenu); 3)Create some object of MenuItem class then attach them to a specific menu using add() method of menu class. Eg:nitem=new MenuItem(“New”); fmenu.add(nitem); 4)Add the ActionListener to all MenuItem and override public ActionPerformed(ActionEvent ae) method. The FileDialog Class The FileDialog class display a dialog window from which the user can select a file. Since, it is a model dialog,when the application calls its show method to display the dialog,it block resr of the application until the user has choosen file. Field:1)static int LOAD This constant value indicates that the purpose of the file dialog window is to locate a file from which to read. 2)static int SAVE This constant value indicates that the purpose of the static file dialog window is to locate to whixh to write. Constructor:1)FileDialog(Frame parent) Creates a file dialog for loading a file. 2)FileDialog(Frame parent,String title) Creates a file dialog window with the specified title for loading a file. Methods:1)String getFile() Gets the selected file of this file dialog. 2)String getdirectory() Gets the directory of this file dialog. 3)void setMode(int modds) Sets the mode of the file dialog. 4)void setTitle(String title) Set the title of the dialog. 5)void setVisible(boolean b) Show or hide this component depending on the value of parameter b. How to use FileDialog:Steps:1)Create an object of FileDialog class fd=new FileDialog(this); 2)In order to setTitle and mode use the following methods. fd.setTitle(“Open’); fd.setMode(fd.LOAD); or fd.setMode(FileDialog.LOAD); Since,LOAD is a static member and we are calling it in another class hence,className.LOAD(FileDialog.LOAD) 3)In order to make visible dialog box ,use the folloe=wing methodFd.setVisible(true); These three methods i.e. in step 2 & 3 should be in the actionPerformed() method to use. Eg:import java.awt.*; import java.awt.event.*; public class Menu1 extends Frame implements ActionListener { MenuBar mb; Menu fmenu,emenu; MenuItem nitem,oitem,sitem,eitem,cutitem,copyitem,pasteitem; TextArea ta; FileDialog fd; Menu1() { ta=new TextArea(); add(ta); mb=new MenuBar(); setMenuBar(mb); fmenu=new Menu(“File”); emenu=new Menu(“Edit”); mb.add(fmenu); mb.add(emenu); nitem=new MenuItem(“New”,new MenuShortcut(KeyEvent.VK_N)); oitem=new MenuItem(“Open”,new MenuShortcut(KeyEvent.VK_O)); sitem=new MenuItem(“Save”,new MenuShortcut(KeyEvent.VK_S)); eitem=new MenuItem(“Exit”,new MenuShortcut(KeyEvent.VK_E)); fd=new FileDialog(this); cutitem=new MenuItem(“Cut”); copyitem=new MenuItem(“Copy”); pasteitem=new MenuItem(“Paste”); nitem.addActionListener(this); oitem.addActionListener(this); sitem.addActionListener(this); eitem.addActionListener(this); cutitem.addActionListener(this); copyitem.addActionListener(this); pasteitem.addActionListener(this); fmenu.add(nitem); fmenu.add(oitem); fmenu.add(sitem); fmenu.add(eitem); emenu.add(cutitem); emenu.add(copyitem); emenu.add(pasteitem); setBounds(100,100,400,400); setVisibel(true); setResizable(false); setTitle(“Notepad”); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==eitem) { System.exit(0); } if(ae.getSource()==oitem) { fd.setTitle(“open”); fd.setMode(fd.LOAD); fd.setVisibel(true); } if(ae.getSource()==sitem) { fd.setTitle(“Save”); fd.setMode(fd.SAVE); fd.setVisibel(true); } if(ae.getSource()==nitem) { ta.setText(“”); } } public static void main(String a[]) { new Menu1(); } } Adapter classes Java.awt.event package provide set of pre-defined classes called Adapter classes they are use to simplify the event handling code,because every adapter class has implemented add method of there corresponding listenerInterface therefore while implementing adapter class we need to override only required things. Adapter class Implements 1)WindowAdapter WindowListener 2)MouseAdapter MouseListener 3)KeyAdapter KeyListener 4)FocusAdapter FocusListener Anonymous class:As the name suggest class without any name is called anonymous class.Such classes are defined as a argument inside method.That is anonymous also simplify the event handling code therefore we need to override only the required method. Syntax:Obj.addXXXXListener(new AdapterClassName() { public returntype method(args) { } }); Note:-While using Adapter classes we nees not to implement corresponding listener Interface. Eg:If we are going to WindowAdapter therefore we need to WindowListener. Thread Java.lang Class Thread:A thread is a thread of execution in a program.The java virtual machine allowe an application to have multiple threads of execution running concurrently. Every thread has a priority.Threads with higher priority are executed in preference to threads with lower priority. Constructor:1)Thread() Allocates a new Thread object. 2)Thread(Runnble target) Allocates a new Thread object. 3)Thread(Runnable target,String name) Allocates a new Thread object. 4)Thread(String name) Allocates a new Thread object. 5)Thread(ThreadGroup group,Runnable target) Allocates a new Thread object. Methods:1)static Thread currentThread() Return a reference to the currently executing thread object. 2)String getName() Returns this thread’s name. 3)int getPriority() Returns this thread’s priority. 4)void setName(String name) Changes the name of this thread to be equal to the argument name. 5)void setPriority(int newPriority) Changes the priority of this thread. 6)static int activeCount() Returns the no. of active threads in the current thread’s thread group. 7)void start() Causes this thread to begin execution,this java virtual machine calls the run method of this thread. 8)void run() If this thread was constructed using a separate Runnable run object,then that Runnabel object’s run method is called,otherwise this method does nothing and returns. 9)static void sleeplong millis) Causes the currently executing thread to sleep(temporarily cause execution) for the specified no. of milliseconds. 10)static void sleep(long millis,int nanos) Same as above + plus the specified no. of nanoseconds. 11)void join() Waits for this thread to die. 12)void join(long millis) Waits at most millis milliseconds for this thread to die. 13)void join(long millis,int nanos) Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. 14)static void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execeute. Methods of Object class but used for Thread1)void wait() Causes current thread to wait until another thread invokes the notify() method the notifyAll() method for this object. 2)void wait(long timeout) Same as above +, or a specified amount of time has elapsed. 3)void wait(long timeout,int nanos) Same as above +,or some other thread interrupts the current thread,or a certain amount of real time has elapsed. 4)void notify() Wakes up a single thread that is waiting on this object’s monitor. 5)void notifyAll() Wakes up all thread that are waiting on this object’s monitor. Thread Priority 1)static int MAX_PRIORITY static maximum priority that a thread can have. 2)static int MIN_PRIORITY The minimum priority that a thread can have. 3)static int NORM_PRIORITY The default priority that is assigned to a thread. How to create Thread:There are two ways to create thread. i)Using Runnabel interface ii)Using Thread class 1)Runnable interface The Runnable interface should be implemented by any class whose instance are intended to be executing by a thread.The class define a method of no argument called run(). Method:public void run() when object implementing interface Runnable is used to create a thread starting the thread causes the object run method to be called. Using Runnable interface 1)create class that should be implement Runnable class. Thread class Create class that should extend thread Interface. 2)Create thread object using – explicitly Thread is no need to create object Thread th=new Thread(this); super(args). it can be created implicitly using (indicates current class is implementer of Runnable) 3)Using Thread object call the start method. any Call the start() method directly without Th.start(); object start(); 4)Write the code to be executed using directly Write the code to be executed public void run() public void run() { } Note:1)To specify the delay use sleep() method in try-catch block because it throws InterruptedException. 2)We should prefer Runnable interface to create thread,because java allows single inheritance. Eg:-// using Runnable interface class RunnableDemo implements Runnable { Thread th; RunnableDemo() { th=new Thread(this,”Child Thread”); th.start(); System.out.println(th.getName() +”start here………”); } public void run() { for(int i=0;i<4;i++) { System.out.println(“Inside”+getName() +”i=”+i); try{ th.sleep(1000); }catch(Exception e) { System.out.println(“Error is “+e); } } System.out.println(th.getName() +”ends here…………”); } public static void main(String a[]) { System.out.println(“Main thread start here……..”) RunnableDemo rd=new RunnableDemo(); for(int i=0;i<4;i++) { System.out.println(“Inside main i=”+i); try{ Thread.sleep(1000); }catch(Exception e) { System.out.println(“Error is”+e); } } System.out.println(“Main thread ends here………”); } } Eg:-2) // using Thread class class ExtendingThread extends Thread { ExtendingThread() { super(“Child Thread”); start (); System.out.println(getName()+”start here…………..”); } public void run() { for(int i=0;i<4;i++) { System.out.println(“Inside”+getName()+”i=”i); try{ sleep(1000); }catch(Exception e) { System.out.println(“Error is”+e); } } System.out.println(getName() +”ends here……”); } public static void main(String a[]) { System.out.println(“Main thread start here………”); ExtendingThread ed=new ExtendingThread(); for (i=0;i<4;i++) { System.out.println(“Inside main i=”+i); try{ Thread.sleep(1000); }catch(Exception e) { System.out.println(“Error is”+e); } } System.out.println(“Main thread ends here………..”); } } How to Thread in Applet:Eg:import java.awt.*; import java.applet.*; /* <applet code=”ColorChange” width=600 height=400> </applet> public class ColorChange extends Applet implements Runnable { Thread t=null; int start; boolean stop; Color c; public void start() { t=new Thread(this); stop=false; t.start(); } public void run() { for(; ;) } c=new Color((float)Math.random();(float)Math.random(),(float)Math.random()); try{ repaint(); Thread.sleep(1000); if(stop) break; }catch(InterruptedException ie) { } } } public void stop() { t=null; stop=true; } public void paint(Graphics g) { setBackground(c); } } Eg:import java.awt.*; import java.applet.*; /*<applet code=”ChangingImg” width=600.height=400> </applet> public class ChangingImg extends Applet implements Runnable { Thread t=null; int start(); boolean stop; Image img[]=new Image[3]; String name[]={“main_3.gif” , “main_pic.gif” ,”sigma121-141.gif”}; public void init() { for(int i=0;i<name.length;i++) { img[i]=getImage(getCodeBase().name[i]); } public void start() { t=new Thread(this); stop=false; t.start(); } public void run() { for(; ;) { try{ repaint(); Thread.sleep(1000); if(stop) break; }catch(Exception e) { } } } public void stop() { t=null; { stop=true; } public void paint(Graphics g) { for(int i=0;i<name.length;i++) { g.drawImage(img[i],50,50,200,200,this); try{ t.sleep(1000); }catch(Exception e) { System.out.println(“Error in draw” +e); } } } } } } Thread Synchronisation In multithreaded application it is possible that same data or resource can be shared by multiple threads.While sharing the same resources by multiple thread it may lead loss of data integrity(validity). Therefore to ensure that the resource will be use by only one at a time the concept of synchronization will be used. There are two ways to implement synchronization – 1)By using Synchronize method Syntax:synchronize returntype method(args) 2)By using Synchronize block Syntax:returntype method(arg) { Synchronized(object) { } } Eg:class DataDemo { synchronized void demo(String str) //void demo(String str) { System.out.println(“ [ “+str); try{ Thread.sleep(1000); }catch(Exception e) { System.out.println(“Error is”+e); } System.out.println(“ ] “); } } class ThreaDemo implements Runnable { DataDemo dd; String msg; Thread th; ThreadDemo(DataDemo dd,String msg) { this.dd=dd; this.msg=msg; th=new Thread(this); th.start(); } public void run() { //synchronized(dd) // { dd.demo(msg); // } } } class SynchDemo { public static void main(String arg[]) { DataDemo dd=new DataDemo(); ThreadDemo td1=new ThreadDemo(dd.”Hello”); ThreadDemo td2=new ThreadDemo(dd.”Friends”); ThreadDemo td3=new ThreadDemo(dd.”Wellcome”); } } Java.net Networking is group of computers & its peripherals connected together to enable communication & sharing of resources. Some networking related terminology1)client The PC using which any request is send called client. 2)Server The PC which is use to generate the response according to request & send back to requestor is called Server. 3)IP-Address When no. of PC’s communicate in network then each PC have unique identification no. called IP-Address.IP-Address is actually 32-bits no. separated using dots(.). Eg:-192.168.0.1 4)Port Numbers:It is actually 16-bits no. which can be between range of 0-65535.While working on internet we must avoid the port no. below 1024,because they are already allocated to some predefined services. Client data IP-Address Server Port No. Port No. IP-Address data 5)Protocols:When no. of PC’s use in a network then set of rules must be followed by every PC to enable communication & sharing of resource this rules are called Protocols. Commanly used Protocols arei)HTTP:-Hyper Text Transfer Protocol enable sending or receiving text. ii)SMPT:-Simple Mail Transfer Protocol enable sending or receiving e-mails. iii)FTP:-File Transfer Protocol enable sending or receiving files. iv)TCP/IP:-Transmission Control Protocol/Internet Protocol. This is acknoeledgmet based bio-directional protocols use to send or receive confidential or important data because it is always guaranteed that data will send to destination. It is known as acknowledgement base because data receiver can send confirmation about receive data. v)UDP:-User Datagram Protocol It is single directional protocol used to send large amount of data in fastest way. The data receiver cannot confirm about receive data.It is mainly used to send large information like,video,audio,images file. It is not guaranteed that data will reach to destination it may be routed differently as well as data sequence is also not guaranteed.It is also possible that some part of data might be lost in travelling. Java.net Package:This package provides set of pre-defined classes,which arer based on TCP/IP & UDP based protocols.Using those class we can implement networking base java application. Class InetAddress getByName(String host) Petermines the IP address of a host,given the host’s name. static InetAddress[] getAllByName(String host) Given the name of a host,return an array of its IP address,based on the configured name service on the system. static InetAddress getLocalHost() Returns the local Host. String getHostName() Gets the host name for this IP address. String getHostAddress() Returns the IP address string in textual presentation. Class ServerSocket This class implements server sockets.A server socket waits for request to come in over the network.It performs some operation based on that request ,and then possibly returns a result to the requester. Constructor:ServerSocket() Creates an unbound server socket. ServerSocket(int port) Creates a server socket,bound to the specified port. Methods:Socket accept() Listens for a connection to be made to this socket and accepts it. void close() Closes this socket. Class Socket This class implements client sockets(also called just “Sockets”).A socket is an endpoint for communication between two machines. Constructor:Socket() Creates an unconnected ssocket,with the system-default type of SocketImpl. Socket(InetAddress addreadd,int port) Creates a stream socket and connects it to the specified port no. at the specified IP Address. Socket(String host,int port) Creates a stream socket and connects it to the specified port no. of named host. Socket(String host,int port,InetAddress LocalAddr,int LocalPort) Creates a socket and connects it to the specified remote host on the specified remote port. Methods:InetAddress getInetAddress() Returns the address to which the socket is connected. InetAddress getLocalAddress() Gets the local address to which the socket is bound. int getLocalPort() Returns the local port to which this socket is bound. Outputstream getOutputStream Returns an O/P stream for this socket. InputStream getinputstream() Returns an I/P stream for this socket. Int getPort() Returns the remote port to which this socket is connected. InetAddress getInetAddress() Returns the address to which the socket is connected. Class DataGramPacket Datagram packets are used to implement a connection less packet delivery service.Each message is routed from one machine to another based solely on information contained within that packet.Multiple packets sent from machine to another might be routed differently and might arrive in any order.Packet delivery is not guaranteed. Constructor:DatagramPacket(byte [] buf,int length) Constructs a DatagramPacket for receiving packets of length length. DatagramPacket(byte []buf,int offset,int length) Constructs a DatagramPacket for sending packets of length length to the specified port no. on the specified host. DatagramPacket(byte []buf,int length,SocketAddress address) Constructs a datagram packet for sending packets of length length to the specified port no. on the specified host. Methods:byte [] getData() Returns the data buffer. int getlength() Returns the length of the data to be sent on the length of the data received. InetAddress getAddress() Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. int getPort() Returns the port no. on the remote host to which this datagram is being sent or from which the datagram was received. Class DatagramSocket This class represents a socket for sending & receiving datagram packets. Constructor:DatagramSocket() Constructs a datagram socket & binds it to any available port on the host machine. DatagramSocket(int port) Constructs a datagram socket & binds it to the specified port on the local host machine. DatagraSocket(int port,InetAddress laddr) Methods:void receive(DatagramPacket p) Receives a datagram from this socket. void send(DatagramPacket p) Sends a datagram packet from this socket. Eg:-1 import java.net.*; import java.awt.*; import java.awt.event.*; public class ClientSocketGUI extends Frame implements ActionListener,Runnable { ServerSocket ss; Socket s; BufferedReader remote; PrintStream ps; Label l1,l2; TextField t1; Button b; Panel p1,p2,mainPanel; Thread th; public ClientSocketGUI() { l1=new Label(“Data”); l2=new Label(“Message received”); t1=new TextField(30); ta=new TextArea(); b=new Button(“Send’); p1=new Panel(); p1.add(l1); p1.add(t1); p1.add(b); p2=new Panel(); p2.add(l2); p2.add(ta); mainPanel=new Panel(); mainPanel.add(p1); mainPanel.add(p2); add(mainPanel); b.addActionListener(this); addActionListener(new WindowAdapter () { public void windowClosing(WindowEvent we) { System.exit(0); } }); setTitle(“Client”); setSize(400,400); setVisiible(true); try{ s=new Socket(“local host”,2000); remote=new BufferedReader(new InputStreamReader(s.getInputSteam()); ps=new PrintStream(s.getOutputStream()); th=new Thread(this); th.start(); }catch(Exception e) { System.out.println(“Error in server”+e); } public void run() { try{ while(true) { String remotedata=remote.readLine(); ta.append(remotedata+”\n”); }}catch{Exception e) { System.out.println(“Error is”+e); } } public void actionPerformed(ActionEvent ae) { try{ String localdata=t1.getText(); }catch(Exception e) { System.out.println(“Error is”+e); } } public static void main(String arg[]) { new ClientSocketGUI(); } } } } Eg:import java.net.*; import java.awt.*; import java.awt.event.*; import java.in.*; public class ServersocketGUI extends Frame implements ActionLiostener,Runnable { ServerSocket ss; Socket s; BufferedReader remote; PrintStream ps; Label l1,l2; TextField t1; Button b; Panel p1,p2,mainPanel; Thread th; public ServerSocketGUI() { l1=new Label(“Data”); l2=new Label(“Message received”); t1=new TextField(30); ta=new TextArea(); b=new Button(“Send’); p1=new Panel(); p1.add(l1); p1.add(t1); p1.add(b); p2=new Panel(); p2.add(l2); p2.add(ta); mainPanel=new Panel(); mainPanel.add(p1); mainPanel.add(p2); add(mainPanel); b.addActionListener(this); addWindowListener(new WindowAdapter () { public void windowClosing(WindowEvent we) { System.exit(0); } }); setTitle(“Server”); setSize(400,400); setVisiible(true); try{ ss=new ServerSocket(2000); s=ss.accept(); remote=new BufferedReader(new InputStreamReader(s.getInputSteam()); ps=new PrintStream(s.getOutputStream()); System.out.println(“Server started”); th=new Thread(this); th.start(); }catch(Exception e) { System.out.println(“Error in server initialization”+e); } public void run() { try{ while(true) { String remotedata=remote.readLine(); ta.append(remotedata+”\n”); }}catch{Exception e) { System.out.println(“Error is”+e); e.printStackTrace(); } } public void actionPerformed(ActionEvent ae) { try{ String localdata=t1.getText(); ps.println(localdata); }catch(Exception e) { System.out.println(“Error in Server”+e); e.printStackTrace(); } } public static void main(String arg[]) { new ServerSocketGUI(); } } } } Eg:-ClientSocketDemo.java SeverSocketDemo.java