Student Class Implementation Guide
Student Class Implementation Guide
Lesson 1:Getting Started Ex1 [Link] class Greeting { public static void main(String[] args) { [Link]("Hello World!"); } } [Link] class TestGreeting { public static void main(String[] args) { Greeting g=new Greeting(); [Link](); } } Lesson 2 :Object Oriented Programming Ex:1 [Link] 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
[Link] class TestDog { public static void main(String[] args) { Dog d=new Dog(); [Link](-30); [Link]([Link]()); [Link](10); [Link]([Link]()); [Link](-14); [Link]([Link]()); [Link](20); [Link]([Link]()); [Link](-11); [Link]([Link]()); } } Ex2: creating Packages [Link] package zoo; public class Dog { private int weight; public Dog() { weight = 42; } public int getWeight() { return weight; } public void setWeight(int newWeight) { weight = newWeight; } }
[Link] import [Link]; public class Test { public static void main(String[] args) { Dog d = new Dog(); [Link](30); [Link]("The dog has a weight of " + [Link]()); } } //javac -d E:\prabha \demo [Link] //javac [Link] //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) { [Link]("Hello World!"); } } //javadoc [Link] Ex4:Creating JAR file(executable files) [Link] Main-Class: Test Hint:you should press the enter key after the Test. [Link] class Test { public static void main(String[] args) { [Link]("Hello World!"); } } //javac [Link] //jar -cvfm [Link] [Link] [Link] //java -jar [Link]
LESSON 3: Identifiers,keywords and Types EX1:Passbyvalue class Passbyvalue { public void increment(int y) { y++; [Link]("y is "+y); } public static void main(String[] args) { int x=10; Passbyvalue p=new Passbyvalue(); [Link]("X is "+x); [Link](x); [Link]("X is "+x); } } EX2:PassbyReference class PassbyRef { int a; PassbyRef() { a=10; } public void increment(PassbyRef y) { y.a++; [Link]("y is "+y.a); } public static void main(String[] args) { PassbyRef x=new PassbyRef(); PassbyRef p=new PassbyRef(); [Link]("X is "+x.a); [Link](x); [Link]("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) { [Link] = street; [Link] = city; [Link] = state; [Link] = 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" + [Link](); } } 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); [Link](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; [Link]("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 [Link] public class MyDate { private int day; private int month; private int year; public MyDate(int day, int month, int year) { [Link] = day; [Link] = month; [Link] = year; } public MyDate(MyDate date) { [Link] = [Link]; [Link] = [Link]; [Link] = [Link]; } public int getDay() { return day; } public void setDay(int day) { [Link] = 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; } }
[Link] 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; [Link](the_next_week); [Link](my_birth); [Link](anotherDate); } } Lesson 4: Expressions and Flow control Ex:Variable Scope class DemoScope { int x; static int y; public void display() { int a=10;//local [Link](a); } public static void main(String[] args) { DemoScope d=new DemoScope(); [Link](); } } 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 [Link]("The value of x is: " + x); [Link]("The value of y is: " + y); [Link]("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 [Link](a) ; } } BitWiseNOT class BitWiseNOT { public static void main(String arr[]) { int x=2; int a ; a = ~x; // Bit-wise NOT operator [Link]("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 [Link]("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
[Link]("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 [Link]("The value of x is:" + x); } else { x = 4<<2 - 10; [Link]("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 [Link]("The result of right shift operator is:"+b); [Link]("The result of left shift operator is:" +c); [Link]("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 [Link]("The value of variable a is:" + a); [Link]("The value of variable b is:" + b); [Link]("The value of variable c is:" + c); [Link]("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() { [Link]("Test #1 - while loop with block"); int i = 0; while ( i < 10 ) { [Link](i + " squared is " + (i*i)); i++; } } EX2 public class TestInitBeforeUse { public void doComputation() { int x = (int)([Link]() * 100); int y; int z; if (x > 50) { y = 9;
12
} z = y + x; // Possible use before initialization [Link](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 < [Link]; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { [Link]("Found " + searchfor + " at " + i + ", " + j); } else { [Link](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 = [Link]() - [Link](); test: for (int i = 0; i <= max; i++) { int n = [Link](); int j = i; int k = 0; while (n-- != 0) { if ([Link](j++) != [Link](k++)) { continue test; } } foundIt = true; break test; } [Link](foundIt ? "Found it" : "Didn't find it"); } }
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 < [Link]; i++ ) { [Link](array[i]); } } public static void main(String[] args) { char[] characters = createArray(); printArray(characters); [Link](); } } Simple Ref Array: class Customer { String name; String Address; public void display() { [Link]("Name is " +name); [Link]("Address is " +Address); } }; class CustomerDetails { Customer [] obj=new Customer[3];//create object array public CustomerDetails()
15
{ for(int i=0;i<[Link];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<[Link];i++) { obj[i].display(); } } public static void main(String[] args) { CustomerDetails c=new CustomerDetails(); [Link](); } } 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 < [Link]; i++ ) { [Link](" x is "+array[i].x+" is "+ array[i].y+"\n" ); } } public static void main(String[] args) { Point[] characters = createArray(); printArray(characters); [Link](); } } 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 ) { [Link](list +"\t"); } } public static void main(String[] args)
" +" y
17
{ int[] b = createArray(); printArray(b); [Link](); } } 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]; [Link]("[Link] = " + [Link]); [Link]("data[0].length = " + data[0].length); [Link]("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 < [Link]; 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
"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) { [Link]("Array " + tag + " is " + [Link] + " x " + array[0].length); [Link]("Array[0][0] = " + array[0][0]); [Link]("Array[0][1] = " + array[0][1]); [Link]("Array[1][0] = " + array[1][0]); [Link]("Array[0][0] = " + array[0][0]); [Link]("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() { [Link]("Base ---a1"); } }; class Child extends Base { public void a2() { [Link]("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() { [Link]("Base ---a1"); } }; class Child extends Base { public void a1() { [Link]("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() { [Link]("Base ---a1"); } }; class Child extends Base { public void a1() {
21
super.a1(); [Link]("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 ( [Link]()+" Department name :"+deptname); } }; class Test1 { public static void main(String [] s) {
22
Manager m=new Manager();//Parent construtor ,then child Constructor [Link]([Link]()); } }; Overriden methods can not be less Accessible. class Base { public void a1() { [Link]("Base ---a1"); } }; class Child extends Base { private void a1() { [Link]("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) { [Link]("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() { [Link]("Base ---a1"); } public void b() { [Link]("Base ---b"); } }; class Child extends Base { public void a2() { [Link]("child ---a2"); } public { } void b()
with
[Link]("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) { [Link]=day; [Link]=month; [Link]=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); [Link](obj[0]); [Link](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(); [Link](obj[0]); [Link](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= [Link] * 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(); [Link]([Link](m)); } }; Object class is the Parent for all classes class demo { public static void main(String[] args) { [Link]("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) [Link]("This is Manager"); else if(e instanceof Engineer) [Link]("This is Engineer"); else [Link]("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(); [Link](em); } }; Casting Objects need to access the functionality of sub classes [Link](implicit)(child-Parent) [Link](explicit)(Parent-child) [Link] to child type casting is not possible .(runtime error occurs) class Employee { public void a() { [Link]("Employee a()"); } }; class Manager extends Employee { public void b() { [Link]("Manager b()"); } }; class Engineer extends Employee { public void c() { [Link]("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(); [Link](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)/[Link]; } /*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(); [Link]([Link](10,20)); [Link]([Link](10,20,30)); [Link]([Link](10,20,30,40)); } }; Overloading Constructor class Date { int day; int month; int year;
31
public Date(int day, int month,int year) { [Link]=day; [Link]=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); [Link](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 [Link]()+"\ndept is :"+dept; } }; class Test { public static void main(String [] a) { Manager m=new Manager(); [Link](m); } }; Super() calls Parent Constructor class Employee { String Ename; double Salary; public Employee() { Ename="jack"; Salary=10000; } public Employee(String Ename,double Salary) { [Link]=Ename; [Link]=Salary; } public Employee(String Ename) {
33
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 [Link] it calls super() { deptname=dept; } public String getDetails() { return ( [Link]()+" 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"); [Link]([Link]()); } }; Object class has two functions([Link](), [Link]()) class MyDate {
34
int day; int month; int year; public MyDate(int day, int month,int year) { [Link]=day; [Link]=month; this .year=year; } public boolean equals(Object c) { boolean result =false; if((c !=null ) && (c instanceof MyDate)) { MyDate d=(MyDate) c; if((day==[Link])&& (month==[Link]) && (year==[Link])) { 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) { [Link]("Date1 is identical to date2"); } else { [Link]("Date1 is not identical to date2"); } if([Link](dat2))
35
{ [Link]("Date1 is identical to date2"); } else { [Link]("Date1 is not date2"); } [Link]("set Date2 = date1"); dat2=dat1; if(dat1==dat2) { [Link]("Date1 is identical to date2"); } else { [Link]("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(); [Link]([Link]()); FunctionStatic obj1=new FunctionStatic(); [Link]([Link]()); } } 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) { [Link](totalcount()); [Link](totalcount()); } } EX2:Static block class FunctionStatic { static int x; int y; static//called once when class is loaded { [Link](" static block called"); x=10; } public FunctionStatic ()// called when obj is called { [Link](" construtor called"); y=10; } public void display() { x++; y++;
37
[Link](" x is }
"+x+"
y is
" +y);
} class TestFunctionStatic { public static void main(String[] args) { FunctionStatic obj1=new FunctionStatic(); [Link](); FunctionStatic obj2=new FunctionStatic(); [Link](); FunctionStatic obj3=new FunctionStatic(); [Link](); } } EX3:Count Objects class CountObjs { // public static int count=0; private static int count=0; public CountObjs() { count++; [Link](count); } } public class TestCountObjs { public static void main(String[] args) { CountObjs cb=new CountObjs(); CountObjs cb1=new CountObjs(); CountObjs cb2=new CountObjs(); [Link]([Link]); [Link]([Link]); } } 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(); [Link]("value of counter="+[Link]); count c2= new count(); [Link]("value of counter="+[Link]); count c3=new count(); [Link]("value of counter="+[Link]); } public static void main(String[] args) { test obj=new test(); [Link](); } } Ex5:Static concept in Overridden method class count1 { public void some() { [Link]("count1-some function"); } public static void disp() { [Link]("count1"); } } class count2 extends count1 { public void some()
39
{ [Link]("count2 some function"); } public static void disp() { [Link]("count2"); } } public class TestCount { public static void main(String[] args) { count1 obj=new count2(); [Link](); //Some overridden function is non static //method is invoked for which class memory is allocated. count1 obj1=new count2(); [Link](); //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) { [Link]("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) { [Link]("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=[Link]; [Link](a); } } Old Enumerated Type package [Link]; 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) { [Link]=suit; [Link]=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: [Link]("Invalid suit"); } return name; } } import [Link]; class TestPlayingCard { public static void main(String[] args) {
42
PlayingCard card1=new PlayingCard(PlayingCard.SUIT_SPADES,2); [Link](" card1 is the "+[Link]()+" of "+ [Link]()); PlayingCard card2=new PlayingCard(47,2);//no proper output; [Link](" card1 is the "+[Link]()+" of "+ [Link]()); } }
New Enumerated Type Problem of old enumerated types:Type safety issues [Link] package [Link]; public enum Suit { SPADES,HEARTS,CLUBS,DIAMONDS } [Link] package [Link]; public class PlayingCard { private Suit suit; private int rank; public PlayingCard(Suit suit,int rank) { [Link]=suit; [Link]=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: [Link]("Invalid suit"); } return name; } } [Link] import [Link]; import [Link]; class TestPlayingCard { public static void main(String[] args) { PlayingCard card1=new PlayingCard([Link],2); [Link](" card1 is the "+[Link]()+" of "+ [Link]()); //PlayingCard card2=new PlayingCard(47,2);//it produces error. //[Link](" card1 is the "+[Link]()+" of "+ [Link]()); } } Advanced Enumerated Types [Link] package [Link]; 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 { [Link]=name; } public String getname() { return name; } } [Link] package [Link]; public class PlayingCard { private Suit suit; private int rank; public PlayingCard(Suit suit,int rank) { [Link]=suit; [Link]=rank; } public Suit getSuit() { return suit; } public int getRank() { return rank; } } [Link] import [Link]; import [Link]; class TestPlayingCard { public static void main(String[] args) { PlayingCard card1=new PlayingCard([Link],2); [Link](" card1 is the "+[Link]()+" of "+ [Link]().getname());
45
//PlayingCard card2=new PlayingCard(47,2);//it produces error. //[Link](" card1 is the "+[Link]()+" of "+ [Link]()); } } Static Imports [Link] package vehicle; public class car { public static void move() { [Link]("Hello wins the race"); } } [Link] import vehicle .car; class Testcar { public static void main(String[] args) { [Link](); } } Modifed into like following [Link] import static vehicle .car.*; class Testcar { public static void main(String[] args) { move(); } } Abstract class abstract class Shape { public void disp() { [Link]("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(); [Link](); [Link]([Link]()); rect r=new rect(); [Link]([Link]()); /*Shape s=new Shape(); //can not be instantiated [Link]();*/ } }; Interface demo1 interface I1 { //events,properties,methods public void a(); } class C1 implements I1 {
47
public void a() { [Link]("This is a of C1"); } } class { C2 implements I1 public void a() { [Link]("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() { [Link]("This is a of C1"); } public void b() { [Link]("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() { [Link]("This is a of C1"); } public void b() { [Link]("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() { [Link]("This is a of C1"); } public void b() { [Link]("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; [Link] ("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) { [Link]("Division by zero is performed"); } [Link]("The result=" + num3); } } Multiple catch with Exception class public class TryCatch { public void disp() { [Link]("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; [Link](num1 / array[1]); TryCatch c=null; [Link](); //more statements } catch(ArithmeticException e) { [Link]("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { [Link]("Error... Out of bounds"); } catch (Exception e) { [Link]("Some other error"); }
51
[Link]("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) { [Link]("Some other error"); } catch(ArithmeticException e) { [Link]("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { [Link]("Error... Out of bounds"); } [Link]("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 { [Link](); } catch(ArithmeticException obj) { //[Link](); [Link]("division by zero"); } } } Finally Block public class TryCatch { public static void main(String args[]) { int array[] = {10,20}; int num1; num1 = 100; try { [Link](num1 / array[1]); } catch(ArithmeticException e) { [Link]("Error... Division by zero"); } catch(ArrayIndexOutOfBoundsException e) { [Link]("Error... Out of bounds"); } finally { [Link]("Program ended"); } } } Throw keyword class ThrowClass
53
{ static void throwDemo()//called { try { throw new IllegalStateException("MyException"); } catch(IllegalStateException objA) { [Link]("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 { [Link]("In throwMethod"); //throw new ClassNotFoundException(); } public static void main(String args[]) { throwMethod();//compile error /*try { throwMethod(); } catch(ClassNotFoundException Obja) { [Link]("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; [Link]("Calculate Method(" + a + "," + b + ")"); sum=a+b; if(sum>20) { throw new UserException(); } [Link]("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) { [Link]("Caught:" + Obja); } } } Assertions public class AssertionDemo { static int balance=1500; public static int transaction(int amt)
55
{ balance =balance-amt; [Link]("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 [Link] //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 <[Link] ;i++ ) { [Link]( a[i]); } } } //javac [Link] //java Demo john jack System Properties
56
import [Link]; import [Link]; class TestProperties { public static void main(String[] args) { Properties props=[Link](); Enumeration pname=[Link](); while([Link]()) { String propName =(String)[Link](); String value=[Link](propName); [Link]("Property ' "+propName+"' is '"+value +"'"); } } } //javac [Link] //java TestProperties //java -DCustom=niit TestPropertiese Println and print class Demo { public static void main(String[] args) { [Link]("hello"); [Link]("h1 ");
57
[Link]("niit"); } } Reading from Standard input import [Link].*; class KeyBoardInput { public static void main(String[] args) { [Link]("Unix: type ctrl-d to exit."+"\nWindow: type ctrl -z to exit"); [Link]("Enter the input"); String s; InputStreamReader ir=new InputStreamReader([Link]); BufferedReader in=new BufferedReader( ir ); try { /*s=[Link](); while(s !=null) { [Link]("Read :"+s); s=[Link](); }*/ while((s=[Link]()) !=null) { [Link]("Read :"+s); } [Link](); } catch(Exception e) { [Link](); } } } 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 [Link]("Name ",name,age,salary); : %s %nAge : %d %nSalary
} } Scanner class for simple formatted input import [Link].*; import [Link]; public class ScanTest { public static void main(String[] args) { Scanner s = new Scanner([Link]); String param =[Link]();//for string input [Link]("the param1 " + param); int value = [Link]();// for Interger input [Link]("the param2 " + value); [Link](); } } Create File objects import [Link].*; class TestFile { public static void main(String[] args) { File f1=new File("c:\\[Link]"); [Link]([Link]()); } } Note: This will not create the physical file for us . It creates file only in Buffer memory Demo1
59
import [Link].*; class TestFile { public static void main(String[] args) { File f1=new File("c:\\[Link]"); try { BufferedWriter bw=new BufferedWriter(new FileWriter(f1)); } catch(Exception e) { [Link](); } [Link]([Link]()); } } Note: When we write the File object with FileWriter class , then only physical file will be created . Demo2 import [Link].*; class TestFile { public static void main(String[] args) { //File f1=new File("c:\\niit","[Link]"); File mydir=new File("C:\\niit"); File myfile=new File(mydir,"[Link]"); [Link]([Link]()); } } Demo 3
60
2)File object does not permit you to access the contents of the file. import [Link].*; class Files { public static void main(String args[])throws NullPointerException { String dirName = "C:/Test"; File f = new File(dirName, "[Link]"); File f3 = new File(dirName, "[Link]"); [Link]("File name is:" +[Link]()); [Link]("Path of the file is:" +[Link]()); [Link]("Parent directory is:" +[Link]()); [Link]("Listing the contents of directory"); File f1 = new File(dirName); String s[] = [Link](); for(int i = 0;i<[Link];i++) { File f2 = new File("\t" +dirName+ "/" +s[i]); if([Link]()) { [Link]("\t" +s[i] + "is a directory"); } else { [Link]("\t" +s[i] + "is a file"); } } } } Write into File import [Link].*; class FileOutput { public static void main(String[] args) { try { BufferedReader in=new BufferedReader( new InputStreamReader([Link])); PrintWriter fileout=new PrintWriter(new FileWriter(new File("c:\\[Link]")));
61
s=[Link](); while(s !=null) { [Link](s); s=[Link](); } [Link](); [Link](); } catch(Exception e) { [Link](); } } } Read from File import [Link].*; class FileInput { public static void main(String[] args) { try { BufferedReader filein=new BufferedReader(new FileReader(new File(args[0]))); String s; s=[Link](); while(s !=null) { [Link](s); s=[Link](); } [Link](); }
62
Set import [Link].*; public class SetExample { public static void main(String[] args) { Set set = new HashSet(); [Link]("one"); [Link]("second"); [Link]("3rd"); [Link]("new Integer(4)"); [Link]("new Float(5.0F)"); [Link]("second"); //Duplicate,not added//no error [Link]("new Integer(4)"); //Duplicate,not added [Link](set); } } List import [Link].*; public class ListExample {
63
public static void main(String[] args) { List list = new ArrayList(); [Link]("one"); [Link]("second"); [Link]("3rd"); [Link]("new Integer(4)"); [Link]("new Float(5.0F)"); [Link]("second"); //Duplicate,added [Link]("new Integer(4)"); //Duplicate, added [Link](list); } } Collections ,Problem:Warning,No Type Safety import [Link].*; public class GenericsWarning { public static void main(String[] args) { ArrayList list = new ArrayList(); [Link](0, new Integer(42)); int total = ((Integer)[Link](0)).intValue(); } } Generic Collections ---no warning , Type Safety import [Link].*; public class GenericsWarning { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); [Link](0, new Integer(42));//Explicit boxing int total = ([Link](0)).intValue();//Explicit unboxing [Link](total); } } Demo2 import [Link].*; public class GenericsWarning {
64
public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); [Link](0, 42);//Implicit boxing int total = [Link](0);//Implicit unboxing [Link](total); } } Iterator [Link] is the process of retrieving every element in the collection [Link] Interface(Iterator)--Child interface (ListIterator) [Link] is set of unordered . a)hasNext()---only forward scan [Link] a)hasNext()---forward scan b)hasPrevious()---backward scan Forward Scan import [Link].*; public class IteratorExample { public static void main(String[] args) { List list = new ArrayList(); [Link]("one"); [Link]("second"); [Link]("3rd"); [Link]("new Integer(4)"); [Link]("new Float(5.0F)"); [Link]("second"); //Duplicate,added [Link]("new Integer(4)"); Iterator e=[Link](); while([Link]()) { [Link]([Link]()); }
65
import [Link]; public class MainClass { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); [Link]("C"); [Link]("A"); [Link]("E"); [Link]("B"); [Link]("D"); [Link]("F"); [Link]("Original contents of al: "); Iterator<String> itr = [Link](); while ([Link]()) { String element = [Link](); [Link](element + " "); } [Link](); ListIterator<String> litr = [Link](); while ([Link]()) { String element = [Link](); [Link](element);//or [Link](element+ "+" ); } // Now, display the list backwards. [Link]("Modified list backwards: "); while ([Link]()) { String element = [Link](); [Link](element + " "); } } } [Link] [Link] Enhanced for loop import [Link]; class ForEachDemo { public static void main(String args[]) { ArrayList<Integer> vals = new ArrayList<Integer>();
66
[Link](1); [Link](2); [Link](3); [Link](4); [Link](5); [Link]("Original contents of vals: "); for (int v : vals) [Link](v + " "); [Link](); int sum = 0; for (int v : vals) sum += v; [Link]("Sum of values: " + sum); } } Iterate a Collection and remove an item (Exception, wrong version) import [Link]; import [Link]; public class Main { public static void main(String args[]) { List<String> list = new ArrayList<String>(); [Link]("A"); [Link]("B"); [Link]("C"); [Link]("C"); [Link]("C"); [Link]("C"); [Link]("C"); for (String s : list) { if ([Link]("B")) { [Link]("B"); } [Link](s); } } } /*A B Exception in thread "main" [Link]
67
Exception at [Link]$[Link](Abst [Link]) at [Link]$[Link]([Link]) at [Link]([Link]) */ Use an Iterator and remove the item with [Link]() import [Link]; import [Link]; public class Main { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>(); [Link]("A"); [Link]("B"); [Link]("C"); [Link]("C"); [Link]("C"); [Link]("C"); [Link]("C"); [Link]("C"); for (Iterator<String> iter = [Link](); [Link] ext();) { String s = [Link](); if ([Link]("B")) { [Link](); } else { [Link](s); } } for (String s : list) { [Link](s); } } } Lesson 14:Advanced IO streams
68
Node Streams
69
Example of FileWriter import [Link].*; public class TestFileWriter { public static void main (String args[]) { String str="Character Stream Classes in Java"; try { FileWriter fout = new FileWriter("[Link]" ); [Link](str, 0, [Link]() ); [Link](); } catch (IOException ioe) { [Link]("Exception: " + [Link]()); } } //End of main() } Example of FileReader import [Link].*; public class TestFileReader {
70
public static void main(String args[]) { try { File file=new File("[Link]"); FileReader f=new FileReader(file); int ch; while((ch=[Link]())!=-1) //Loop till end of file. { [Link]((char)ch); } } catch(FileNotFoundException fnfe) { [Link]("Exception: "+[Link]()); } catch(IOException ioe) { [Link]("Exception: "+[Link]()); } } //End of main() } Copy Files Contents using read() import [Link].*; 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=[Link](buffer);//read one by one character while(ch!=-1) { //Loop till end of file.
71
[Link](buffer, 0,ch ); ch=[Link](buffer); } [Link](); [Link](); } catch(FileNotFoundException fnfe) { [Link]("Exception: "+[Link]()); } catch(IOException ioe) { [Link]("Exception: "+[Link]()); } } //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 < [Link]; i++) {
72
// Write Java data types [Link](sData[i]); [Link](bData[i]); [Link](iData[i]); // Clear any buffered data [Link](); // Get stream data into byte array and write record record = [Link](); [Link](record, 0, [Link]); // Toss any data in the internal array so writes // starts at beginning (of the internal array) [Link](); } [Link](); [Link](); } catch (Exception e) { db([Link]()); } } /*-------------------------------------------------* 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 <= [Link](); i++) { // Get data into the byte array [Link](i, recData, 0); // Read back the data types [Link]("Record #" + i); [Link]("UTF: " + [Link]() ); [Link]("Boolean: " + [Link] oolean()); [Link]("Int: " + [Link]() ); [Link]("--------------------"); // Reset so read starts at beginning of array [Link](); } [Link](); [Link](); } catch (Exception e) { db([Link]()); } } /*-------------------------------------------------* 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) { [Link]("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(); [Link](pn); l1=new Label("User name"); l2=new Label("Password"); t1=new TextField(10); t2=new TextField(10); b1=new Button("Sign up"); [Link](l1); [Link](t1); [Link](l2); [Link](t2); [Link](b1); [Link](300,300); [Link](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(); [Link](pn); l1=new Label("User name"); l2=new Label("Password"); t1=new TextField(10); t2=new TextField(10); b1=new Button("Sign up"); [Link](l1); [Link](t1); [Link](l2); [Link](t2); [Link](b1); [Link](300,300); [Link](true); } }; class TestGUI { public static void main(String[] args) { Loginscreen obj=new Loginscreen(); } } Ex3 import [Link].*; 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(); [Link]().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"); [Link](ldname); [Link](tdname); [Link](ldadd); [Link](tdadd); [Link](ldpno); [Link](tdpno); [Link](ldser); [Link](ser); [Link](b1); [Link](b2); } public static void main(String []args) { f=new JFrame("Dealer Details Form"); dealer obj=new dealer(); [Link](true); [Link](300,300); } } Ex4:Password Field in awt. import [Link].*; class PasswordDemo
77
{ Frame fr; Panel pn; Label l1; TextField t1; public PasswordDemo() { fr=new Frame("Test Form"); pn=new Panel(); [Link](pn); l1=new Label("Password"); t1=new TextField(10); [Link]('*'); [Link](l1); [Link](t1); [Link](400,300); [Link](true); } public static void main(String[] args) { PasswordDemo p=new PasswordDemo(); } } Ex5: import [Link].*; class PasswordDemo1 { JFrame fr; JPanel pn; JLabel l1; JPasswordField t1; public PasswordDemo1() { fr=new JFrame("Test Form"); pn=new JPanel(); [Link]().add(pn); l1=new JLabel("Password"); t1=new JPasswordField(10);//default //[Link]('*'); [Link](l1); [Link](t1); .
78
[Link](400,300); [Link](true); } public static void main(String[] args) { PasswordDemo1 p=new PasswordDemo1(); } } Add controls to Frame import [Link].*; 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"); [Link](400,300); [Link](true); } } Ex6 import [Link].*; 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"); [Link](400,300); [Link](true); } } Applets demo [Link] import [Link].*; public class Demo extends JApplet { JPanel pn; JButton b1; public void init() { pn=new JPanel(); getContentPane().add(pn); b1=new JButton("submit"); [Link](b1); } } [Link] <HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <applet code="[Link]" height=300 width=300></applet> </BODY> </HTML> Javac [Link] Appletviewer [Link] Another applet demo import [Link].*; public class Demo extends JApplet {
80
JPanel pn; JButton b1; public void init() { pn=new JPanel(); getContentPane().add(pn); b1=new JButton("submit"); [Link](b1); } } //<applet code="[Link]" height=300 width=300></applet> Javac [Link] Appletviewer [Link] FlowLayout //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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(); [Link](fl); b1=new b2=new b3=new b4=new JButton("Button JButton("Button JButton("Button JButton("Button 1"); 2"); 3"); 4");
[Link](b1);
81
[Link](b2); [Link](b3); [Link](b4); } } Border layout //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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); [Link](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"); [Link]("East",b1); [Link]("West",b2); [Link]("North",b3); [Link]("South",b4); [Link](b5,[Link]); } } GridLayout //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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); [Link](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"); [Link](b1); [Link](b2); [Link](b3); [Link](b4); [Link](b5); [Link](b6); } } GridBag Layout //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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(); [Link](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");
[Link]=[Link]; [Link]=[Link]; [Link]=1; [Link]=1; [Link]=1; [Link]=1; [Link](b1,gbc); [Link](b1); [Link]=1; [Link]=3; [Link]=1; [Link]=1; [Link](b2,gbc); [Link](b2); [Link]=2; [Link]=1; [Link]=3; [Link]=1; [Link](b3,gbc); [Link](b3); [Link]=3; [Link]=1; [Link]=1; [Link]=1; [Link](b4,gbc); [Link](b4);
84
[Link]=3; [Link]=3; [Link]=1; [Link]=1; [Link](b5,gbc); [Link](b5); [Link]=4; [Link]=1; [Link]=3; [Link]=1; [Link](b6,gbc); [Link](b6); } } Card layout //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; import [Link].*; 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(); [Link]([Link]); p2=new JPanel(); [Link]([Link]); p3=new JPanel(); [Link]([Link]); getContentPane().add(p); cl=new CardLayout(); [Link](cl); [Link]("Card1",p1);
85
[Link]("Card2",p2); [Link]("Card3",p3); b1=new JButton("1"); b2=new JButton("2"); b3=new JButton("3"); [Link](b1); [Link](b2); [Link](b3); [Link](this); [Link](this); [Link](this); } public void actionPerformed(ActionEvent evt) { if([Link]()==b1) { [Link](p); } if([Link]()==b2) { [Link](p); } if([Link]()==b3) { [Link](p); } } } Tabbed Panels import [Link].*; import [Link].*; 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(); [Link]().add(tb); b1=new JButton("Button1"); b2=new JButton("Button2"); b3=new JButton("Button3"); p1=new JPanel(); [Link]([Link]); [Link](b1); p2=new JPanel(); [Link]([Link]); [Link](b2); p3=new JPanel(); [Link]([Link]); [Link](b3); [Link]("First panel",null,p1,"this is first panel"); [Link]("Second panel",null,p2,"this is Second panel"); [Link]("Third panel",null,p3,"this is Third panel"); [Link](300,300); [Link](true); } } class demoTabbedPane { public static void main(String[] args) { demo dm=new demo(); } } Ex4 import [Link].*;
87
public class TestColor { public static void main(String[] args) { TestColor tester = new TestColor(); [Link](); } TestColor() {} private void launchFrame() { Frame f = new Frame(); Button b = new Button("Purple"); Color purple = new Color(255, 0, 255); [Link](purple); [Link](b); [Link](); [Link](true); } } Ex5 import [Link].*; class GWindow extends Frame { public void paint(Graphics g) { [Link](0,0,50,50); [Link](5,20,300,30); [Link]([Link]); [Link]("Hello",100,40); [Link](120,40,20,100); [Link](120,40,220,100); [Link](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; [Link](x,y,n); } } public class ShowGWindow { public static void main(String[] arg) { GWindow w = new GWindow(); [Link](350,60); [Link]("GWindow"); [Link](true); }
88
} Ex6 import [Link].*; import [Link].*; public class drawhouse extends Applet { public void paint(Graphics g) { [Link](120,40,20,100); [Link](120,40,220,100); [Link](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; [Link](x,y,n); } /*<APPLET CODE="[Link]" HEIGHT=300 WIDTH=300></APPLET>*/ } Lesson11:Events import [Link].*; import [Link].*; class TestButton { Frame fr; Panel pn; Button b1; public TestButton() { fr=new Frame("Niit"); pn=new Panel(); [Link](pn); b1=new Button("Submit"); [Link](b1); [Link](300,300); [Link](true); //register the listener class listerner l=new listerner(); [Link](l); }
89
public static void main(String[] args) { TestButton t=new TestButton(); } } class listerner implements ActionListener { public void actionPerformed(ActionEvent e) { Button b2=(Button)[Link](); [Link]("Hello"); } } Ex2 import [Link].*; import [Link].*; class TestButton1 { Frame fr; Panel pn; Button b1; public TestButton1() { fr=new Frame("Niit"); pn=new Panel(); [Link](pn); b1=new Button("Submit"); [Link]("Pressed"); [Link](b1); [Link](300,300); [Link](true); //register the listener class listerner l=new listerner(); [Link](l); } public static void main(String[] args) { TestButton1 t=new TestButton1(); }
90
} class listerner implements ActionListener { public void actionPerformed(ActionEvent e) { [Link]([Link]()); [Link]([Link]()); } } Ex3 import [Link].*; import [Link].*; class TestButton2 implements ActionListener { Frame fr; Panel pn; Button b1; Label l1; public TestButton2() { fr=new Frame("Niit"); pn=new Panel(); [Link](pn); b1=new Button("Submit"); l1=new Label("label"); [Link](b1); [Link](l1); [Link](300,300); [Link](true); //register the listener class [Link](this); } public void actionPerformed(ActionEvent e) { //Button b2=(Button)[Link](); //[Link]("Hello"); [Link]("hello"); } public static void main(String[] args) { TestButton2 t=new TestButton2();
91
} } Ex4:Adapter class import [Link].*; import [Link].*; 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"); [Link](label, [Link]); [Link](tf, [Link]); [Link](this); [Link](300, 200); [Link](true); } public void mouseDragged(MouseEvent e) { String s = "The mouse clicked x= "+[Link]() + " Y = " + [Link](); [Link](s); } public static void main(String args[]) { TestAdapter1 two = new TestAdapter1(); [Link](); } } Ex5:Inner class Inner class can access the private member of Outer class import [Link].*;
92
import [Link].*; 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 "+[Link]() + " Y = " + [Link](); [Link](s); } }; public void launchFrame() { Label label = new Label("Click the mouse"); // Add components to the frame [Link](label, [Link]); [Link](tf, [Link]); // Add this object as a listener [Link](new Inner() ); // Size the frame and make it visible [Link](300, 200); [Link](true); }
x=
93
public static void main(String args[]) { TestInner two = new TestInner(); [Link](); } } Ex6:Anonymous Class Compile Time generates the TestAdapter$[Link] import [Link].*; import [Link].*; 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 [Link](label, [Link]); [Link](tf, [Link]); // Add this object as a listener [Link]( new MouseAdapter() { public void mouseClicked(MouseEvent e) { String s = "The mouse clicked x= "+[Link]() + " Y = " + [Link](); [Link](s); } } ); // Size the frame and make it visible [Link](300, 200);
94
[Link](true); }
public static void main(String args[]) { TestAdapter two = new TestAdapter(); [Link](); } } Create table in GUI //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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); [Link](new GridLayout(2,1)); t=new JTable(content,heading); [Link]([Link]); [Link]([Link]); [Link]([Link]); JScrollPane jsp=new JScrollPane(t,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
95
[Link](jsp); } } Lesson 12 : MENUS Create the menus in GUI //<applet code="[Link]" height=300 width=300></applet> import [Link].*; import [Link].*; 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); [Link](new GridLayout(2,1)); t=new JTable(content,heading); [Link]([Link]); [Link]([Link]); [Link]([Link]); JScrollPane jsp=new JScrollPane(t,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); [Link](jsp); } }
96
Lesson 13 :Thread class Demo extends Thread { public void run()//overriden { } public static void main(String[] args) { [Link]("Hello World!"); } } class Demo implements Runnable { public void run()//interface method implemented { } public static void main(String[] args) { [Link]("Hello World!"); } } Book Reference Ex1:single Thread class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { [Link]("Hello"+i++); if(i==15) break; } } } class ThreadTester { public static void main(String[] args)
97
{ [Link]("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h);//create//Non runnable [Link]();//runnable [Link]("Main ended"); } }
Ex2:Multiple Threads class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { [Link]("Hello"+i++); if(i==5) break; } } } class ThreadTester { public static void main(String[] args) { [Link]("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); [Link]();//runnable [Link](); [Link]("Main ended"); }
98
Ex3:Sleep() class HelloRunner implements Runnable { int i; public void run() { i=1; while(true) { [Link]("Hello"+i++); if(i==5) break; } } } class ThreadTester { public static void main(String[] args) { [Link]("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); [Link]();//runnable [Link](); try { [Link](2000);//it comes only inside try ,otherwise compile time error. } catch(InterruptedException e) { [Link](); } [Link]("Main ended"); }
99
class newThreadClass implements Runnable { String ThreadName; newThreadClass(String name) { ThreadName = name; Thread t = new Thread(this, ThreadName); [Link]("Thread created: " + t); [Link](); } public void run() { for(int i=1;i<=5;i++) { [Link](ThreadName + "loop :" + i); } [Link](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++) { [Link]("Main Thread loop:" + i);
100
} [Link]("Main Thread is terminating now"); } } Ex4:sleep() class HelloRunner implements Runnable { int i; public void run() { for(int i=0;i<3;i++) { [Link]("Thread "+[Link]().getName()); [Link]("Hello"+i); try { [Link](2000); } catch(InterruptedException e) { [Link](); } } } } class ThreadTester { public static void main(String[] args) { [Link]("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); Thread t2=new Thread(h); [Link]("T1"); [Link]("T2"); [Link](); [Link](); [Link]("Main ended"); }
101
Ex5: sleep() class PrintMe implements Runnable { public void run() { for(int x = 0; x < 3; x++) { [Link]([Link]().getName()); try { [Link](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); [Link]("T1 - Larry"); [Link]("T2 - Curly"); [Link]("T3 - Moe"); [Link](); [Link](); [Link](); } }
102
Start(),join(),stop() is not static Thread t1=new Thread(r); [Link](); Sleep() is static [Link](); Terminating a thread class HelloRunner implements Runnable { int i; public void run() { for(int i=0;i<5;i++) { [Link]("Thread "+[Link]().getName()); [Link]("Hello"+i); try { [Link](200); } catch(InterruptedException e) { [Link](); } } } } class ThreadTester { public static void main(String[] args) { [Link]("Main started"); HelloRunner h=new HelloRunner(); Thread t1=new Thread(h); [Link]("T1"); [Link](); try
103
isAliveDemo class newThreadClass implements Runnable { public void run() { try { for(int i=1;i<=5;i++) { [Link](" child loop :" + i); [Link](100); } } catch( InterruptedException obj) { [Link]("Thread :" + obj + "interrupted"); } } } class isAliveDemo { public static void main(String args[]) { newThreadClass obj = new newThreadClass(); Thread t= new Thread(obj,"ChildThread" );
104
[Link]("Thread created: " + t); [Link](); [Link]([Link]() + " is alive ? : " + [Link]()); try { for(int i=1;i<=5;i++) { [Link]("Main Thread loop:" + i); [Link](200); } } catch(InterruptedException e) { [Link]("Main thread is interrupted");} [Link](t .getName() + "is alive ? : " + [Link]()); [Link]("Main Thread is exiting"); } }
Priority Demo class ChildThread implements Runnable { public void run() { try { for(int i=1;i<=5;i++) { [Link]("loop :" + i); [Link](500); } } catch( InterruptedException obj) { [Link]("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" ); [Link](Thread.NORM_PRIORITY - 2); [Link](Thread.NORM_PRIORITY + 2); [Link](Thread.NORM_PRIORITY +3); [Link]("Thread created: " + t1); [Link]("Thread created: " + t2); [Link]("Thread created: " + t3); [Link]("Child thread1 Priority "+[Link]() ); [Link]("Child thread2 Priority "+[Link]() ); [Link]("Child thread3 Priority "+[Link]() ); [Link]("Main Thread is exiting"); } }
Another Demo for Priority class ChildThread implements Runnable { Thread t; ChildThread(int p) { t = new Thread(this,"ChildThread" ); [Link](p); [Link]("Thread created: " + t); } public void run() { try
106
{ for(int i=1;i<=5;i++) { [Link](t+"loop :" + i); [Link](100); } } catch( InterruptedException obj) { [Link]("Thread :" + t + "interrupted");} } } class PriorityDemo { public static void main(String args[]) { [Link]("Main thread is started"); ChildThread obj1 = new ChildThread(Thread.MIN_PRIORITY); ChildThread obj2 = new ChildThread(Thread.MAX_PRIORITY); [Link](); [Link]();
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" ); [Link](p); [Link]("Thread created: " + t); } public void run() { try { for(int i=1;i<=5;i++) { [Link](t+"loop :" + i); [Link](100); } } catch( InterruptedException obj) { [Link]("Thread :" + obj + "interrupted");} } } class PriorityDemo { public static void main(String args[]) { [Link]("Main thread is started"); ChildThread obj1 = new ChildThread(Thread.MIN_PRIORITY+2); ChildThread obj2 = new ChildThread(Thread.MAX_PRIORITY-2); [Link](); [Link](); try { [Link](); //[Link](); } catch( InterruptedException obj) { [Link]("Thread :" + obj + "interrupted"); } for(int i=1;i<=5;i++) {
108
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); [Link]("Thread created: " + t); } public void run() { for(int i=1;i<=5;i++) { [Link](t+" loop :" + i); if(i==3) [Link](); } } }
109
class yieldDemo { public static void main(String args[]) { [Link]("Main thread is started"); ChildThread obj1 = new ChildThread("T1"); ChildThread obj2 = new ChildThread("T2"); [Link](); [Link]();
Not synchronized Demo class Thread1 { void call() { [Link]("first statement"); try { [Link](1000); } catch(Exception e) { [Link]("Error " + e); } [Link]("second statement"); } } class Thread2 extends Thread {
110
Thread1 t; public Thread2(Thread1 t) { this.t = t; } public void run() { [Link](); } } public class NotSynchronized { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 Obja = new Thread2(obj1); Thread2 Objb = new Thread2(obj1); [Link](); [Link](); } }
Synchronized Block class Thread1 { void call() { [Link]("first statement"); try { [Link](1000); } catch(Exception e) { [Link]("Error " + e); } [Link]("second statement"); } } class Thread2 extends Thread { Thread1 t;
111
public Thread2(Thread1 t) { this.t = t; } public void run() { synchronized(t) { [Link](); } } } public class SynchronizedBlock { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 obja = new Thread2(obj1); Thread2 objb = new Thread2(obj1); [Link](); [Link](); } }
Synchronized threads class Thread1 { synchronized void call() { [Link]("first statement"); try { [Link](1000); } catch(Exception e) { [Link]("Error " + e); } [Link]("second statement"); } }
112
class Thread2 extends Thread { Thread1 t; public Thread2(Thread1 t) { this.t = t; } public void run() { [Link](); } } public class SynchronizedThreads { public static void main(String args[]) { Thread1 obj1 = new Thread1(); Thread2 Obja = new Thread2(obj1); Thread2 Objb = new Thread2(obj1); [Link](); [Link](); } }
Producer consumer demo class Thread1 { int d; synchronized void getData() { [Link]("Got data:" + d); } synchronized void putData(int d) { this.d = d; [Link]("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++) { [Link]("Put Called by producer"); [Link](data++); } } } class consumer extends Thread { Thread1 t; public consumer(Thread1 t) { this.t = t; } public void run() { for(int i=0; i<5 ;i++) { [Link]("Get Called by consumer"); [Link](); } } } public class ProducerConsumer { public static void main(String args[]) { Thread1 obj1 = new Thread1(); producer p = new producer(obj1); consumer c = new consumer(obj1); [Link](); [Link](); }
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) { [Link](" Exception caught"); } } [Link]("Got data:" + d); flag=false; notify(); return d; } synchronized void putData(int d) { if(flag==true ) { try { wait();
115
} catch(InterruptedException e) { [Link](" Exception caught"); } } this.d = d; [Link]("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(); [Link]("Put Called by producer"); } public void run() { int data =10; for(int i=0; i<5 ;i++) { data=data+1; [Link](data); } } } class consumer implements Runnable { Thread1 t; public consumer(Thread1 t) { this.t = t; new Thread(this,"Consumer").start(); [Link]("Get Called by consumer"); } public void run() {
116
for(int i=0; i<5 ;i++) { [Link](); } } } 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"); [Link]("Child Thread:" + t); [Link](); } int i; public void run()
117
{ i=1; while(true) { [Link]("Hello"+i++); if(i==15) break; } } } class ThreadTester { public static void main(String[] args) { [Link]("Main started"); HelloRunner h=new HelloRunner(); [Link]("Main ended"); } }
Ex2: extends Thread(Another way) class ThreadDemo extends Thread { ThreadDemo() { super("ChildThread"); // calls the superclass constructor [Link]("ChildThread:" + this); start(); } public void run() { [Link]("The child thread started"); [Link]("Exiting the child thread"); }
118
} class ThreadDemoClass { public static void main(String args[]) { new ThreadDemo(); [Link]("The main thread started"); [Link]("The main thread sleeping"); try { [Link](1000); } catch(InterruptedException e) { [Link]("The main thread interrupted"); } [Link]("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); [Link]("Thread created: " + t); [Link](); } public void run() { try { for(int i=1;i<=5;i++) { [Link](ThreadName + "loop :" + i); [Link](100); }
119
} catch( InterruptedException obj) { [Link]("Thread :" + ThreadName + "interrupted"); } [Link](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++) { [Link]("Main Thread loop:" + i); [Link](300); } } catch(InterruptedException obj) { [Link]("Main thread is interrupted"); } [Link]("Main Thread is terminating now"); } }
120
Ex4: Main contains Thread coding class mainThreadDemo { public static void main(String args[]) { Thread t= [Link](); [Link](" The current thread: " + t); [Link]("MainThread"); [Link](" The current thread after name change : " + t); [Link](" The current Thread is going to sleep for 10 seconds"); try{ [Link](10000); } catch(InterruptedException e) { [Link]("Main thread interrupted"); } [Link](" After 10 seconds...........the current Thread is exiting now."); } }
Application Applet ---using thread import [Link].*; import [Link]; import [Link]; import [Link];
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); [Link](labelAppId); [Link](textAppID);
122
[Link](labelAppName); [Link](textAppName); [Link](labelAppPosition); [Link](comboAppPosition); dateTime(); } public void dateTime() { /* Initialize thread */ datimeThread = new Thread(this); /* Starting thread */ [Link](); } public void run() /* body of the thread */ { while(datimeThread != null) { display();// This method displays date try { [Link](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(); [Link](date); strTime = [Link]([Link])+":"+[Link]([Link] E)+":"+[Link]([Link]);
123
strDate = ([Link]([Link])+1)+"/"+[Link](Calendar. DATE)+"/"+[Link]([Link]); strStatus=strTime+" "+strDate; showStatus(strStatus); } }/* end of program */ [Link] <HTML> <HEAD> <TITLE> Applicant Applet </TITLE> </HEAD> <BODY> <APPLET ALIGN = center CODE= "[Link]" WIDTH = 100 HEIGHT = 0> </APPLET> </BODY> </HTML> Lesson15:Networking Client is sending message , server is reading Client programgetOutputStream() Server Program getInputStream() [Link] import [Link].*; import [Link].*; public class AppServer extends Thread { ServerSocket serverSocket; Thread th; public AppServer() { try { [Link]("Server is going to start . . ."); serverSocket = new ServerSocket(1800); [Link]("Server config at port no 1800. . ."); [Link]("Server started . . ."); th=new Thread(this); [Link](); // Starts the thread
124
} catch(IOException e) { [Link]("Error..."+ e); } } public void run() { try { while(true) { [Link]("Wating for client request...."); Socket client = [Link](); ObjectInputStream fromClient = new ObjectInputStream([Link]()); String clientMessage = (String)[Link](); [Link]("Received from:"+clientMessage); } } catch(Exception e) { [Link]("Error..."+ e); } }//run close public static void main(String args[]) { new AppServer(); } } [Link] import [Link].*; import [Link].*; public class myClient { public static void main(String[] args) { String str=args[0];
125
try { Socket sc=new Socket("[Link]",1800); ObjectOutputStream toServer = new ObjectOutputStream([Link]()); [Link]((String)str); [Link](); [Link]("Message Send"); } catch (Exception ex) { [Link]("Error..."); } } } Java myclient John Server is writing and client is reading that Server Program getOutputStream() Client programgetInputStream() [Link] import [Link].*; import [Link].*; public class AppServer1 { ServerSocket serverSocket; public AppServer1() { try { [Link]("Server is going to start . . ."); serverSocket = new ServerSocket(1800); [Link]("Server config at port no 1800. . ."); [Link]("Server started . . ."); } catch(IOException e) { [Link]("Error..."+ e); }
126
} public void send() { try { while(true) { [Link]("Wating for client request...."); Socket client = [Link](); OutputStream fromClient = [Link](); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(fromClient)); [Link]("Hello niit\n"); [Link](); [Link](); } } catch(Exception e) { [Link]("Error..."+ e); } } public static void main(String args[]) { AppServer1 obj=new AppServer1(); [Link](); } } [Link] import [Link].*; import [Link].*; public class myClient1 { public static void main(String[] args) { try { Socket sc=new Socket("[Link]",1800);
127
InputStream
toServer = [Link]();
DataInputStream dis =new DataInputStream(toServer); [Link]([Link]()); [Link](); [Link](); } catch (ConnectException ex) { [Link]("Error..."+ex); } catch (Exception ex) { [Link]("Error. is a .."+ex); } } }