Você está na página 1de 127

1

Lesson 1:Getting Started Ex1 Greeting.java class Greeting { public static void main(String[] args) { System.out.println("Hello World!"); } } TestGreeting.java class TestGreeting { public static void main(String[] args) { Greeting g=new Greeting(); g.display(); } } Lesson 2 :Object Oriented Programming Ex:1 Dog.java class Dog { public Dog() { weight=5; } private int weight;//member variable public void set(int value)//local variable { if(value>0) weight=value; } public int get() { return weight; } } //Dog(){weight=5;}------without parameter constructor //Dog()--------default constructor

TestDog.java class TestDog { public static void main(String[] args) { Dog d=new Dog(); d.set(-30); System.out.println(d.get()); d.set(10); System.out.println(d.get()); d.set(-14); System.out.println(d.get()); d.set(20); System.out.println(d.get()); d.set(-11); System.out.println(d.get()); } } Ex2: creating Packages Dog.java package zoo; public class Dog { private int weight; public Dog() { weight = 42; } public int getWeight() { return weight; } public void setWeight(int newWeight) { weight = newWeight; } }

Test.java import zoo.Dog; public class Test { public static void main(String[] args) { Dog d = new Dog(); d.setWeight(30); System.out.println("The dog has a weight of " + d.getWeight()); } } //javac -d E:\prabha \demo Dog.java //javac Test.java //java Test Ex3:Creating java technology API documentation public class Demodoc { private int x; private int y; public void a() { } public void b() { } public static void main(String[] args) { System.out.println("Hello World!"); } } //javadoc Demodoc.java Ex4:Creating JAR file(executable files) MANIFEST.MF Main-Class: Test Hint:you should press the enter key after the Test. Test.java class Test { public static void main(String[] args) { System.out.println("Hello World!"); } } //javac Test.java //jar -cvfm bb.jar MANIFEST.MF Test.class //java -jar bb.jar

LESSON 3: Identifiers,keywords and Types EX1:Passbyvalue class Passbyvalue { public void increment(int y) { y++; System.out.println("y is "+y); } public static void main(String[] args) { int x=10; Passbyvalue p=new Passbyvalue(); System.out.println("X is "+x); p.increment(x); System.out.println("X is "+x); } } EX2:PassbyReference class PassbyRef { int a; PassbyRef() { a=10; } public void increment(PassbyRef y) { y.a++; System.out.println("y is "+y.a); } public static void main(String[] args) { PassbyRef x=new PassbyRef(); PassbyRef p=new PassbyRef(); System.out.println("X is "+x.a); p.increment(x); System.out.println("X is "+x.a); } }

public class Address { private String street; private String city; private String state; private String zipCode; public Address(String street, String city, String state, String zipCode) { this.street = street; this.city = city; this.state = state; this.zipCode = zipCode; } public String toString() { return street + "\n" + city + ", " + state + " " + zipCode; } } public class Student { private int studentID; private String firstName; private String lastName; private Address address; public Student(int id, String fn, String ln, Address addr) { studentID = id; firstName = fn; lastName = ln; address = addr; } public int getStudentID() { return studentID; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; }

public Address getAddress() { return address; } public String toString() { return firstName + " " + lastName + "\n" + address.toString(); } } public class TestStudent { public static void main(String[] args) { Address addr = new Address("One Java Place", "HomeTown", "State", "12345"); Student cust = new Student(1, "Java", "Duke", addr); System.out.println(cust); } } Ex3: This keyword to resolve ambiguity between instance variables and Parameters class DemoThis { int a;//member variable public DemoThis(int a)//local variable { this.a=a; System.out.println("a :"+a); } public static void main(String[] args) { DemoThis d=new DemoThis(20); } }

Ex4:This keyword to pass current object to another method or constructor Mydate.java public class MyDate { private int day; private int month; private int year; public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public MyDate(MyDate date) { this.day = date.day; this.month = date.month; this.year = date.year; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public MyDate addDays(int more_days) { MyDate new_date = new MyDate(this); new_date.day = new_date.day + more_days; // Not Yet Implemented: wrap around code... return new_date; } public String toString() { return "" + day + "-" + month + "-" + year; } }

TestMyDate.java public class TestMyDate { public static void main(String[] args) { MyDate my_birth = new MyDate(22, 7, 1964); MyDate the_next_week = my_birth.addDays(7); MyDate anotherDate = my_birth; System.out.println(the_next_week); System.out.println(my_birth); System.out.println(anotherDate); } } Lesson 4: Expressions and Flow control Ex:Variable Scope class DemoScope { int x; static int y; public void display() { int a=10;//local System.out.println(a); } public static void main(String[] args) { DemoScope d=new DemoScope(); d.display(); } } Assignment operator class AssignOp { public static void main(String arr[]) { int x , y, z; x= y = z = 5; x += y; //x=x+y Arithmetic assignment operator //x=10 y -= z; //y=y-z //y=0 z *= x; //z=z*x //z=50 System.out.println("The value of x is: " + x); System.out.println("The value of y is: " + y); System.out.println("The value of z is: " + z);

} } BitWiseAND class BitWiseOR { public static void main(String arr[]) { int x=128, y = 2; int a ; a = x>>>y; // Bit-wise OR operator System.out.println(a) ; } } BitWiseNOT class BitWiseNOT { public static void main(String arr[]) { int x=2; int a ; a = ~x; // Bit-wise NOT operator System.out.println("The bit-wise NOT of 2 is: " +a) ; } } BitWiseOR class BitWiseOR { public static void main(String arr[]) { int x=2, y = 3; int a ; a = x|y; // Bit-wise OR operator System.out.println("The bit-wise OR of 2 and 3 is: " +a) ; } } BitWiseXOR class BitWiseXOR { public static void main(String arr[]) { int x=2, y = 3; int a ; a = x^y; // Bit-wise XOR operator

10

System.out.println("The bit-wise XOR of 2 and 3 is: " +a) ; } } Precedence class Precedence { public static void main(String args[]) { int x=10; boolean b =true; if(b) { x = x++ + 1 -2 * 3 + 4 << 2 / 2 ; // Various operators used System.out.println("The value of x is:" + x); } else { x = 4<<2 - 10; System.out.println("The value of x is:" + x); } } } ShiftOp class ShiftOp { public static void main(String arr[]) { int a = -1; int b = a>>2; // Right shift operator int c = a<<2; // Left shift operator int d = a>>>24; // Unsigned shift operator System.out.println("The result of right shift operator is:"+b); System.out.println("The result of left shift operator is:" +c); System.out.println("The result of unsigned shift operator is:"+ d); } } UnaryOp class UnaryOp { public static void main(String args[]) {

11

int x=5; int y=10; int a,b,c,d; a=x++; // Postfix increment operator b=y--; // Postfix decrement operator c=++x; // Prefix increment operator d=--y; // Prefix decrement operator System.out.println("The value of variable a is:" + a); System.out.println("The value of variable b is:" + b); System.out.println("The value of variable c is:" + c); System.out.println("The value of variable d is:" + d); } } Ex1:TestWhilloops public class TestWhileLoops { public static void main(String[] args) { test1(); test2(); test3(); test4(); } private static void test1() { System.out.println("Test #1 - while loop with block"); int i = 0; while ( i < 10 ) { System.out.println(i + " squared is " + (i*i)); i++; } } EX2 public class TestInitBeforeUse { public void doComputation() { int x = (int)(Math.random() * 100); int y; int z; if (x > 50) { y = 9;

12

} z = y + x; // Possible use before initialization System.out.println(z); } public static void main(String[] args) { new TestInitBeforeUse().doComputation(); } } EX3:Break with Labels public class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i = 0; int j = 0; boolean foundIt = false; search: for ( ; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + "not in the array");

13

} } } EX4:Continue with label public class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } }

Lesson 5: Arrays Two Types of Array 1.Character Array 2.Reference Array

14

Simple Char Array: public class SimpleCharArray { public static char[] createArray() { char[] s= new char[26]; for ( int i=0; i<26; i++ ) { s[i] = (char) ('A' + i); } return s; } public static void printArray(char[] array) { for ( int i = 0; i < array.length; i++ ) { System.out.print(array[i]); } } public static void main(String[] args) { char[] characters = createArray(); printArray(characters); System.out.println(); } } Simple Ref Array: class Customer { String name; String Address; public void display() { System.out.println("Name is " +name); System.out.println("Address is " +Address); } }; class CustomerDetails { Customer [] obj=new Customer[3];//create object array public CustomerDetails()

15

{ for(int i=0;i<obj.length;i++) { obj[i]=new Customer(); } obj[0].name="Jack"; obj[0].Address="ssdfdsfds"; obj[1].name="Jim"; obj[1].Address="jjjjjjjj"; obj[2].name="Jenny"; obj[2].Address="kkkkkkkk"; } public void disp() { for(int i=0;i<obj.length;i++) { obj[i].display(); } } public static void main(String[] args) { CustomerDetails c=new CustomerDetails(); c.disp(); } } class Point { int x; int y; public Point(int x1,int y1) { x=x1; y=y1; } }; public class SimpleRefArray { public static Point[] createArray() { Point[] p= new Point[3]; for ( int i=0; i<3; i++ )

16

{ p[i] = new Point(i,i+1); } return p; } public static void printArray(Point[] array) { for ( int i = 0; i < array.length; i++ ) { System.out.print(" x is "+array[i].x+" is "+ array[i].y+"\n" ); } } public static void main(String[] args) { Point[] characters = createArray(); printArray(characters); System.out.println(); } } Enhanced for Loop: public class EnhancedForLoop { public static int[] createArray() { int[] s= new int[5]; for ( int i=0; i<5; i++ ) { s[i] = i+10; } return s; } public static void printArray(int[] c) { for ( int list:c ) { System.out.print(list +"\t"); } } public static void main(String[] args)

" +" y

17

{ int[] b = createArray(); printArray(b); System.out.println(); } } 2D array public class Array2D { public static void main(String[] args) { int[][] data; data = new int[10][]; data[0] = new int[5]; data[1] = new int[20]; System.out.println("data.length = " + data.length); System.out.println("data[0].length = " + data[0].length); System.out.println("data[1].length = " + data[1].length); } } --------------------------------/** Show Two-Dimensional Array of Objects */ public class ArrayTwoDObjects { /** Return list of subscript names (unrealistic; just for demo). */ public static String[][] getArrayInfo() { String info[][]; info = new String[10][10]; for (int i=0; i < info.length; i++) { for (int j = 0; j < info[i].length; j++) { info[i][j] = "String[" + i + "," + j + "]"; } } return info; } /** Return list of allowable parameters (Applet method). */ public static String[][] getParameterInfo() { String param_info[][] = { {"fontsize", "9-18", "Size of font"},

18

{"URL", "-", }; return param_info; }

"Where to download"},

/** Run both initialization methods and print part of the results */ public static void main(String[] args) { print("from getArrayInfo", getArrayInfo()); print("from getParameterInfo", getParameterInfo()); } /** Print selected elements from the 2D array */ public static void print(String tag, String[][] array) { System.out.println("Array " + tag + " is " + array.length + " x " + array[0].length); System.out.println("Array[0][0] = " + array[0][0]); System.out.println("Array[0][1] = " + array[0][1]); System.out.println("Array[1][0] = " + array[1][0]); System.out.println("Array[0][0] = " + array[0][0]); System.out.println("Array[1][1] = " + array[1][1]); } } Lesson 6:Inheritance Access Specifier Package p1 class X { public int a; private int b; protected int c; int d; } class Y { a=10; b=10//error c=10//error. it is not child class d=10; } class Z extends X { a=10;

19

b=10//error c=10 d=10; }; Package P2 class J { a=10; b=10//error c=10//error. it is not child class d=10;//error . it is outside package } class K extends P1.X { a=10; b=10//error c=10 d=10;//error . it is outside package }; Child object can access both classes(Parent,Child) class Base { public void a1() { System.out.println("Base ---a1"); } }; class Child extends Base { public void a2() { System.out.println("child ---a2"); } }; class Test { public static void main(String [] a) { Child c=new Child();// this object can access both classes c.a2(); c.a1(); }

20

}; Overloading/polymorphism Public void add(int a,int b) Public void add(int a,float b) Public void add(float a,int b) add(12.3f,56) Overriding/Inheritance class Base { public void a1() { System.out.println("Base ---a1"); } }; class Child extends Base { public void a1() { System.out.println("child ---a1"); } }; class Test { public static void main(String [] a) { Child c=new Child();// this object can access both classes c.a1(); } }; In Overriding, to use Parent members class Base { public void a1() { System.out.println("Base ---a1"); } }; class Child extends Base { public void a1() {

21

super.a1(); System.out.println("child ---a2"); } }; class Test { public static void main(String [] a) { Child c=new Child();// this object can access both classes c.a1(); } }; class Employee { String Ename; double Salary; public Employee() { Ename="John"; Salary=30000.00; } public String getDetails() { return ("Ename "+Ename+" Salary "+Salary); } } class Manager extends Employee { String deptname; public Manager() { deptname="Marketing"; } public String getDetails() { return ( super.getDetails()+" Department name :"+deptname); } }; class Test1 { public static void main(String [] s) {

22

Manager m=new Manager();//Parent construtor ,then child Constructor System.out.println(m.getDetails()); } }; Overriden methods can not be less Accessible. class Base { public void a1() { System.out.println("Base ---a1"); } }; class Child extends Base { private void a1() { System.out.println("child ---a2"); } }; class Test { public static void main(String [] a) { Base b=new Base();//only can access Parent b.a1(); Base bb=new Child();//can access parent and child bb.a1();//illegal } }; Constructor concepts Example1 class Base { int x; public Base(int y) { System.out.println("Base (y) constructor called"); x=y; } } class Child extends Base

23

{ } class Test { public static void main(String [] a) { //default constructor also can not be called . //because we have some constructor coding //Base b=new Base();//illegal Base b1=new Base(10);//legal,even it is giving error } }; The Class has a single default constructor .A Parent constructor is always called in addition to a child constructor Add the following coding for the solution public Base() { } Example2 class Base { int x; public Base(int y) { x=y; } }; class Child extends Base//error will come , to solve create 'Base()' in Parent { }; class Test { public static void main(String [] a) { Base b=new Base(10); } };

24

Java Programming permits you to refer to an object variable of one of the Parent class types class Base { public void a1() { System.out.println("Base ---a1"); } public void b() { System.out.println("Base ---b"); } }; class Child extends Base { public void a2() { System.out.println("child ---a2"); } public { } void b()

with

System.out.println("child ---b"); }; class Test { public static void main(String [] a) { Base b=new Child(); b.a1();//legal //b.a2();//can not access the child function b.b();//legal//child method is called at runtime.(virtual method invocation) } }; HomoGeneous Collections class Mydate { int day; int month;

25

int year; public Mydate(int day,int month,int year) { this.day=day; this.month=month; this.year=year; } public String toString() { return " day :"+day +" Month "+month+" Year "+year; } public static void main(String[] args) { Mydate [] obj=new Mydate[2]; obj[0]=new Mydate(22,5,2009); obj[1]=new Mydate(23,5,2009); System.out.println(obj[0]); System.out.println(obj[1]); } } HeteroGeneous Collections class Employee { String Ename; double Salary; public Employee() { Ename="John"; Salary=30000.00; } public String toString() { return ("Ename "+Ename+" Salary "+Salary); } } class Manager extends Employee { String deptname; public Manager() { deptname="Marketing"; } public String toString() {

26

return ( " }

Department name

:"+deptname);

}; class Test1 { public static void main(String [] s) { Employee[] obj=new Employee[2]; obj[0]=new Employee(); obj[1]=new Manager(); System.out.println(obj[0]); System.out.println(obj[1]); } }; Polymorphic Arguments //java Programming permits you to refer to an object variable of one of the Parent class types class Employee { int Rate; public Employee() { Rate=500; } }; class Manager extends Employee { int Rate1; public Manager() { Rate1=1000; } }; class Taxservice { public int FindTaxRate(Employee e) { int amt= e.Rate * 10; //amt=e.Rate1*10; return amt; } }

with

27

class Test { public static void main(String [] a) { Taxservice t=new Taxservice(); Manager m=new Manager(); System.out.println(t.FindTaxRate(m)); } }; Object class is the Parent for all classes class demo { public static void main(String[] args) { System.out.println("Hello World!"); } } //javap demo Class demo Class demo extends Object Example of INSTANCEOF class Employee { }; class Manager extends Employee { }; class Engineer extends Employee { }; class Test { public void dosomething(Employee e) { if( e instanceof Manager) System.out.println("This is Manager"); else if(e instanceof Engineer) System.out.println("This is Engineer"); else System.out.println("This is Employee"); } public static void main(String [] a) {

28

Manager m=new Manager(); Employee em=new Employee(); Engineer en=new Engineer(); Test t=new Test(); t.dosomething(em); } }; Casting Objects need to access the functionality of sub classes 1.upward(implicit)(child-Parent) 2.downwad(explicit)(Parent-child) 3.Child to child type casting is not possible .(runtime error occurs) class Employee { public void a() { System.out.println("Employee a()"); } }; class Manager extends Employee { public void b() { System.out.println("Manager b()"); } }; class Engineer extends Employee { public void c() { System.out.println("Engineer c()"); } }; class Test { public void dosomething(Employee e) //upward casting (implicit) { if( e instanceof Manager) {

29

Manager m=(Manager) e;//downward cating (explicit) m.b(); } else if(e instanceof Engineer) { Engineer en=(Engineer) e;//legal //Manager m=(Manager) e;//(child to child :wrong)//ClassCastException thrown m.b(); } else { e.a(); } } public static void main(String [] a) { Manager m=new Manager(); Employee em=new Employee(); Engineer en=new Engineer(); Test t=new Test(); t.dosomething(en); } };

Overloading Methods Public void add(int i)-------both are same function . can not overload Public int add(int j) Public void add(int i)-------both are different . can be overloaded Public void add(float j) Methods using variable arguments function

30

class Test { public float average(int... num) { int sum=0; for(int value :num) { sum=sum+value; } return ((float)sum)/num.length; } /*public float average(int n1,int n2)//Instead of this, make one method { int sum=n1+n2; return ((float)sum)/2; } public float average(int n1,int n2,int n3) { int sum=n1+n2+n3; return ((float)sum)/3; } public float average(int n1,int n2,int n3,int n4) { int sum=n1+n2+n3+n4; return ((float)sum)/4; }*/ public static void main(String [] a) { Test t=new Test(); System.out.println(t.average(10,20)); System.out.println(t.average(10,20,30)); System.out.println(t.average(10,20,30,40)); } }; Overloading Constructor class Date { int day; int month; int year;

31

public Date(int day, int month,int year) { this.day=day; this.month=month; this .year=year; } public String toString() { return day+"/"+month+"/"+year; } }; class Employee { public static final double BASE_SALARY=15000.00; String name; double salary; Date DOB; public Employee(String name1,double salary1,Date DOB1) { name=name1; salary=salary1; DOB=DOB1; } public Employee(String name,double salary) { this(name,salary,null);//this line should be first. } public Employee(String name,Date DOB) { this(name,BASE_SALARY,DOB);//calls the another constructor } public String toString() { return "Name is :"+name+"\nSalary is :"+salary+"\nDOB is "+DOB; } }; class Test { public static void main(String [] a) { //Employee e=new Employee("john",34000.00); Date d1=new Date(22,5,1980);

32

Employee e=new Employee("john",d1); System.out.println(e); } }; class has a single defalut constructor . class Employee { String name; public String get() { return "Name is :"+name; } }; class Manager extends Employee { String dept; public String toString() { return super.get()+"\ndept is :"+dept; } }; class Test { public static void main(String [] a) { Manager m=new Manager(); System.out.println(m); } }; Super() calls Parent Constructor class Employee { String Ename; double Salary; public Employee() { Ename="jack"; Salary=10000; } public Employee(String Ename,double Salary) { this.Ename=Ename; this.Salary=Salary; } public Employee(String Ename) {

33

this.Ename=Ename; } public String getDetails() { return ("Ename "+Ename+" }

Salary

"+Salary);

} class Manager extends Employee { String deptname; public Manager(String Ename,double Salary,String dept) { super(Ename,Salary); deptname=dept; } public Manager(String Ename,String dept) { super(Ename); deptname=dept; } public Manager(String dept)//here there is no super keyword.so it calls super() { deptname=dept; } public String getDetails() { return ( super.getDetails()+" Department name :"+deptname); } }; class Test1 { public static void main(String [] s) { //Manager m=new Manager("John",20000.00,"Marketing"); //Manager m=new Manager("John","Marketing"); Manager m=new Manager("Marketing"); System.out.println(m.getDetails()); } }; Object class has two functions(1.equals(), 2.toString()) class MyDate {

34

int day; int month; int year; public MyDate(int day, int month,int year) { this.day=day; this.month=month; this .year=year; } public boolean equals(Object c) { boolean result =false; if((c !=null ) && (c instanceof MyDate)) { MyDate d=(MyDate) c; if((day==d.day)&& (month==d.month) && (year==d.year)) { result=true; } } return result; } public int hascode() { return (day^month^ year); } } class TestEquals { public static void main(String [] a) { MyDate dat1=new MyDate(22,3,1980); MyDate dat2=new MyDate(22,3,1980); if(dat1==dat2) { System.out.println("Date1 is identical to date2"); } else { System.out.println("Date1 is not identical to date2"); } if(dat1.equals(dat2))

35

{ System.out.println("Date1 is identical to date2"); } else { System.out.println("Date1 is not date2"); } System.out.println("set Date2 = date1"); dat2=dat1; if(dat1==dat2) { System.out.println("Date1 is identical to date2"); } else { System.out.println("Date1 is not date2"); } } }; Lesson7:Advanced class Features Ex1:Static class FunctionStatic { static int x=0;//static int y=0;//member public FunctionStatic() { x++; y++; } public static int totalcount() { return x; //return y;//cannot used non-static variable inside static function } } public class TestFunctionStatic { public static void main(String[] args) { identical to identical to

36

FunctionStatic obj=new FunctionStatic(); System.out.println(FunctionStatic.totalcount()); FunctionStatic obj1=new FunctionStatic(); System.out.println(FunctionStatic.totalcount()); } } Proofs:Static constructor can not create static FunctionStatic() { x++; } NO need of class name class FunctionStatic { static int x=0;//static public static int totalcount() { x++; return x; } public static void main(String[] args) { System.out.println(totalcount()); System.out.println(totalcount()); } } EX2:Static block class FunctionStatic { static int x; int y; static//called once when class is loaded { System.out.println(" static block called"); x=10; } public FunctionStatic ()// called when obj is called { System.out.println(" construtor called"); y=10; } public void display() { x++; y++;

37

System.out.println(" x is }

"+x+"

y is

" +y);

} class TestFunctionStatic { public static void main(String[] args) { FunctionStatic obj1=new FunctionStatic(); obj1.display(); FunctionStatic obj2=new FunctionStatic(); obj2.display(); FunctionStatic obj3=new FunctionStatic(); obj3.display(); } } EX3:Count Objects class CountObjs { // public static int count=0; private static int count=0; public CountObjs() { count++; System.out.println(count); } } public class TestCountObjs { public static void main(String[] args) { CountObjs cb=new CountObjs(); CountObjs cb1=new CountObjs(); CountObjs cb2=new CountObjs(); System.out.println(CountObjs.count); System.out.println(cb.count); } } Ex4: can not Count objects without static class count {

// //

38

int serialnumber; public int counter=0; count() { counter++; serialnumber=counter; } } class test { void display() { count c1=new count(); System.out.println("value of counter="+c1.serialnumber); count c2= new count(); System.out.println("value of counter="+c2.serialnumber); count c3=new count(); System.out.println("value of counter="+c3.serialnumber); } public static void main(String[] args) { test obj=new test(); obj.display(); } } Ex5:Static concept in Overridden method class count1 { public void some() { System.out.println("count1-some function"); } public static void disp() { System.out.println("count1"); } } class count2 extends count1 { public void some()

39

{ System.out.println("count2 some function"); } public static void disp() { System.out.println("count2"); } } public class TestCount { public static void main(String[] args) { count1 obj=new count2(); obj.some(); //Some overridden function is non static //method is invoked for which class memory is allocated. count1 obj1=new count2(); obj1.disp(); //overridden methods should be non-static. //if Static in overriding concept // then the method invoked is one for the class for which the variable is declared.} } Ans: Count2 some function Count1 Final Demo class Base { public final void a(){} } class child extends Base { public void a(){} }; class Test { public static void main(String[] args) { System.out.println("Hello World!"); } }; Final demo2

40

class Test { //public final int a=10; public final int a;//blank final variable public Test() { a=10; } public void a() { //public int c;//In local variable , can't specify Access specifier final int b;//local blank final variable b=10; b=20; //a=20;error //a++;//error } public static void main(String[] args) { System.out.println("Hello World!"); } }; Check enum Day { sun,mon,tue,wed,thu,fri,sat } public class Test { public static void main(String[] args) { //Day d=new Day();//can not create object Integer a=Day.fri; System.out.println(a); } } Old Enumerated Type package cards.domain; public class PlayingCard { public static final int SUIT_SPADES=0; public static final int SUIT_HEARTS=1; public static final int SUIT_CLUBS=2; public static final int SUIT_DIAMONDS=3;

41

private int suit; private int rank; public PlayingCard(int suit,int rank) { this.suit=suit; this.rank=rank; } public int getSuit() { return suit; } public int getRank() { return rank; } public String getSuitName() { String name=""; switch(suit) { case SUIT_SPADES: name="Spades"; break; case SUIT_HEARTS: name="Hearts"; break; case SUIT_CLUBS: name="Clubs"; break; case SUIT_DIAMONDS: name ="Diamonds"; break; default: System.err.println("Invalid suit"); } return name; } } import cards.domain.PlayingCard; class TestPlayingCard { public static void main(String[] args) {

42

PlayingCard card1=new PlayingCard(PlayingCard.SUIT_SPADES,2); System.out.println(" card1 is the "+card1.getRank()+" of "+ card1.getSuitName()); PlayingCard card2=new PlayingCard(47,2);//no proper output; System.out.println(" card1 is the "+card2.getRank()+" of "+ card2.getSuitName()); } }

New Enumerated Type Problem of old enumerated types:Type safety issues Suit.java package cards.domain; public enum Suit { SPADES,HEARTS,CLUBS,DIAMONDS } PlayingCard.java package cards.domain; public class PlayingCard { private Suit suit; private int rank; public PlayingCard(Suit suit,int rank) { this.suit=suit; this.rank=rank; } public Suit getSuit() { return suit; } public int getRank() { return rank; } public String getSuitName() { String name=""; switch(suit)

43

{ case SPADES: name="Spades"; break; case HEARTS: name="Hearts"; break; case CLUBS: name="Clubs"; break; case DIAMONDS: name ="Diamonds"; break; default: System.err.println("Invalid suit"); } return name; } } TestPlayingCard.java import cards.domain.PlayingCard; import cards.domain.Suit; class TestPlayingCard { public static void main(String[] args) { PlayingCard card1=new PlayingCard(Suit.SPADES,2); System.out.println(" card1 is the "+card1.getRank()+" of "+ card1.getSuitName()); //PlayingCard card2=new PlayingCard(47,2);//it produces error. //System.out.println(" card1 is the "+card2.getRank()+" of "+ card2.getSuitName()); } } Advanced Enumerated Types Suit.java package cards.domain; public enum Suit { SPADES("Spades"), HEARTS("Hearts"), CLUBS("Clubs"), DIAMONDS("Diamonds"); private final String name;

44

private Suit(String name)//enum constructor are always less accessible { this.name=name; } public String getname() { return name; } } PlayingCard.java package cards.domain; public class PlayingCard { private Suit suit; private int rank; public PlayingCard(Suit suit,int rank) { this.suit=suit; this.rank=rank; } public Suit getSuit() { return suit; } public int getRank() { return rank; } } TestPlayingCard.java import cards.domain.PlayingCard; import cards.domain.Suit; class TestPlayingCard { public static void main(String[] args) { PlayingCard card1=new PlayingCard(Suit.SPADES,2); System.out.println(" card1 is the "+card1.getRank()+" of "+ card1.getSuit().getname());

45

//PlayingCard card2=new PlayingCard(47,2);//it produces error. //System.out.println(" card1 is the "+card2.getRank()+" of "+ card2.getSuitName()); } } Static Imports Car.java package vehicle; public class car { public static void move() { System.out.println("Hello wins the race"); } } Testcar.java import vehicle .car; class Testcar { public static void main(String[] args) { car.move(); } } Modifed into like following Testcar.java import static vehicle .car.*; class Testcar { public static void main(String[] args) { move(); } } Abstract class abstract class Shape { public void disp() { System.out.println("disp of Parent"); } public abstract double calculateArea(); } class circle extends Shape

46

{ int radius ; public double calculateArea() { radius=2; double CArea=3.14*radius*radius; return CArea; } }; class rect extends Shape { int l,b; public double calculateArea() { l=10; b=20; double CArea=l*b; return CArea; } }; class Test { public static void main(String [] a) { circle c=new circle(); c.disp(); System.out.println(c.calculateArea()); rect r=new rect(); System.out.println(r.calculateArea()); /*Shape s=new Shape(); //can not be instantiated s.disp();*/ } }; Interface demo1 interface I1 { //events,properties,methods public void a(); } class C1 implements I1 {

47

public void a() { System.out.println("This is a of C1"); } } class { C2 implements I1 public void a() { System.out.println("This is a of C2"); } } class Test { public static void main(String[] args) { C1 c1=new C1(); c1.a(); C2 c2=new C2(); c2.a(); } } Demo 2 interface I1 { public void a(); } interface I2 { public void b(); } class C1 implements I1,I2 { public void a() { System.out.println("This is a of C1"); } public void b() { System.out.println("This is b of C1"); } } class Test

48

{ public static void main(String[] args) { C1 c1=new C1(); c1.a(); c1.b(); } } Demo 3 interface I1 { public void a(); } interface I2 extends I1 { public void b(); } class C1 implements I2 { public void a() { System.out.println("This is a of C1"); } public void b() { System.out.println("This is b of C1"); } } class Test { public static void main(String[] args) { C1 c1=new C1(); c1.a(); c1.b(); } } Demo 4 interface I1 {

49

public void a(); public void b(); } class { C1 implements I1 public void a() { System.out.println("This is a of C1"); } public void b() { System.out.println("This is b of C1"); } } class Test { public static void main(String[] args) { C1 c1=new C1(); c1.a(); c1.b(); } } Lesson8:Exceptions and Assertions Unhandled Exception class UnhandledException { public static void main(String args[]) { int num1=0, num2=5; int num3=num2/num1; System.out.println ("The num3 = " + num3); } } Arithmetic Exception class ArithmeticExp { public static void main(String args[]) { int num1=0, num2=5,num3=0; try {

50

num3=num2/num1; } catch(ArithmeticException e) { System.out.println("Division by zero is performed"); } System.out.println("The result=" + num3); } } Multiple catch with Exception class public class TryCatch { public void disp() { System.out.println("this is disp"); } public static void main(String args[]) { int array[] = {10,20}; int num1, num2, result = 0; num1 = 100; num2 = 20; try { result = num1/num2; System.out.println(num1 / array[1]); TryCatch c=null; c.disp(); //more statements } catch(ArithmeticException e) { System.out.println("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error... Out of bounds"); } catch (Exception e) { System.out.println("Some other error"); }

51

System.out.println("The result is: " + result); //program proceeds } } Parent Exception class should be last catch block in the coding public class TryCatch { public static void main(String args[]) { int num1, num2, result = 0; num1 = 100; num2 = 0; try { result = num1/num2; } catch (Exception e) { System.out.println("Some other error"); } catch(ArithmeticException e) { System.out.println("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error... Out of bounds"); } System.out.println("The result is: " + result); } } Compile time error of uncaught This coding will give compile time errorArithmetic Exception already been caught Call Stack Mechanism class CallStack { public void disp()//called {

52

int Num1= 30 , Num2 = 0; int Num3=Num1/Num2; } public static void main(String args[]) //calling { CallStack c=new CallStack(); try { c.disp(); } catch(ArithmeticException obj) { //obj.printStackTrace(); System.out.println("division by zero"); } } } Finally Block public class TryCatch { public static void main(String args[]) { int array[] = {10,20}; int num1; num1 = 100; try { System.out.println(num1 / array[1]); } catch(ArithmeticException e) { System.out.println("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error... Out of bounds"); } finally { System.out.println("Program ended"); } } } Throw keyword class ThrowClass

53

{ static void throwDemo()//called { try { throw new IllegalStateException("MyException"); } catch(IllegalStateException objA) { System.out.println("Caught:" + objA); } } public static void main(String args[])//calling { throwDemo();//called } } Throws Keyword After function name only it is specified When throws comes calling function will have the try and catch block class ThrowsClass { static void throwMethod() throws ClassNotFoundException { System.out.println("In throwMethod"); //throw new ClassNotFoundException(); } public static void main(String args[]) { throwMethod();//compile error /*try { throwMethod(); } catch(ClassNotFoundException Obja) { System.out.println("throwMethod has thrown an Exception:" + Obja); }*/ } }

54

User defined Exception class UserException extends Exception { public String toString()//predefined method of Throwable class { return "UserException Caught: The sum of the numbers Exceeds 20.."; }//called by the println() method when throwable object is passed to it } class UserExceptionDemo { static void calculate(int a,int b) throws UserException { int sum; System.out.println("Calculate Method(" + a + "," + b + ")"); sum=a+b; if(sum>20) { throw new UserException(); } System.out.println("The Value of the sum of two numbers is:" + sum); } public static void main(String args[])//calling { try { calculate(12,1);//called calculate(15,7); } catch (UserException Obja) { System.out.println("Caught:" + Obja); } } } Assertions public class AssertionDemo { static int balance=1500; public static int transaction(int amt)

55

{ balance =balance-amt; System.out.println("Balance is :"+balance); return balance; } public static void main(String[] args) { int n; for(int i=0;i<4;i++) { n=transaction(400); assert balance>=500 : "Balance is below $500"; //error message is passed to AssertionError object when assertion fails } } } //to compile : javac -source 1.6 AssertionDemo.java //to execute(to enable) :java -ea AssertionDemo //to execute(to disable) :java -da AssertionDemo Lesson 9: File Handling Command Line arguments class Demo { public static void main(String[] a) { for (int i=0;i <a.length ;i++ ) { System.out.println( a[i]); } } } //javac Demo.java //java Demo john jack System Properties

56

import java.util.Proprties; import java.util.Enumeration; class TestProperties { public static void main(String[] args) { Properties props=System.getProperties(); Enumeration pname=props.propertyNames(); while(pname.hasMoreElements()) { String propName =(String)pname.nextElement(); String value=props.getProperty(propName); System.out.println("Property ' "+propName+"' is '"+value +"'"); } } } //javac TestProperties.java //java TestProperties //java -DCustom=niit TestPropertiese Println and print class Demo { public static void main(String[] args) { System.out.println("hello"); System.out.print("h1 ");

57

System.out.print("niit"); } } Reading from Standard input import java.io.*; class KeyBoardInput { public static void main(String[] args) { System.out.println("Unix: type ctrl-d to exit."+"\nWindow: type ctrl -z to exit"); System.out.println("Enter the input"); String s; InputStreamReader ir=new InputStreamReader(System.in); BufferedReader in=new BufferedReader( ir ); try { /*s=in.readLine(); while(s !=null) { System.out.println("Read :"+s); s=in.readLine(); }*/ while((s=in.readLine()) !=null) { System.out.println("Read :"+s); } in.close(); } catch(Exception e) { e.printStackTrace(); } } } BufferReader,InputStreamReader --readLine() can read from Standard input (keyboard) BufferReader,FileReader --readLine() can read from File PrintWriter,FileWriter-- print(), println() can print(write) on file

58

Printf Demo class Demo1 { public static void main(String[] args) { String name="jack"; int age=65; float salary=34000.00f; : %f System.out.printf("Name ",name,age,salary); : %s %nAge : %d %nSalary

} } Scanner class for simple formatted input import java.io.*; import java.util.Scanner; public class ScanTest { public static void main(String[] args) { Scanner s = new Scanner(System.in); String param =s.next();//for string input System.out.println("the param1 " + param); int value = s.nextInt();// for Interger input System.out.println("the param2 " + value); s.close(); } } Create File objects import java.io.*; class TestFile { public static void main(String[] args) { File f1=new File("c:\\aa.txt"); System.out.println(f1.getPath()); } } Note: This will not create the physical file for us . It creates file only in Buffer memory Demo1

59

import java.io.*; class TestFile { public static void main(String[] args) { File f1=new File("c:\\aaaa.txt"); try { BufferedWriter bw=new BufferedWriter(new FileWriter(f1)); } catch(Exception e) { e.printStackTrace(); } System.out.println(f1.getPath()); } } Note: When we write the File object with FileWriter class , then only physical file will be created . Demo2 import java.io.*; class TestFile { public static void main(String[] args) { //File f1=new File("c:\\niit","aa.txt"); File mydir=new File("C:\\niit"); File myfile=new File(mydir,"aa.txt"); System.out.println(myfile.getPath()); } } Demo 3

1)directory is just another file.

60

2)File object does not permit you to access the contents of the file. import java.io.*; class Files { public static void main(String args[])throws NullPointerException { String dirName = "C:/Test"; File f = new File(dirName, "work.txt"); File f3 = new File(dirName, "renFile.txt"); System.out.println("File name is:" +f.getName()); System.out.println("Path of the file is:" +f.getPath()); System.out.println("Parent directory is:" +f.getParent()); System.out.println("Listing the contents of directory"); File f1 = new File(dirName); String s[] = f1.list(); for(int i = 0;i<s.length;i++) { File f2 = new File("\t" +dirName+ "/" +s[i]); if(f2.isDirectory()) { System.out.println("\t" +s[i] + "is a directory"); } else { System.out.println("\t" +s[i] + "is a file"); } } } } Write into File import java.io.*; class FileOutput { public static void main(String[] args) { try { BufferedReader in=new BufferedReader( new InputStreamReader(System.in)); PrintWriter fileout=new PrintWriter(new FileWriter(new File("c:\\aa.txt")));

61

String s; System.out.println(" Type ctrl -z to exit"); System.out.println("enter the name :");

s=in.readLine(); while(s !=null) { fileout.println(s); s=in.readLine(); } in.close(); fileout.close(); } catch(Exception e) { e.printStackTrace(); } } } Read from File import java.io.*; class FileInput { public static void main(String[] args) { try { BufferedReader filein=new BufferedReader(new FileReader(new File(args[0]))); String s; s=filein.readLine(); while(s !=null) { System.out.println(s); s=filein.readLine(); } filein.close(); }

62

catch(Exception e) { e.printStackTrace(); } } } Collections API

Set import java.util.*; public class SetExample { public static void main(String[] args) { Set set = new HashSet(); set.add("one"); set.add("second"); set.add("3rd"); set.add("new Integer(4)"); set.add("new Float(5.0F)"); set.add("second"); //Duplicate,not added//no error set.add("new Integer(4)"); //Duplicate,not added System.out.println(set); } } List import java.util.*; public class ListExample {

63

public static void main(String[] args) { List list = new ArrayList(); list.add("one"); list.add("second"); list.add("3rd"); list.add("new Integer(4)"); list.add("new Float(5.0F)"); list.add("second"); //Duplicate,added list.add("new Integer(4)"); //Duplicate, added System.out.println(list); } } Collections ,Problem:Warning,No Type Safety import java.util.*; public class GenericsWarning { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(0, new Integer(42)); int total = ((Integer)list.get(0)).intValue(); } } Generic Collections ---no warning , Type Safety import java.util.*; public class GenericsWarning { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, new Integer(42));//Explicit boxing int total = (list.get(0)).intValue();//Explicit unboxing System.out.println(total); } } Demo2 import java.util.*; public class GenericsWarning {

64

public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, 42);//Implicit boxing int total = list.get(0);//Implicit unboxing System.out.println(total); } } Iterator 1.It is the process of retrieving every element in the collection 2.Parent Interface(Iterator)--Child interface (ListIterator) 3.Iterator is set of unordered . a)hasNext()---only forward scan 4.ListIterator a)hasNext()---forward scan b)hasPrevious()---backward scan Forward Scan import java.util.*; public class IteratorExample { public static void main(String[] args) { List list = new ArrayList(); list.add("one"); list.add("second"); list.add("3rd"); list.add("new Integer(4)"); list.add("new Float(5.0F)"); list.add("second"); //Duplicate,added list.add("new Integer(4)"); Iterator e=list.iterator(); while(e.hasNext()) { System.out.println(e.next()); }

} } Backward scan import java.util.ArrayList; import java.util.Iterator;

65

import java.util.ListIterator; public class MainClass { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); System.out.print("Original contents of al: "); Iterator<String> itr = al.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.print(element + " "); } System.out.println(); ListIterator<String> litr = al.listIterator(); while (litr.hasNext()) { String element = litr.next(); litr.set(element);//or litr.set(element+ "+" ); } // Now, display the list backwards. System.out.print("Modified list backwards: "); while (litr.hasPrevious()) { String element = litr.previous(); System.out.print(element + " "); } } } http://www.java2s.com/Code/JavaAPI/java.util/ListIteratorha sPrevious.htm Enhanced for loop import java.util.ArrayList; class ForEachDemo { public static void main(String args[]) { ArrayList<Integer> vals = new ArrayList<Integer>();

66

vals.add(1); vals.add(2); vals.add(3); vals.add(4); vals.add(5); System.out.print("Original contents of vals: "); for (int v : vals) System.out.print(v + " "); System.out.println(); int sum = 0; for (int v : vals) sum += v; System.out.println("Sum of values: " + sum); } } Iterate a Collection and remove an item (Exception, wrong version) import java.util.ArrayList; import java.util.List; public class Main { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("C"); list.add("C"); list.add("C"); for (String s : list) { if (s.equals("B")) { list.remove("B"); } System.out.println(s); } } } /*A B Exception in thread "main" java.util.ConcurrentModification

67

Exception at java.util.AbstractList$Itr.checkForComodification(Abst ractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at Main.main(Main.java:17) */ Use an Iterator and remove the item with Iterator.remove() import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("C"); list.add("C"); list.add("C"); list.add("C"); for (Iterator<String> iter = list.iterator(); iter.hasN ext();) { String s = iter.next(); if (s.equals("B")) { iter.remove(); } else { System.out.println(s); } } for (String s : list) { System.out.println(s); } } } Lesson 14:Advanced IO streams

68

Node Streams

69

Example of FileWriter import java.io.*; public class TestFileWriter { public static void main (String args[]) { String str="Character Stream Classes in Java"; try { FileWriter fout = new FileWriter("stream.txt" ); fout.write(str, 0, str.length() ); fout.close(); } catch (IOException ioe) { System.out.println("Exception: " + ioe.toString()); } } //End of main() } Example of FileReader import java.io.*; public class TestFileReader {

70

public static void main(String args[]) { try { File file=new File("stream.txt"); FileReader f=new FileReader(file); int ch; while((ch=f.read())!=-1) //Loop till end of file. { System.out.print((char)ch); } } catch(FileNotFoundException fnfe) { System.out.println("Exception: "+fnfe.toString()); } catch(IOException ioe) { System.out.println("Exception: "+ioe.toString()); } } //End of main() } Copy Files Contents using read() import java.io.*; public class TestCopyFile { public static void main(String args[]) { try { FileReader fin=new FileReader(args[0]); FileWriter fout = new FileWriter(args[1] ); char[] buffer=new char[128]; int ch; ch=fin.read(buffer);//read one by one character while(ch!=-1) { //Loop till end of file.

71

fout.write(buffer, 0,ch ); ch=fin.read(buffer); } fin.close(); fout.close(); } catch(FileNotFoundException fnfe) { System.out.println("Exception: "+fnfe.toString()); } catch(IOException ioe) { System.out.println("Exception: "+ioe.toString()); } } //End of main() } Copy Files Contents using readLine() Example of ByteArrayInputStream and ByteArrayOutputStream

/*-------------------------------------------------* Write to record store using streams. *-------------------------------------------------*/ public void writeStream(String[] sData, boolean[] bData, int[] iData) { try { // Write data into an internal byte array ByteArrayOutputStream strmBytes = new ByteArrayOutput Stream(); // Write Java data types into the above byte array DataOutputStream strmDataType = new DataOutputStream( strmBytes); byte[] record; for (int i = 0; i < sData.length; i++) {

72

// Write Java data types strmDataType.writeUTF(sData[i]); strmDataType.writeBoolean(bData[i]); strmDataType.writeInt(iData[i]); // Clear any buffered data strmDataType.flush(); // Get stream data into byte array and write record record = strmBytes.toByteArray(); rs.addRecord(record, 0, record.length); // Toss any data in the internal array so writes // starts at beginning (of the internal array) strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Read from the record store using streams *-------------------------------------------------*/ public void readStream() { try { // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputSt ream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(st rmBytes);

73

for (int i = 1; i <= rs.getNumRecords(); i++) { // Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i); System.out.println("UTF: " + strmDataType.readUTF() ); System.out.println("Boolean: " + strmDataType.readB oolean()); System.out.println("Int: " + strmDataType.readInt() ); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } } /*-------------------------------------------------* Simple message to console for debug/errors * When used with Exceptions we should handle the * error in a more appropriate manner. *-------------------------------------------------*/ private void db(String str) { System.err.println("Msg: " + str); } } Lesson 10 :GUI components import java .awt.*; class Loginscreen { Frame fr; Panel pn;

74

Label l1,l2; TextField t1; PasswordTextField Button b1; public Loginscreen() { fr=new Frame(" Login screen"); pn=new Panel(); fr.add(pn); l1=new Label("User name"); l2=new Label("Password"); t1=new TextField(10); t2=new TextField(10); b1=new Button("Sign up"); pn.add(l1); pn.add(t1); pn.add(l2); pn.add(t2); pn.add(b1); fr.setSize(300,300); fr.setVisible(true); } }; class TestGUI { public static void main(String[] args) { Loginscreen obj=new Loginscreen(); } } Ex2 import java .awt.*; class Loginscreen { Frame fr; Panel pn; Label l1,l2; TextField t1; PasswordTextField Button b1;

75

public Loginscreen() { fr=new Frame(" Login screen"); pn=new Panel(); fr.add(pn); l1=new Label("User name"); l2=new Label("Password"); t1=new TextField(10); t2=new TextField(10); b1=new Button("Sign up"); pn.add(l1); pn.add(t1); pn.add(l2); pn.add(t2); pn.add(b1); fr.setSize(300,300); fr.setVisible(true); } }; class TestGUI { public static void main(String[] args) { Loginscreen obj=new Loginscreen(); } } Ex3 import javax.swing.*; public class dealer { static JFrame f; static JPanel p; JLabel ldname,ldadd,ldpno,ldser; JTextField tdname, tdpno; JTextArea tdadd; JList ser; JButton b1,b2;

76

dealer() { p=new JPanel(); f.getContentPane().add(p); ldname=new JLabel("Dealer Name"); ldadd=new JLabel("Dealer Add"); ldpno=new JLabel ("Dealer Phone no"); ldser=new JLabel ("Dealer Services"); tdname=new JTextField(20); tdadd=new JTextArea(10,5); tdpno=new JTextField(10); String str[]={"Free Service charges","Gifts fro mobile bought","10% discount on new mobile bought"}; ser=new JList(str); b1=new JButton("Submit"); b2=new JButton("Reset"); p.add(ldname); p.add(tdname); p.add(ldadd); p.add(tdadd); p.add(ldpno); p.add(tdpno); p.add(ldser); p.add(ser); p.add(b1); p.add(b2); } public static void main(String []args) { f=new JFrame("Dealer Details Form"); dealer obj=new dealer(); f.setVisible(true); f.setSize(300,300); } } Ex4:Password Field in awt. import java.awt.*; class PasswordDemo

77

{ Frame fr; Panel pn; Label l1; TextField t1; public PasswordDemo() { fr=new Frame("Test Form"); pn=new Panel(); fr.add(pn); l1=new Label("Password"); t1=new TextField(10); t1.setEchoChar('*'); pn.add(l1); pn.add(t1); fr.setSize(400,300); fr.setVisible(true); } public static void main(String[] args) { PasswordDemo p=new PasswordDemo(); } } Ex5: import javax.swing.*; class PasswordDemo1 { JFrame fr; JPanel pn; JLabel l1; JPasswordField t1; public PasswordDemo1() { fr=new JFrame("Test Form"); pn=new JPanel(); fr.getContentPane().add(pn); l1=new JLabel("Password"); t1=new JPasswordField(10);//default //t1.setEchoChar('*'); pn.add(l1); pn.add(t1); .

78

fr.setSize(400,300); fr.setVisible(true); } public static void main(String[] args) { PasswordDemo1 p=new PasswordDemo1(); } } Add controls to Frame import java.awt.*; class Demo extends Frame { Button b1; public Demo(String str) { super(str); setLayout(new FlowLayout()); b1=new Button("Submit"); add(b1); } public static void main(String[] args) { Demo d=new Demo("Demo frame"); d.setSize(400,300); d.setVisible(true); } } Ex6 import java.awt.*; class Demo extends Frame { Button b1,b2; public Demo(String str) { super(str); //setLayout(new FlowLayout()); b1=new Button("Submit"); b2=new Button("Cancel"); //add(b1) //add(b2)//overlapped with submit btton add(b1,"North"); add(b2,"South"); }

79

public static void main(String[] args) { Demo d=new Demo("Demo frame"); d.setSize(400,300); d.setVisible(true); } } Applets demo Demo.java import javax.swing.*; public class Demo extends JApplet { JPanel pn; JButton b1; public void init() { pn=new JPanel(); getContentPane().add(pn); b1=new JButton("submit"); pn.add(b1); } } aa.html <HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <applet code="Demo.class" height=300 width=300></applet> </BODY> </HTML> Javac Demo.java Appletviewer aa.html Another applet demo import javax.swing.*; public class Demo extends JApplet {

80

JPanel pn; JButton b1; public void init() { pn=new JPanel(); getContentPane().add(pn); b1=new JButton("submit"); pn.add(b1); } } //<applet code="Demo.class" height=300 width=300></applet> Javac Demo.java Appletviewer Demo.java FlowLayout //<applet code="flow.class" height=300 width=300></applet> import javax.swing.*; import java.awt.*; public class flow extends JApplet { JPanel p; JButton b1,b2,b3,b4; FlowLayout fl; public void init() { p=new JPanel(); getContentPane().add(p); fl=new FlowLayout(); p.setLayout(fl); b1=new b2=new b3=new b4=new JButton("Button JButton("Button JButton("Button JButton("Button 1"); 2"); 3"); 4");

p.add(b1);

81

p.add(b2); p.add(b3); p.add(b4); } } Border layout //<applet code="border.class" height=300 width=300></applet> import javax.swing.*; import java.awt.*; public class border extends JApplet { JPanel p; JButton b1,b2,b3,b4,b5; BorderLayout bl; public void init() { p=new JPanel(); getContentPane().add(p); //bl=new BorderLayout(); bl=new BorderLayout(10,20); p.setLayout(bl); b1=new JButton("Button 1"); b2=new JButton("Button 2"); b3=new JButton("Button 3"); b4=new JButton("Button 4"); b5=new JButton("Button 5"); p.add("East",b1); p.add("West",b2); p.add("North",b3); p.add("South",b4); p.add(b5,BorderLayout.CENTER); } } GridLayout //<applet code="grid.class" height=300 width=300></applet> import javax.swing.*; import java.awt.*; public class grid extends JApplet

82

{ JPanel p; JButton b1,b2,b3,b4,b5,b6; GridLayout gl; public void init() { p=new JPanel(); getContentPane().add(p); gl=new GridLayout(2,3,8,20); p.setLayout(gl); b1=new JButton("Button 1"); b2=new JButton("Button 2"); b3=new JButton("Button 3"); b4=new JButton("Button 4"); b5=new JButton("Button 5"); b6=new JButton("Button 6"); p.add(b1); p.add(b2); p.add(b3); p.add(b4); p.add(b5); p.add(b6); } } GridBag Layout //<applet code="gridbag.class" height=300 width=300></applet> import javax.swing.*; import java.awt.*; public class gridbag extends JApplet { JPanel p; JButton b1,b2,b3,b4,b5,b6; GridBagLayout gbl; GridBagConstraints gbc; public void init() { p=new JPanel(); getContentPane().add(p);

83

gbl=new GridBagLayout(); gbc=new GridBagConstraints(); p.setLayout(gbl); b1=new b2=new b3=new b4=new b5=new b6=new JButton("Button JButton("Button JButton("Button JButton("Button JButton("Button JButton("Button 1"); 2"); 3"); 4"); 5"); 6");

gbc.fill=GridBagConstraints.BOTH; gbc.anchor=GridBagConstraints.CENTER; gbc.gridx=1; gbc.gridy=1; gbc.gridheight=1; gbc.gridwidth=1; gbl.setConstraints(b1,gbc); p.add(b1); gbc.gridx=1; gbc.gridy=3; gbc.gridheight=1; gbc.gridwidth=1; gbl.setConstraints(b2,gbc); p.add(b2); gbc.gridx=2; gbc.gridy=1; gbc.gridheight=3; gbc.gridwidth=1; gbl.setConstraints(b3,gbc); p.add(b3); gbc.gridx=3; gbc.gridy=1; gbc.gridheight=1; gbc.gridwidth=1; gbl.setConstraints(b4,gbc); p.add(b4);

84

gbc.gridx=3; gbc.gridy=3; gbc.gridheight=1; gbc.gridwidth=1; gbl.setConstraints(b5,gbc); p.add(b5); gbc.gridx=4; gbc.gridy=1; gbc.gridheight=3; gbc.gridwidth=1; gbl.setConstraints(b6,gbc); p.add(b6); } } Card layout //<applet code="card.class" height=300 width=300></applet> import javax.swing.*; import java.awt.*; import java.awt.event.*; public class card extends JApplet implements ActionListener { JPanel p,p1,p2,p3; JButton b1,b2,b3; CardLayout cl; public void init() { p=new JPanel(); p1=new JPanel(); p1.setBackground(Color.red); p2=new JPanel(); p2.setBackground(Color.blue); p3=new JPanel(); p3.setBackground(Color.yellow); getContentPane().add(p); cl=new CardLayout(); p.setLayout(cl); p.add("Card1",p1);

85

p.add("Card2",p2); p.add("Card3",p3); b1=new JButton("1"); b2=new JButton("2"); b3=new JButton("3"); p1.add(b1); p2.add(b2); p3.add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent evt) { if(evt.getSource()==b1) { cl.next(p); } if(evt.getSource()==b2) { cl.next(p); } if(evt.getSource()==b3) { cl.next(p); } } } Tabbed Panels import javax.swing.*; import java.awt.*; class demo { JFrame fr; JPanel p1,p2,p3;

86

JTabbedPane tb; JButton b1,b2,b3; public demo() { fr=new JFrame("my window"); tb=new JTabbedPane(); fr.getContentPane().add(tb); b1=new JButton("Button1"); b2=new JButton("Button2"); b3=new JButton("Button3"); p1=new JPanel(); p1.setBackground(Color.red); p1.add(b1); p2=new JPanel(); p2.setBackground(Color.blue); p2.add(b2); p3=new JPanel(); p3.setBackground(Color.yellow); p3.add(b3); tb.addTab("First panel",null,p1,"this is first panel"); tb.addTab("Second panel",null,p2,"this is Second panel"); tb.addTab("Third panel",null,p3,"this is Third panel"); fr.setSize(300,300); fr.setVisible(true); } } class demoTabbedPane { public static void main(String[] args) { demo dm=new demo(); } } Ex4 import java.awt.*;

87

public class TestColor { public static void main(String[] args) { TestColor tester = new TestColor(); tester.launchFrame(); } TestColor() {} private void launchFrame() { Frame f = new Frame(); Button b = new Button("Purple"); Color purple = new Color(255, 0, 255); b.setBackground(purple); f.add(b); f.pack(); f.setVisible(true); } } Ex5 import java.awt.*; class GWindow extends Frame { public void paint(Graphics g) { g.drawLine(0,0,50,50); g.fillOval(5,20,300,30); g.setColor(Color.green); g.drawString("Hello",100,40); g.drawLine(120,40,20,100); g.drawLine(120,40,220,100); g.drawRect(20,100,200,180); int x[] ={100,140,170,140,100,60,100}; int y[]={150,150,200,250,250,200,150}; int n=7; g.drawPolygon(x,y,n); } } public class ShowGWindow { public static void main(String[] arg) { GWindow w = new GWindow(); w.setSize(350,60); w.setTitle("GWindow"); w.setVisible(true); }

88

} Ex6 import java.awt.*; import java.applet.*; public class drawhouse extends Applet { public void paint(Graphics g) { g.drawLine(120,40,20,100); g.drawLine(120,40,220,100); g.drawRect(20,100,200,180); int x[] ={100,140,170,140,100,60,100}; int y[]={150,150,200,250,250,200,150}; int n=7; g.drawPolygon(x,y,n); } /*<APPLET CODE="drawhouse.class" HEIGHT=300 WIDTH=300></APPLET>*/ } Lesson11:Events import java.awt.*; import java.awt.event.*; class TestButton { Frame fr; Panel pn; Button b1; public TestButton() { fr=new Frame("Niit"); pn=new Panel(); fr.add(pn); b1=new Button("Submit"); pn.add(b1); fr.setSize(300,300); fr.setVisible(true); //register the listener class listerner l=new listerner(); b1.addActionListener(l); }

89

public static void main(String[] args) { TestButton t=new TestButton(); } } class listerner implements ActionListener { public void actionPerformed(ActionEvent e) { Button b2=(Button)e.getSource(); b2.setLabel("Hello"); } } Ex2 import java.awt.*; import java.awt.event.*; class TestButton1 { Frame fr; Panel pn; Button b1; public TestButton1() { fr=new Frame("Niit"); pn=new Panel(); fr.add(pn); b1=new Button("Submit"); b1.setActionCommand("Pressed"); pn.add(b1); fr.setSize(300,300); fr.setVisible(true); //register the listener class listerner l=new listerner(); b1.addActionListener(l); } public static void main(String[] args) { TestButton1 t=new TestButton1(); }

90

} class listerner implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); System.out.println(e.getModifiers()); } } Ex3 import java.awt.*; import java.awt.event.*; class TestButton2 implements ActionListener { Frame fr; Panel pn; Button b1; Label l1; public TestButton2() { fr=new Frame("Niit"); pn=new Panel(); fr.add(pn); b1=new Button("Submit"); l1=new Label("label"); pn.add(b1); pn.add(l1); fr.setSize(300,300); fr.setVisible(true); //register the listener class b1.addActionListener(this); } public void actionPerformed(ActionEvent e) { //Button b2=(Button)e.getSource(); //b2.setLabel("Hello"); l1.setText("hello"); } public static void main(String[] args) { TestButton2 t=new TestButton2();

91

} } Ex4:Adapter class import java.awt.*; import java.awt.event.*; public class TestAdapter1 extends MouseMotionAdapter { private Frame f; private TextField tf; public TestAdapter1() { f = new Frame("Two listeners example"); tf = new TextField(30); } public void launchFrame() { Label label = new Label("Click and drag the mouse"); f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); f.addMouseMotionListener(this); f.setSize(300, 200); f.setVisible(true); } public void mouseDragged(MouseEvent e) { String s = "The mouse clicked x= "+e.getX() + " Y = " + e.getY(); tf.setText(s); } public static void main(String args[]) { TestAdapter1 two = new TestAdapter1(); two.launchFrame(); } } Ex5:Inner class Inner class can access the private member of Outer class import java.awt.*;

92

import java.awt.event.*; public class TestInner //outer { private Frame f; private TextField tf; public TestInner() { f = new Frame("Two listeners example"); tf = new TextField(30); } class Inner extends MouseAdapter//Inner { public void mouseClicked(MouseEvent e) { String s = "The mouse clicked "+e.getX() + " Y = " + e.getY(); tf.setText(s); } }; public void launchFrame() { Label label = new Label("Click the mouse"); // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add this object as a listener f.addMouseListener(new Inner() ); // Size the frame and make it visible f.setSize(300, 200); f.setVisible(true); }

x=

93

public static void main(String args[]) { TestInner two = new TestInner(); two.launchFrame(); } } Ex6:Anonymous Class Compile Time generates the TestAdapter$1.class import java.awt.*; import java.awt.event.*; public class TestAdapter //outer { private Frame f; private TextField tf; public TestAdapter() { f = new Frame("Two listeners example"); tf = new TextField(30); } public void launchFrame() { Label label = new Label("Click the mouse"); // Add components to the frame f.add(label, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); // Add this object as a listener f.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { String s = "The mouse clicked x= "+e.getX() + " Y = " + e.getY(); tf.setText(s); } } ); // Size the frame and make it visible f.setSize(300, 200);

94

f.setVisible(true); }

public static void main(String args[]) { TestAdapter two = new TestAdapter(); two.launchFrame(); } } Create table in GUI //<applet code="table.class" height=300 width=300></applet> import java.awt.*; import javax.swing.*; public class table extends JApplet { JPanel p; JTable t; String heading[]={"Film Name","Rating"}; String content[][]={ {"Rush Hour","1"}, {"Golden Eye","2"}, {"You have got mail","3"}, {"Nice Guy","4"} }; public void init() { p=new JPanel(); getContentPane().add(p); p.setLayout(new GridLayout(2,1)); t=new JTable(content,heading); t.setGridColor(Color.red); t.setBackground(Color.yellow); t.setForeground(Color.black); JScrollPane jsp=new JScrollPane(t,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

95

p.add(jsp); } } Lesson 12 : MENUS Create the menus in GUI //<applet code="table.class" height=300 width=300></applet> import java.awt.*; import javax.swing.*; public class table extends JApplet { JPanel p; JTable t; String heading[]={"Film Name","Rating"}; String content[][]={ {"Rush Hour","1"}, {"Golden Eye","2"}, {"You have got mail","3"}, {"Nice Guy","4"} }; public void init() { p=new JPanel(); getContentPane().add(p); p.setLayout(new GridLayout(2,1)); t=new JTable(content,heading); t.setGridColor(Color.red); t.setBackground(Color.yellow); t.setForeground(Color.black); JScrollPane jsp=new JScrollPane(t,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); p.add(jsp); } }

96

Lesson 13 :Thread class Demo extends Thread { public void run()//overriden { } public static void main(String[] args) { System.out.println("Hello World!"); } } class Demo implements Runnable { public void run()//interface method implemented { } public static void main(String[] args) { System.out.println("Hello World!"); } } Book Reference Ex1:single Thread class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { System.out.println("Hello"+i++); if(i==15) break; } } } class ThreadTester { public static void main(String[] args)

97

{ System.out.println("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h);//create//Non runnable t1.start();//runnable System.out.println("Main ended"); } }

Ex2:Multiple Threads class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { System.out.println("Hello"+i++); if(i==5) break; } } } class ThreadTester { public static void main(String[] args) { System.out.println("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); t1.start();//runnable t2.start(); System.out.println("Main ended"); }

98

Ex3:Sleep() class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { System.out.println("Hello"+i++); if(i==5) break; } } } class ThreadTester { public static void main(String[] args) { System.out.println("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); t1.start();//runnable t2.start(); try { Thread.sleep(2000);//it comes only inside try ,otherwise compile time error. } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("Main ended"); }

99

class newThreadClass implements Runnable { String ThreadName; newThreadClass(String name) { ThreadName = name; Thread t = new Thread(this, ThreadName); System.out.println("Thread created: " + t); t.start(); } public void run() { for(int i=1;i<=5;i++) { System.out.println(ThreadName + "loop :" + i); } System.out.println(ThreadName + "is exiting"); } } class MultipleThread { public static void main(String args[]) { new newThreadClass("FirstChildThread"); //Creating first Thread new newThreadClass("SecondChildThread"); //Creating second Thread for(int i=1;i<=5;i++) { System.out.println("Main Thread loop:" + i);

100

} System.out.println("Main Thread is terminating now"); } } Ex4:sleep() class HelloRunner implements Runnable { int i; public void run() { for(int i=0;i<3;i++) { System.out.println("Thread "+Thread.currentThread().getName()); System.out.println("Hello"+i); try { Thread.sleep(2000); } catch(InterruptedException e) { e.printStackTrace(); } } } } class ThreadTester { public static void main(String[] args) { System.out.println("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); t1.setName("T1"); t2.setName("T2"); t1.start(); t2.start(); System.out.println("Main ended"); }

101

Ex5: sleep() class PrintMe implements Runnable { public void run() { for(int x = 0; x < 3; x++) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(2000); } catch(Exception e) {} } } } public class TestThreeThreads { public static void main(String[] args) { Runnable prog = new PrintMe(); Thread t1 = new Thread(prog); Thread t2 = new Thread(prog); Thread t3 = new Thread(prog); t1.setName("T1 - Larry"); t2.setName("T2 - Curly"); t3.setName("T3 - Moe"); t1.start(); t2.start(); t3.start(); } }

102

Start(),join(),stop() is not static Thread t1=new Thread(r); T1.Start(); Sleep() is static Thread.Sleep(); Terminating a thread class HelloRunner implements Runnable { int i; public void run() { for(int i=0;i<5;i++) { System.out.println("Thread "+Thread.currentThread().getName()); System.out.println("Hello"+i); try { Thread.sleep(200); } catch(InterruptedException e) { e.printStackTrace(); } } } } class ThreadTester { public static void main(String[] args) { System.out.println("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); t1.setName("T1"); t1.start(); try

103

{ Thread.sleep(500); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println("Main is going to abort"); t1.stop(); System.out.println("Main ended"); } }

isAliveDemo class newThreadClass implements Runnable { public void run() { try { for(int i=1;i<=5;i++) { System.out.println(" child loop :" + i); Thread.sleep(100); } } catch( InterruptedException obj) { System.out.println("Thread :" + obj + "interrupted"); } } } class isAliveDemo { public static void main(String args[]) { newThreadClass obj = new newThreadClass(); Thread t= new Thread(obj,"ChildThread" );

104

System.out.println("Thread created: " + t); t.start(); System.out.println(t.getName() + " is alive ? : " + t.isAlive()); try { for(int i=1;i<=5;i++) { System.out.println("Main Thread loop:" + i); Thread.sleep(200); } } catch(InterruptedException e) { System.out.println("Main thread is interrupted");} System.out.println(t .getName() + "is alive ? : " + t.isAlive()); System.out.println("Main Thread is exiting"); } }

Priority Demo class ChildThread implements Runnable { public void run() { try { for(int i=1;i<=5;i++) { System.out.println("loop :" + i); Thread.sleep(500); } } catch( InterruptedException obj) { System.out.println("Thread :" + obj + "interrupted");}

105

} } class PriorityDemo { public static void main(String args[]) { ChildThread obj1 = new ChildThread(); Thread t1= new Thread(obj1,"ChildThread1" ); Thread t2= new Thread(obj1,"ChildThread2" ); Thread t3= new Thread(obj1,"ChildThread3" ); t1.setPriority(Thread.NORM_PRIORITY - 2); t2.setPriority(Thread.NORM_PRIORITY + 2); t3.setPriority(Thread.NORM_PRIORITY +3); System.out.println("Thread created: " + t1); System.out.println("Thread created: " + t2); System.out.println("Thread created: " + t3); System.out.println("Child thread1 Priority "+t1.getPriority() ); System.out.println("Child thread2 Priority "+t2.getPriority() ); System.out.println("Child thread3 Priority "+t3.getPriority() ); System.out.println("Main Thread is exiting"); } }

Another Demo for Priority class ChildThread implements Runnable { Thread t; ChildThread(int p) { t = new Thread(this,"ChildThread" ); t.setPriority(p); System.out.println("Thread created: " + t); } public void run() { try

106

{ for(int i=1;i<=5;i++) { System.out.println(t+"loop :" + i); Thread.sleep(100); } } catch( InterruptedException obj) { System.out.println("Thread :" + t + "interrupted");} } } class PriorityDemo { public static void main(String args[]) { System.out.println("Main thread is started"); ChildThread obj1 = new ChildThread(Thread.MIN_PRIORITY); ChildThread obj2 = new ChildThread(Thread.MAX_PRIORITY); obj1.t.start(); obj2.t.start();

System.out.println("Main Thread is exiting"); } }

Join Demo Join method causes the current thread to wait until thread on which join method is called terminates. class ChildThread implements Runnable {

107

Thread t; ChildThread(int p) { t = new Thread(this,"ChildThread" ); t.setPriority(p); System.out.println("Thread created: " + t); } public void run() { try { for(int i=1;i<=5;i++) { System.out.println(t+"loop :" + i); Thread.sleep(100); } } catch( InterruptedException obj) { System.out.println("Thread :" + obj + "interrupted");} } } class PriorityDemo { public static void main(String args[]) { System.out.println("Main thread is started"); ChildThread obj1 = new ChildThread(Thread.MIN_PRIORITY+2); ChildThread obj2 = new ChildThread(Thread.MAX_PRIORITY-2); obj1.t.start(); obj2.t.start(); try { obj1.t.join(); //obj2.t.join(); } catch( InterruptedException obj) { System.out.println("Thread :" + obj + "interrupted"); } for(int i=1;i<=5;i++) {

108

System.out.println("main loop :" + i); }

System.out.println("Main Thread is exiting"); } }

Yield Demo Thread .Yield to give other runnable threads a chance o execute. class ChildThread implements Runnable { Thread t; ChildThread(String tname) { t = new Thread(this,tname); System.out.println("Thread created: " + t); } public void run() { for(int i=1;i<=5;i++) { System.out.println(t+" loop :" + i); if(i==3) t.yield(); } } }

109

class yieldDemo { public static void main(String args[]) { System.out.println("Main thread is started"); ChildThread obj1 = new ChildThread("T1"); ChildThread obj2 = new ChildThread("T2"); obj1.t.start(); obj2.t.start();

System.out.println("Main Thread is exiting"); } }

Not synchronized Demo class Thread1 { void call() { System.out.println("first statement"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("Error " + e); } System.out.println("second statement"); } } class Thread2 extends Thread {

110

Thread1 t; public Thread2(Thread1 t) { this.t = t; } public void run() { t.call(); } } public class NotSynchronized { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 Obja = new Thread2(obj1); Thread2 Objb = new Thread2(obj1); Obja.start(); Objb.start(); } }

Synchronized Block class Thread1 { void call() { System.out.println("first statement"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("Error " + e); } System.out.println("second statement"); } } class Thread2 extends Thread { Thread1 t;

111

public Thread2(Thread1 t) { this.t = t; } public void run() { synchronized(t) { t.call(); } } } public class SynchronizedBlock { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 obja = new Thread2(obj1); Thread2 objb = new Thread2(obj1); obja.start(); objb.start(); } }

Synchronized threads class Thread1 { synchronized void call() { System.out.println("first statement"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("Error " + e); } System.out.println("second statement"); } }

112

class Thread2 extends Thread { Thread1 t; public Thread2(Thread1 t) { this.t = t; } public void run() { t.call(); } } public class SynchronizedThreads { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 Obja = new Thread2(obj1); Thread2 Objb = new Thread2(obj1); Obja.start(); Objb.start(); } }

Producer consumer demo class Thread1 { int d; synchronized void getData() { System.out.println("Got data:" + d); } synchronized void putData(int d) { this.d = d; System.out.println("Put data:" + d);

113

} } class producer extends Thread { Thread1 t; public producer(Thread1 t) { this.t = t; } public void run() { int data =700; for(int i=0; i<5 ;i++) { System.out.println("Put Called by producer"); t.putData(data++); } } } class consumer extends Thread { Thread1 t; public consumer(Thread1 t) { this.t = t; } public void run() { for(int i=0; i<5 ;i++) { System.out.println("Get Called by consumer"); t.getData(); } } } public class ProducerConsumer { public static void main(String args[]) { Thread1 obj1 = new Thread1(); producer p = new producer(obj1); consumer c = new consumer(obj1); p.start(); c.start(); }

114

Wait and Notify (Inter Thread communication) class Thread1 { int d; boolean flag = false; synchronized int getData() { if(flag==false) { try { wait(); } catch(InterruptedException e) { System.out.println(" Exception caught"); } } System.out.println("Got data:" + d); flag=false; notify(); return d; } synchronized void putData(int d) { if(flag==true ) { try { wait();

115

} catch(InterruptedException e) { System.out.println(" Exception caught"); } } this.d = d; System.out.println("Put data with value:" + d); flag=true; notify(); } } class producer implements Runnable { Thread1 t; public producer(Thread1 t) { this.t = t; new Thread(this,"Producer").start(); System.out.println("Put Called by producer"); } public void run() { int data =10; for(int i=0; i<5 ;i++) { data=data+1; t.putData(data); } } } class consumer implements Runnable { Thread1 t; public consumer(Thread1 t) { this.t = t; new Thread(this,"Consumer").start(); System.out.println("Get Called by consumer"); } public void run() {

116

for(int i=0; i<5 ;i++) { t.getData(); } } } public class InterThreadComm { public static void main(String args[]) { Thread1 obj1 = new Thread1(); producer p = new producer(obj1); consumer c = new consumer(obj1); } }

Extra reference in threads Ex1: extends Thread(single Thread) class HelloRunner extends Thread { Thread t; public HelloRunner() { t = new Thread(this,"child Thread"); System.out.println("Child Thread:" + t); t.start(); } int i; public void run()

117

{ i=1; while(true) { System.out.println("Hello"+i++); if(i==15) break; } } } class ThreadTester { public static void main(String[] args) { System.out.println("Main started"); HelloRunner h=new HelloRunner(); System.out.println("Main ended"); } }

Ex2: extends Thread(Another way) class ThreadDemo extends Thread { ThreadDemo() { super("ChildThread"); // calls the superclass constructor System.out.println("ChildThread:" + this); start(); } public void run() { System.out.println("The child thread started"); System.out.println("Exiting the child thread"); }

118

} class ThreadDemoClass { public static void main(String args[]) { new ThreadDemo(); System.out.println("The main thread started"); System.out.println("The main thread sleeping"); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("The main thread interrupted"); } System.out.println("Exiting main thread"); } }

EX3:Multiple threads another way class newThreadClass implements Runnable { String ThreadName; newThreadClass(String name) { ThreadName = name; Thread t = new Thread(this, ThreadName); System.out.println("Thread created: " + t); t.start(); } public void run() { try { for(int i=1;i<=5;i++) { System.out.println(ThreadName + "loop :" + i); Thread.sleep(100); }

119

} catch( InterruptedException obj) { System.out.println("Thread :" + ThreadName + "interrupted"); } System.out.println(ThreadName + "is exiting"); } } class MultipleThread { public static void main(String args[]) { new newThreadClass("FirstChildThread"); //Creating first Thread new newThreadClass("SecondChildThread"); //Creating second Thread try { for(int i=1;i<=5;i++) { System.out.println("Main Thread loop:" + i); Thread.sleep(300); } } catch(InterruptedException obj) { System.out.println("Main thread is interrupted"); } System.out.println("Main Thread is terminating now"); } }

120

Ex4: Main contains Thread coding class mainThreadDemo { public static void main(String args[]) { Thread t= Thread.currentThread(); System.out.println(" The current thread: " + t); t.setName("MainThread"); System.out.println(" The current thread after name change : " + t); System.out.println(" The current Thread is going to sleep for 10 seconds"); try{ t.sleep(10000); } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println(" After 10 seconds...........the current Thread is exiting now."); } }

Application Applet ---using thread import javax.swing.*; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar;

121

public class ApplicantApplet extends JApplet implements Runnable { /* Declare panels */ static JPanel panel; /* Declare labels */ JLabel labelAppId; JLabel labelAppName; JLabel labelAppPosition; /* Declare TextArea */ JTextField textAppID; JTextField textAppName; JComboBox comboAppPosition; /* Declare a Thread variable */ Thread datimeThread; /* Declare a Date variable */ Date date; /* Declare a GregorianCalendar variable */ GregorianCalendar calendar; /* Declare String variables to store date time and status bar messages. */ String strDate, strTime, strStatus; /* init method of applet */ public void init() { panel = new JPanel(); getContentPane().add(panel); labelAppId = new JLabel("Applicant ID"); labelAppName = new JLabel("Applicant Name"); labelAppPosition = new JLabel("Position"); textAppID = new JTextField(5); textAppName = new JTextField(5); String positions[] = {"Manager", "Executive", "Associate"}; comboAppPosition = new JComboBox(positions); panel.add(labelAppId); panel.add(textAppID);

122

panel.add(labelAppName); panel.add(textAppName); panel.add(labelAppPosition); panel.add(comboAppPosition); dateTime(); } public void dateTime() { /* Initialize thread */ datimeThread = new Thread(this); /* Starting thread */ datimeThread.start(); } public void run() /* body of the thread */ { while(datimeThread != null) { display();// This method displays date try { datimeThread.sleep(1000); } catch(InterruptedException e) { showStatus("Thread interrupted"); } } /*end of while loop */ } /* end of run method */ /* displays date and time on the status bar */ public void display() { date = new Date(); calendar = new GregorianCalendar(); calendar.setTime(date); strTime = calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUT E)+":"+calendar.get(Calendar.SECOND);

123

strDate = (calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar. DATE)+"/"+calendar.get(Calendar.YEAR); strStatus=strTime+" "+strDate; showStatus(strStatus); } }/* end of program */ aa.html <HTML> <HEAD> <TITLE> Applicant Applet </TITLE> </HEAD> <BODY> <APPLET ALIGN = center CODE= "ApplicantApplet.class" WIDTH = 100 HEIGHT = 0> </APPLET> </BODY> </HTML> Lesson15:Networking Client is sending message , server is reading Client programgetOutputStream() Server Program getInputStream() AppServer.java import java.io.*; import java.net.*; public class AppServer extends Thread { ServerSocket serverSocket; Thread th; public AppServer() { try { System.out.println("Server is going to start . . ."); serverSocket = new ServerSocket(1800); System.out.println("Server config at port no 1800. . ."); System.out.println("Server started . . ."); th=new Thread(this); this.start(); // Starts the thread

124

} catch(IOException e) { System.out.println("Error..."+ e); } } public void run() { try { while(true) { System.out.println("Wating for client request...."); Socket client = serverSocket.accept(); ObjectInputStream fromClient = new ObjectInputStream(client.getInputStream()); String clientMessage = (String)fromClient.readObject(); System.out.println("Received from:"+clientMessage); } } catch(Exception e) { System.out.println("Error..."+ e); } }//run close public static void main(String args[]) { new AppServer(); } } Myclient.java import java.io.*; import java.net.*; public class myClient { public static void main(String[] args) { String str=args[0];

125

try { Socket sc=new Socket("172.45.56.101",1800); ObjectOutputStream toServer = new ObjectOutputStream(sc.getOutputStream()); toServer.writeObject((String)str); toServer.close(); System.out.println("Message Send"); } catch (Exception ex) { System.out.println("Error..."); } } } Java myclient John Server is writing and client is reading that Server Program getOutputStream() Client programgetInputStream() Appserver1.java import java.io.*; import java.net.*; public class AppServer1 { ServerSocket serverSocket; public AppServer1() { try { System.out.println("Server is going to start . . ."); serverSocket = new ServerSocket(1800); System.out.println("Server config at port no 1800. . ."); System.out.println("Server started . . ."); } catch(IOException e) { System.out.println("Error..."+ e); }

126

} public void send() { try { while(true) { System.out.println("Wating for client request...."); Socket client = serverSocket.accept(); OutputStream fromClient = client.getOutputStream(); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fromClient)); bw.write("Hello niit\n"); bw.close(); client.close(); } } catch(Exception e) { System.out.println("Error..."+ e); } } public static void main(String args[]) { AppServer1 obj=new AppServer1(); obj.send(); } } myClient1.java import java.io.*; import java.net.*; public class myClient1 { public static void main(String[] args) { try { Socket sc=new Socket("172.45.56.101",1800);

127

InputStream

toServer = sc.getInputStream();

DataInputStream dis =new DataInputStream(toServer); System.out.println(dis.readLine()); sc.close(); dis.close(); } catch (ConnectException ex) { System.out.println("Error..."+ex); } catch (Exception ex) { System.out.println("Error. is a .."+ex); } } }

Você também pode gostar