Chapter 1 Introduction to java Java is language for the development of Enterprise applications, and it was developed at Sun Microsystems as a platform-independent language primarily aimed at controlling appliances such as video game consoles VCRs, bread toasters . “Sun” , later modified the language to take advantage of World Wide Web . Java is an object-oriented language, and very similar to C++. Java Features 1. PlatformIndependent The concept of Write-once-run-anywhere is one of the important key feature of java language that makes java as the most powerful language. 2. Simple Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system. 3. ObjectOriented java is a fully Object Oriented language because, object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into objects. 4. Robust Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust. 5. Distributed Internet programmers can call functions on HTTP , FTP protocols 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Chapter 1
Introduction to javaJava is language for the development of Enterprise applications, and it was developed at Sun Microsystems as a platform-independent language primarily aimed at controlling appliances such as video game consoles VCRs, bread toasters .
“Sun” , later modified the language to take advantage of World Wide Web. Java is an object-oriented language, and very similar to C++.
Java Features
1. PlatformIndependentThe concept of Write-once-run-anywhere is one of the important key feature of java language that makes java as the most powerful language.
2. SimplePrograms are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system.
3. ObjectOrientedjava is a fully Object Oriented language because, object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into objects.
4. RobustJava has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.
5. DistributedInternet programmers can call functions on HTTP , FTP protocols and can get access to the files from any remote machine rather than writing codes on their local system.
6. PortableThe feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM.
7. SecureJava does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.
8. PerformanceJava uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted in slow performance but the advanced versions of JVM uses just in time compilation technique that improves the performance.
9. MultithreadedMultithreading programming is a very interesting concept in Java.
10. InterpretedOne of the advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced.
11. Architecture Neutral Java was designed to support applications on network. The Java compiler generates byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly.
What is Java Virtual Machine?
Languages like C and Pascal converts the source code into machine code for one specific type of machine and the machine language vary from system to system . But Java compiler produce code for a virtual machine . JVM converts the byte code into machine code for the computer one wants to run. The JVM is a part of JRE that is required by every operating system.
Each operating system and CPU architecture requires a JRE. JRE consists of a set of base classes i.e. Java API as well as a JVM. JVM is java interpreter as it converts the byte code into machine code for the computer one wants to run.
JRE consists of a number of classes based on JavaAPI and JVM, and without JRE, it is impossible to run Java.
How to write First Java program
public class FirstProgram{ public static void main(String arr[] ) { System.out.println(" Hello Java World"); }}
Save the file with same name as the public class just adding the extension “ .java” e.g. FirstProgram.java.
Now compile as:
c:\ javac FirstProgram.java
This creates a class file in bytecode form as FirstProgam.class
How to execute this code:
c:\ java MyFirstProgram
OUTPUT :: Hello Java World
Different Editions of Java Technology
a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create desktop applications, applets, server applications. These programs developed using Java SE can be run on almost every popular operating system.
b) JEE - Java Enterprise Edition helps in web application service, component model and enterprise class service oriented architecture(SOA).
c) JME - Java Micro Edition or JME is an accumulation of Java APIs that are used for the development of software for devices like mobile phones, PDAs, TV set-top boxes, game programming.
Demonstartion Programs
Example 1 : Demo of a Simple java program public class FirstProg { public static void main(String args[]) { System.out.println( “welcome to the java SE 6”); } }
Example 2 : Demo of if statement through a java program public class DemoIf { public static void main(String args[]) { int a = 10, b = 15, m;
if (a > b) m = a; else m = b; System.out.println( “max number = “+m); } } Example 3 : Demo of while.. loop through a java program public class DemoWhile { public static void main(String args[]) { int n = 257, s =0, d; while (n !=0) { d = n % 10; s = s +d ; n = n / 10; } System.out.println( “sum of digits = “+s); } }
Example 4 : Demo of for.. loop public class DemoFor { public static void main(String args[]) { int n = 30, i; for (i = 1; i <=n; i++) if ( n % i == 0 ) System.out.println( “ “+ i ); } }
4
Structure of ArraysArray is the most widely used data structure in java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased. The Array class implicitly extends java.lang.Object so an array is an instance of Object. Suppose an array contains "n" integers. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first index value.
The figure below shows the structure of an Array more precisely.
Array Declaration
To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable.
int[] array_name; //declares an array of integersString[] names;int[][] matrix; //this is an array of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. for example:
int[] array_name = new int[5];
Here is an example that creates an array that has 5 elements.
public class Array{ public static void main(String[] args) { int[] a = new int[5]; }}
5
Array InitializationAfter declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the array object. The correct way to use the "new" operator isString names[];names = new String[10];Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated.Lets see a simple example of an array,public class Sum { public static void main(String[] args) { int[] x = new int [101]; for (int i = 0; i<x.length; i++ ) x[i] = i; int sum = 0; for(int i = 0; i<x.length; i++) sum += x[i]; System.out.println(sum); }}
To know the length of the Array, we use field length, as shown.Example 5 : Demo of 1 D array - Linear search public class DemoLsearch { public static void main(String args[]) { int a[] ={ 10,20,30,15,25}, i, n; int x = 15, flag = 0; n = a.length; for ( i = 0 ; i < n ; i ++) if ( a[ i ] == x) { flag = 1; break; } if ( flag != 0 ) System.out.println( “item found at = “+ ( i+1)); }
Example 6 : Demo of 1 D array - Sorting of n integers public class DemoSort { public static void main( String args[] ) { int a[ ] ={ 10,08,30,15,27,17,12}, i, j, n,temp; n = a.length; for ( i = 0 ; i < n-1 ; i ++) for (j= i+1; j < n; j++) if ( a[ i ] >a[ j ]) { temp = a[ i ]; a[ i ] = a[ j ]; a[ j ]= temp; } for ( i=0; i < n; i++) System.out.println( “ “+ a[ i ]); } }
Example 7 : Demo of user defined iterative functions public class DemoFunction { public static void main(String args[]) { int n = 5, i, fm; fm = fact (m); System.out.println(“result = “ + fm); } static int fact( int n) { int fn = 1, i; for (i = 2; i <=n; i++) fn = fn * i; return fn; } }
7
Example 8 : Demo of Recursive functions public class DemoRecfun { public static void main(String args[]) { int n = 5, i, fm; fm = fact (m); System.out.println(“result = “ + fm); } static int fact( int n) { if ( n < 0) return 1; else return n * fact ( n – 1); } }
8
Chapter 2
Object Oriented Features of JavaOOP stands for Object Oriented Programming. There are four main pillars of an Object Oriented Programming Language :
Inheritance: Inheritance provide the facility to derive one class by another using simple syntax. You can say that it is a process of creating new class and use the behavior of the existing class by extending them for reuse the existing code and adding the additional features as you need.
Encapsulation: Encapsulation is the ability to bundle the property and method of the object and also operate them. It is the mechanism of combining the information and providing the abstraction as well.
Polymorphism: Polymorphism is the way that provide the different functionality by the functions having the same name based on the signatures of the methods. There are two type of polymorphism first is run-time polymorphism and second is compile-time polymorphism.
Dynamic binding: It is the way that provide the maximum functionality to a program for a specific type at runtime. There are two type of binding first is dynamic binding and second is static binding.
Class: A class provide a feature to defines the properties and behavior (variables and methods) as an ADT , that can be used by all its objects. It is a blue print for the creation of objects.
Object: Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (members) and uses the behavior (methods) defined in the class.
The Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been described below :
Encapsulation:Encapsulation is the process of binding together the methods and data variables as a single entity. It keeps both the data and functionality code safe from the outside world. It hides the data within the class and makes it available only through the methods. Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside.
Here we provide a example in which we create a class "Check" which has a variable "amount" to store the current amount. Now to manipulate this variable we create a methods and to set the value of amount we create setAmount() method and to get the value of amount we create getAmount() method
9
Here is the code for "Mainclass" class :
class Check { private int amount=0; public int getAmount() { return amount; } public void setAmount(int amt) { amount=amt; } }
public class Mainclass{ public static void main(String[] args)
{ int amt=0; Check obj = new Check(); obj.setAmount(200); amt = obj.getAmount(); System.out.println("Your current amount is :"+amt); }}
Here the data variable "amount" and methods setAmount() and getAmount() are enclosed together with in a single entity called the "Check" class. These two methods are used to manipulate this variable i.e. set and get the current value of amount.
Example 9 : Demo of object oriented programming
class DemoCalc { int a , b;
public DemoCalc() { a = 5; b = 10; }
public int sum ()10
{ int x; x = a + b; return x; } }
public class TestDemoCalc { public static void main(String args[]) { DemoCalc m = new DemoCalc(); int z; z = m.sum(); System.out.println(“result = “ + z); } }
Constructor
Constructor is the method whoose name is same as that of the class. But there are many difference between the method (function) and the Constructor. It has no return type.
It is used for initialization purpose. A class can have any number of constructors. It is then called constructor overloading.
Example 10 : Demo of Constructor Overloading class DemoOver { int a , b; /* default constructor */ public DemoOver() { a = 5; b = 10; } /* constructor with parameter */ public DemoOver( int k1, ink k2) { a = k1; b = k2; } public int sum ()
11
{ int x; x = a + b; return x; } } public class TestDemoOver { public static void main(String args[]) { DemoOver m1 = new DemoOver(); DemoOver m2 = new DemoOver(20,25); int z1, z2; z1 = m1.sum(); z2 = m2.sum(); System.out.println(“result1 = “ + z1 + “result2 “+z2); } }
this key word : It is used to resolve the ambiguity between a formal parameter and a datamember.
Example 11 : Demo of keyword this class Demothis { int a , b; /* constructor with parameter */
public Demothis( int a, ink b) { this.a = a; this.b = b; } public int sum () { int x; x = a + b; return x; } } public class TestDemothis {
12
public static void main(String args[]) { Demothis m1 = new Demothis(20,25); int z1; z1 = m1.sum(); System.out.println(“result = “ + z1 ); } }
Instance variables: They are the datamembers in a class and get a copy of memory for each object instance. With one object instance if they are modified , the other instances are not effected.
Example 12 : Demo of instance variable class DemoInvar { int a,b; public DemoInvar( ) { a=5; b=7; } public void update () { a++; b++; }
public class TestDemoInvar { public static void main(String args[]) { DemoInvar m1 = new DemoInvar(); DemoInvar m2 = new DemoInvar ();
13
m1.update(); m1.disp(); m2.disp(); } }Static variables: They are the data members in a class defined with a keyword static. Such members are also called class members , . and get a single copy of memory per JVM, for all object instances. With one object instance if they are modified , the other instances are also effected as they are shared . Example 13 : Demo of class variable class DemoClvar { static int a ; int b; public DemoClvar( ) { a = 5; b = 7; } public void update( ) { a ++; b++; }
public void disp( ) { System.out.println ( “a= “+a + “b=”+b); } } public class TestDemoClvar { public static void main(String args[]) { DemoClvar m1 = new DemoClvar(); DemoClvar m2 = new DemoClvar (); m1.update( ); m1.disp( ); m2.disp( ); }
14
}
Class methods : Such methods belong the class but not to the objects. They are called with class name.
Example 14 : Demo of class method class DemoClmd
{ public static wishcode01 () { System.out.println( “ Happy New Year”); } public static wishcode02 () { System.out.println(“Happy returns"); } } public class TestDemoClmd { public static void main(String args[]) { DemoClmd.wishcode01( ); DemoClmd.wishcode02( ); } }
15
Example 15 : Demo of class method class DemoMathop { static float multiply(float x, float y) { return x*y; }
public class TestDemoMathop { public static void main(String args[]) { float a = DemoMathop.multiply(2.0,5,0); float x = DemoMathop.divide(a,2.0); System.out.println("x=" + x); } }
Example 16 : Demo of method invocation by other methods of the same class ( Nested methods) class DemoNest { int a,b; public DemoNest( ) { a=15; b=7; } public int large() { int m; m= ( a>b)? a : b; return m; }
16
public void disp() { int x = large(); /* method call */ System.out.println ( “max= “+ x); }
} public class TestDemoNest { public static void main(String args[]) { DemoNest m1 = new DemoNest(); m1.disp(); } }System.out.println() ::
The "java.lang" package is built into every program. A package is a libaries of classes.The java.lang package has a System Class, which includes a static nested class called "out" and this out class, has a method by name println().
Why method main has " public , static" access specifiers ::
It is called from outside. The main() is a class method It is invoked by the interpretor with its class name.
17
Chapter 3
String Handling
Strings are handled as objects in java. Java support two classes to handle strings
1 String 2 StringBuffer
String objects hold text which can't be changed. A String class object is immutable because the time taken by JVM to reallocate memory and add data is more than creating a new object. A StringBuffer on the otherhand, is mutable. It can change and grow in size The default constructor allocates 16 char size to a StringBuffer String Methods Let s1, s2 are the source and destination strings. Then some methods are s2 = s1.toLowerCase() s2 = s1.replace('x', 'y')
s2 = s1.trim()
s1.equals(s2) , s1.isEmpty()
s1.equalsIgnoreCase(s2)
S1.length s1.charAt(n)
s1.subString(n) , s1.subString(m,n)
s1.indexOf("x")
s1.toString()
s1.compareTo(s2)
s2 = s1.concat(s3) s2 = s1.replace('x','y') (It create a new string object s2)
18
StringBuffer methods
s1.charAt(n) s1.append(s2), s1.replace(m,n,s2)
s1.setCharAt(n,'x')
s1.insert(n,s2)
s1.setLength(n) , s1.length(), s1.reverse()
The following programs demonstrate String handling in java.
Example 17 : Demo of methods in String class
public class TestStread { public static void main( String args[]) { String s1 = "hello";
public class TestSbuff { public static void main( String args[]) {
20
StringBuffer sb= new StringBuffer("Java is tough"); System.out.println(sb); int n = sb.length(); int p; for ( i=0; i< n; i++) { p = i + 1; System.out.print("char at pos" +p+"=" + sb.charAt(i)); } String a = new String(sb.toString()); p = a.indexOf("tough"); sb.insert(p,"Not "); System.out.println(sb); sb.append(" to learn"); System.out.println(sb); } }
StringBuilder class ::
StringBuffer , can be used by multiple threads. It is recommended when synchronization is required. Its methods are synchronized. A StringBuilder has no synchronized methods. So it works faster and , When we are doing number of string operations in a single thread we gain tremendous performance than StringBuffer.
Example 21 :: Demo of StringBuilder
public class TestApp { public static void main(String args[]) { String s = concate("java"," ","is"," ","simple"); System.out.println(s); } static String concate(String... k) { StringBuilder sd = new StringBuilder( ); int n = k.length; int i;
for ( i= 0; i< n ; i++) sd.append(k[i]);
21
return sd.toString( ); } }
StringTokenizer.
Example 22:
import java.util.StringTokenizer;class STDemo {static String in ="title=Java: The Complete Reference;" +"author=Naughton and Schildt;" +"publisher=Osborne/McGraw-Hill;" +"copyright=1999";public static void main(String args[]) {StringTokenizer st = new StringTokenizer(in, "=;");while(st.hasMoreTokens()) {String key = st.nextToken();String val = st.nextToken();System.out.println(key + "\\t" + val);}}}
Wrappers
Java provide wrapper classes in order to use primitive data types as objects, Every primitive type has a class defined
primitive wrapper22
int Integer float Float char Character
There are methods defined to return the values of an object Example 23 : Demo of wrapper class
public class TestWrp1 { public static void main( String args[]) { Integer i = new Integer(25); Character c = new Character('H'); int J = i.intValue(); char k = c.charValue();
System.out.println(j + " " +i); System.out.println(k+ " " + c); } }Let a,b are primitive types, m,n are objects , and S is string object
Conversion of primitive types to primitive objects Integer m = new Integer(a); Float n = new Float(b);
Conversion of primitive objects to primitive types int a = m.intValue(); float b = n.floatValue(); Conversion of primitive types to string objects String s = Integer.toString(a); String s = Float.toString(b);
Conversion of string objects to primitive types int a = Integer.parseInt(s); float b = Float.parseFloat(s);Example 24 : Demo of wrapper class
public class Adder { public static void main( String args[])
23
{ int a, b, m; a= Integer.parseInt(args[0]); b= Integer.parseInt(args[1]); m = a+b; System.out.println("result " + m); } }
Autoboxing, unboxing of primitive types
Example 25 : Demo of autoboxing, unboxing
public class TestBoxUnbox { public static void main( String args[]) { Integer ib1,ib2,ib3; ib1 = 25; // autoboxing - encapsulating a value int i1 = ib1; // unboxing - extracting the value
} } class Abox { static int getval( Integer ib) { return ib; // unbox the return vaule } }
for - each loop ::
for (type varaible : collection)24
statement;
Example 26 : Demo of for each
public class DemoApp { public static void main( String args[]) { for ( String s: args) System.out.println(s); } }
Example 27 : Demo of for-each
public class DemoApp { enum Country { india, china, japan, canada}; public static void main( String args[]) { for ( Country c: Country.values()) System.out.println("it Is" + c); } }
variable number of arguemnts ::
25
Example 28 : Demo of variable numer of parameters
public class DemoApp { static void mthvar(int... i) { int n = i.length; System.out.println("number of para"+ n); System.out.println("contents are");
for ( int k : i) System.out.println("it Is" + k); } public static void main( String args[]) { mthvar(); mthvar(25,35); mthvar(10,20,30,40); } }
Example 29 : Demo of for-each public class DemoApp { public static void main( String args[]) { int a[] = { 10,20,30,40,50}; int max = 0;
for ( int k: a) if ( k > max) max = k; System.out.println("maximum" + max); } }
26
Chapter 4
Inheritance & Polymorphism in javaInheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class (superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.
Here is the code of the example :
class A { public void fun1(int x) { System.out.println("in A is :" + x); } }
class B extends A { public void fun2(int x,int y) { fun1(6); // prints "int in A" System.out.println("in B is :" + x " and "+y); }}
public class Testinherit { public static void main(String[] args) { B obj= new B(); obj.fun2(2); }}
In the above example, class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.
Thus inheritance is aechanism used to create new class by extending the definition of another class. This process of extending one class to create new class is called subclassing.
27
Types::
Single inheritance Multiple Inheritance Multilevel Inheritance Hirarchial Inheritance Hybrid Inheritance /* Demo of inheritance */ class DemoCalc { int a,b; public DemoCalc() { a = 5; b = 10; } public int sum () { int x; x = a + b; return x; } } public class TestDemoCalc { public static void main(String args[]) { DemoCalc m = new DemoCalc(); int z; z = m.sum(); System.out.println(“result = “ + z); } }
Example 30 : Demo of inheritance
class ChDemoCalc extends DemoCalc { public int diff() { int x; x = a-b; return x; }
28
} public class TestChDemoCalc { public static void main(String args[]) { ChDemoCalc m = new ChDemoCalc(); int z1,z2; z1 = m.sum(); z2 = m.diff(); System.out.println( “sum=“+ z1 + "diff=" +z2 ); } }
Constructor under inheritance When a child class object is instantiated the constructor of the base class is called first , then followed by the derived class constructor.
Example 31 : Demo of constructor under inheritance
class A { A( ) { System.out.println("In constructor of A"); } } class B extends A { B( ) { System.out.println("In constructor of B"); } } public class TestApp { public static void main(String args[]) { B b1 = new B(); } }
output :: In construtor of A In construtor of B
29
Example 32 : constructor with param under inheritance - 1
class A { A( ) { System.out.println("In constructor of A"); } }
class B extends A { B(String s ) { System.out.println("In string constructor of B"); System.out.println(s); } }
public class TestConInhe { public static void main(String args[]) { B b1 = new B("Java is simple"); } }
output :: In construtor of A In string construtor of B java is simple
30
Example 33 : constructor with param under inheritance - 2
class A {
A( ) { System.out.println("In constructor of A"); } A(String s ) { System.out.println("In string constructor of A"); System.out.println("In A" + s); } }
class B extends A { B(String s ) { super(s); System.out.println("In string constructor of B"); System.out.println("In B" + s); } }
public class TestApp { public static void main(String args[]) { B b1 = new B("Java is simple"); } }
output :: In string construtor of A In A java is simple In string construtor of B In B java is simple
super( ) :: It can be used to call super class methods/constructor
31
Multilevel inheritance:: Example 34 : Constructor under Multilevel inheritance
class A { A( ) { System.out.println("In constructor of A"); } } class B extends A { B( ) { System.out.println("In constructor of B"); } }
class C extends B { C( ) { System.out.println("In constructor of C"); } } public class TestApp { public static void main(String args[]) { C c1 = new C(); } }
output :: In construtor of A In construtor of B
In contructor of C
Polymorphism
Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows a object to accept different requests of a client (it then properly
32
interprets the request like choosing appropriate method) and responds according to the current state of the runtime system, all without bothering the user.
In compiletime Polymorphism, method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept in java.
Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).
Here is the code of the example :
class A{ public void fun1(int x){ System.out.println("The value of class A is : " + x); } public void fun1(int x,int y){ System.out.println("The value of class B is : " + x + " and " + y); }}public class polyone{ public static void main(String[] args){ A obj=new A();// Here compiler decides that fun1(int) is to be called and "int" will be printed. obj.fun1(2); // Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed. obj.fun1(2,3); }}
In rumtime polymorphism, the method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.
class A{ public void fun1(int x){ System.out.println("int in Class A is : "+ x); }}class B extends A{ public void fun1(int x){
33
System.out.println("int in Class B is : "+ x); }}public class polytwo{ public static void main(String[] args){ A obj; obj= new A(); // line 1 obj.fun1(2); // line 2 (prints "int in Class A is : 2") obj=new B(); // line 3 obj.fun1(5); // line 4 (prints ""int in Class B is : 5") }}
Method Overriding ::
It is used when a subclass has to replace a method of its superclass. Whenever such a method is invoked, java looks for a method of that signature, in the class definition of the current object. If such a method is not found then it looks for a matching signature in the superclass.
Example 35 :: Demo of method overriding
class Animal { public void breath( ) { System.out.println(" Breathing..."); } } class Fish extends Animal { public void breath( ) { System.out.println("Bubbling..."); } }
public class TestRide { public static void main(String args[])
34
{ Fish f = new Fish(); f.breath(); } }
output :: bubbling...
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class. It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions.
class A{ int a; float b; void Show(){ System.out.println("b in super class: " + b); }}
class B extends A { int a; float b; B( int p, float q) { a = p; super.b = q; } void Show()
35
{ super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args) { B subobj = new B(1, 5); subobj.Show(); }}
Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list.
Example 36 : method overriding - how to access original method
class Animal { public void breath( ) { System.out.println(" Breathing..."); } } class Fish extends Animal { public void breath( ) { System.out.println("Bubbling..."); }
public void newbreath( ) { super.breath(); }
36
}
public class TestRide { public static void main(String args[]) { Fish f = new Fish(); f.newbreath(); f.breath(); } } output :: breathing... bubbling... Dynamic method dispatch ( Run time polymorphism)
Any subclass object reference can be given to a super class variable. It is to suport runtime polymorphism. It lets us write code that works with many different types of objects, and decide on the actual object type at runtime.
Example 37 : Runtime polymorphism
class A { public void disp( ) { System.out.println("printing A"); } } class B extends A { public void disp( ) { System.out.println("printing B"); } }
class C extends B { public void disp( ) { System.out.println("printing C"); } }
37
public class TestApp { public static void main(String args[]) { A a1 = new A(); B b1 = new B(); C c1 = new C();
A class is abstract if one or more methods in it are defined by the abstract key word. A method is abstract when it has only declaration but no expansion in the base class.No objects can be instantiated from such a class. When writing classes , we run across cases where we can provide general code and it is upto the developer to customize it in a subclass. To make sure he customizes it, we make the method abstract. Such a class is also made abstract.
38
Example 38 : Demo of abstract class -- 1
abstract class A { abstract public void disp( ); }
class B extends A { public void disp( ) { system.out.println("java is simple"); } }
public class TestApp { public static void main(String args[]) { B b1 = new B( ); b1.disp( ); } } Example 39 : Demo of abstract class -- 2
abstract class A { abstract String getData( ); public void disp( ) { System.out.println( getData( ) ); } } class B extends A { String getData( ) { String s = "java is simple"; return(s); } } public class TestApp
39
{ public static void main(String args[]) { B b1 = new B( ); b1.disp( ); } }Note : constructors, private, static methods can NOT be abstract.
Final modifier ::
To stop overriding To stop Inheritance creating constants
To stop overriding ::
class Animal { final void breath( ) { System.out.println(" Breathing..."); } } class Fish extends Animal { public void breath( ) ......???? ( not allowed ) { System.out.println("Bubbling..."); } } To stop inheritance ::
final class Animal { public void breath( ) { System.out.println(" Breathing..."); } } class Fish extends Animal .....????! ( no .. not allowed ) { public void breath( )
40
{ System.out.println("Bubbling..."); } }
To create constants::
final int a = 25; a++; .....????! not allowed a = 50; .....????! not allowed
is-a relation :: standard inheritance refers to is-a relation class A { void disp( ) { System.out.println("from A"); } }
class B extends A // B is-a A { B( ) { disp( ); } }
public class TestApp { public static void main(String args[]) { B b1 = new B(); } }
has-a relation :: It is a state when one object holds other object instances.
class A { void disp( )
41
{ System.out.println("from A"); } } class B { A a1; // B has-a A
B( ) { a1 = new A( ); a1.disp( ) ; //The disp of A is avilable to obj B } }
public class TestApp { public static void main(String args[]) { B b1 = new B(); } }
java Object class ::
Every class in java is derived automatically from java.lang.Object class. All classes in java are subclasses
Every object thus inherits certain methods. some of them
boolean equals(ob) :: used to check whether an object ob equals to this one
protected void finalize() :: called by garbage collector when it is about to dispose object Class getClass() :: It gives the run time class of the object
int hashCode() :: It gives a hashcode value of the object.
Example 40 :: Demo of Object class
class A42
{ public void disp( ) { System.out.println("printing A"); } } class B extends A { public void disp( ) { System.out.println("printing B"); } }
class C extends B { public void disp( ) { System.out.println("printing C"); } }
public class TestApp { public static void main(String args[]) { A a1 = new A(); B b1 = new B(); C c1 = new C(); A oref; oref = a1; oref.disp(); System.out.println( "ref is " + oref.getClass() );
Java has a built in process called garbage collector. It occurs automatically , although we can not predict when it will happen. Java itself dispose of the memory that no longer has reference to it. However to make it happen we can set references to null
Example 41 :: Demo of garbage collection
class A { void disp( ) { System.out.println("from A"); } } public class TestApp { public static void main(String args[]) { int a[ ] = { 10,20,30 }; A b1 = new A(); int l ; b1.disp(); l = a.length; System.out.println ( "l=" + l );
b1 = null; a = null; // making them null
} }
Example 42 :: Demo of garbage collection & finalize() method
class Tester {
44
public int k; Tester( int i ) { k = i; } }
class A {
int m1; Tester t; A( ) { m1 = 5; t = new Tester(2500); } void disp( ) { System.out.println("from A"); }
protected void finalize() { t = null; // inner object to null }
} public class TestApp { public static void main(String args[]) { A b1 = new A(); b1.disp(); b1 = null; } }
interfaces : 45
They provide templates of behaviour, that other classes can implement. They define the design and classes that implement the interface must provide the implementation of the design. In Abstract classes some methods may have definition, and leaving few undefined. In interfaces no method can be defined.
The data members in Abstract class can be variables or constants but they are only constants in an interface. A class can extend only one abstarct class. But a class may implement multiple interfaces, and thus provide an indirect way to multiple inheritance.
class Printer { public void print() { // set the params // print data ..... } } interface Copier { public void copyDocument( Document d); } interface Fax { public void transmitDocument(Document d); } class MultiFunctionPrinter extends Printer implements Copier, Fax { // the content ... }
Note : A method inside an interface can not be declared private or protected. They can carry public abstract modifiers only. The members must be public, static final making them constants.
46
interface Examp { public static final int a = 3; int b = 5; // effectively public static final
public abstract void calc( ); void change( ); // effectively public and abstract }
Extending an interface :
Like classes interface can inherit from other interfaces. The sub interface acquires all the method definitions and constants of the super interfaces.
interface Newxerox extends Copier, Fax { .... }
Marker Interface
In java language programming, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.
e.g. Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.
Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.
Example 43 : Demo of Interfaces import java.io.*; interface StudentInter { void getData( ) throws IOException; void showData(); int calcTot();
public float calcPercent( ) { int t = m1+ m2; return ( t / 2 ); }
public void menu( )48
{ System.out.println ( "Enter 1 to get total"); System.out.println ( "Enter 2 to get percent"); }
}
public class TestStudent { public static void main( String args[ ] ) { Student s = new Student( ); s.getData(); s.showData(); int tot; float per; s.menu( ); // to display menu
DataInputStream d = new DataInputstream( System.in ); System.out.print( "Enter choice : " ); int n = Integer.parseInt( d.readLine( ) ); switch( n ) { case 1: tot = s.calcTot(); System.out.println("total =" + tot); break; case 2: per = s.calcPercent(); System.out.println("percent=" + per); break; default: System.out.println( "incorrect choice" ); } } }
Partially implementing an interface
Classes that partially implement an interface must be abstract as they are only expanding few methods.
49
Example 43 :
interface A { void dispone(); void disptwo(); } abstract class B implements A { void disptwo() { system.out.println("expanded from b); } } class C extends B { void dispone( ) { System.out.println("expanded from c"); } }
public class TestApp { public static void main( string args[]) { C k1 = new C(); k1.dispone(); k1.disptwo(); } }
Inner classes ::
They are non static nested classes. They nest the definition of one class inside another. They are usefull while handling events such as user closing a window etc.
Example 44 :Demo of inner classes
class A { class B
50
{ public void disp( ) { system.out.print("inside B .."); } }
B b1; A( ) { b1 = new B( ); b1.disp( ); } } public class TestApp { public static void main(String args[]) { A a1 = new A(); } } when we instantiate Object a1 of class A, it instantiates internal object b1 of class B.
ProcessBuilder class ::
An Operating system process can be created using this class, and it manage all the process attributes. It is not at all synchronized.
Example 45 :: Demo of ProcessBuilder class
import java.io.*; public class TestApp { public static void main(String args) throws IOException { ProcessBuilder pb1; pb1 = new ProcessBuilder("notepad.exe","first.java"); pb1.start( ); }
51
}
52
Chapter 5
Exception Handling
Exception is a runtime error , that may cause abnormal termination of the program during its execution. When an error occurs within a java method , the method creates an exception object and hands it off ( Throwing) to the runtime system. This exception object contain information about exception, its type, state of the program when it occured.
The runtime system searches for appropriate block of code to handle the exception.
If there is no appropriate handler, with in that block the serach progresses up through the call stack, until an appropriate handler is found. If no such handler is found, the runtime system stops and the program terminates.
public class Divide { public static void main(String args[]) { System.out.println("prog starts here.."); int a,b,c; a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b; System.out.println("c="+ c); System.out.println("program ends here.."); } }
Running with 4 cases as below would give a picture :
case 1 : java Divide 4 2 case 2 : java Divide 4 case 3 : java Divide a 2 case 4 : java Divide 4 0
To prevent interuption of the programs flow from exceptions such as the ones shown above, handlers are used to catch such exceptions and handle them appropriately through cleanup or message notification.
53
There are three types of Exceptions:
1. Checked Exceptions - These are the exceptions which occur during the compile time of the program. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. These exceptional conditions should be anticipated and recovered by an application. Furthermore Checked exceptions are required to be caught.
ClassNotFoundException
NoSuchMethodException
InterruptedException
Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the runtime of the program. Unchecked exceptions are internal to the application and extend the java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions cannot be anticipated and recovered like programming bugs, such as logic errors or improper use of an API. These type of exceptions are also called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by zero etc.
2.Error - An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions.
The exception classes can be explained as well seeing the hierarchy structure:
The java.lang package defines several classes and exceptions. Some of these classes are not checked while some other classes are checked.
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED
ArithmeticException Arithmetic errors such as a divide by zero
- YES
ArrayIndexOutOfBoundsExceptionArrays index is not within array.length
- YES
ClassNotFoundException Related Class not found YES -
IOException InputOuput field not found
YES -
IllegalArgumentException Illegal argument when calling a method
- YES
InterruptedExceptionOne thread has been
interrupted by another thread
YES -
NoSuchMethodException Nonexistent method YES -
NullPointerException Invalid use of null reference
- YES
NumberFormatException Invalid string for conversion to number
- YES
As you have come to know that exceptions are Objects that means an object is thrown when you throw an exception. Moreover only those objects could be thrown whose classes are derived from Throwable.
It is interesting to note here that the objects of your own design could also be thrown provided that they should be the subclass of some member of the Throwable family. Also the throwable classes which are defined by you must extend Exception class.
55
Handling Exceptions in java It is done using five key words try, catch, throw, throws, finally
try { // statements that may throw exception }
catch( Exceptiontype-1 e) { // statements to handle } catch( Exceptiontype-2 e) { // statements to handle }
finally { // clean up code or exit code(optional) }
The code in the finally block always gets executed regardless of what happens with in the try block. It is used to close files, data base connections , Sockets etc. When exception occurs the method may instantiate an exception object and hand it to the run time system to deal with it.
The exception object carry the following
1. Type of exception - its class 2. Where it occured - stack trace 3. Context information - message and state
The arguement type in the catch clause is from throwable class or one of its subclasses. Once an exception is thrown , the block from where it is thown expires and control can not return back to the throw point.
Java uses a termination model of handling exception rather than resumption model.
56
Throwable class :: It is the super class in the hierarchy, under java.lang.Object. An exception object is an instance of throwable class or any of its sub class.
The Throwable class provides a set of methods apart from various constructors
Throwable() : Throwable(String message) :
getMessage() : retuns the message from the object or null printStackTrace() : print the stack trace
A stack Trace is a list of methods excecuted in sequence that lead to the exception.
Example 46 ::
public class Divide { public static void main(String args[]) { System.out.println("prog starts here.."); int a,b,c;
try { a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b; System.out.println("c="+ c); } catch ( NumberFormatException e) { system.out.println("Invalid argumets"); }
catch ( ArithmeticException e) { system.out.println("Second Arg can not be zero"); }
catch ( ArayIndexOutOfBoundsException e) {
57
system.out.println("pass proper args"); } System.out.println("program ends here.."); } } Order of Catch Blocks ::
The order of catch blocks are important when there are multiple catch blocks. The exception subclasss must come before any of its super class. Otherwise the subclass exception never gets executed.
Example 47 : incorrect ordering of Exception
public class Divide { public static void main(String args[]) { System.out.println("prog starts here.."); int a,b,c;
try { a = Integer.parseInt(args[0]); b = integer.parseInt(args[1]); c = a/b; System.out.println("c="+ c); } catch ( Exception e) { System.out.println("It is " + e"); }
catch ( ArithmeticException e) { System.out.println("Second Arg can not be zero"); } System.out.println("program ends here.."); } }
Hence it is improtant to handle right exception in the right context. 58
Nested try statements ::
Each time a try in entered , the context of the Exception is pushed on to the stack. If an inner try does not have a catch for an exception, the stack is unwound and catch belonging to next try is inspected for a match.
Example 48 : Demo nested try
public class Divide { public static void main(String args[]) { System.out.println("prog starts here.."); int a,b,c;
try { a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]);
try { c = a/b; System.out.println("c="+ c); } catch ( ArithmeticException e) { System.out.println("Sec.Arg cannot be zero"); } }
When an exception can occur in a method, then it is supposed to be handled, or atleast explicitely warn the potential callers about its possibility. This is done using a throws clause in the method declaration so that it can be passed to a different method in the call stack. void Divide( ) throws Exception-A, Exception-B {
}
Example 49:: demo of throws
public class Testthrows { public static void main(String args[]) { int i; int n=args.length; try { for( i=0;i<n;i++) dispnames(args[i]); } catch ( ClassNotFoundException e) { System.out.println("not found " + e); } } static void dispnames(String s) throws ClassNotFoundException { Class c = Class.forName(s); System.out.println("class name " + c.getName()); } }
The Keyword " throw " ::60
Exceptions are thrown by run time. But they can even be thrown by using a throw statement.
throw < Exception Object > The Exception object is an object of class Throwable or any of its subclass. In a specific case where an instance of Exception object is to be thrown, it takes the form as throw new < Exception Object >
Example 50 :: demo of Throwtest
public class Testthrow { public static void main(String args[]) throws Exception { int i1 = 15; int i2 = 20; if (i1 > i2) throw new Exception("First numb can not be more"); else System.out.print("ok"); } } Throwing custom (user defined) Exception ::
Usefull to handle business specific error conditions.For Ex, while withdrawal from bank, an Exception MinBal may be created. Such Exceptions are placed as a subclass of Exception under Throwable class. They can be created using any method as below
1. Throwable Uexcep = new Throwable( );
2. Throwable Uexcep = new Throwable("message"); 3. class Uexcep extends Exception { public Uexcep() { ... } public Uexcep(String s)
61
{ ... } } It is thrown by using keyword throw. It is also possible to override the methods such as getmessage(), toString() etc.
public Testcustom { public static void main(String args[]) { int sAges = { 21,12,18,-5,45}; int i, n=sAges.length; try { for( i=0; i<n; i++) testAges(sAges[i]); } catch ( invalidAgeException e) { system.out.println( e.getMessage() ); } catch ( youngAgeException e) { System.out.println( e.getMessage() ); } }
static void testAges(int a) throws invalidAgeException, youngAgeException { if (a < 0) throw new invalidAgeException(a); if (a <=15) throw new youngAgeException(a,"java"); if (a > 40) throw new AgeException("Retire. say no to java"); System.out.println("you are allowed to learn!"); } }
Rethrowing an Exception ::
63
An exception that is caught can once again be rethrown and can be handled again. The try block just above the rethrown statement will catch this object.
It is used to propagate an exception.It has no special syntax.
Example 52 : Demo of rethrowing exceptions
public class Rethrowtest { public static void main(String args[]) { System.out.println("prog starts here.."); int a,b,c;
Jjava provides a method getMessage() method that is used with an object of the Exception class to print errors to debug the process. Instead of this this method we can get more information about the error process if we use print a stack trace from the exception using the printStackTrace() method that is the method of the Throwable class and prints the stack trace to the console and provides the line numbers of statements that called the methods in the current stack.
ASSERTIONS ( DESIGN BY CONTRACT ) :: They can be used to test the assumptions made by the programmer and create software according to user requirements
Assertions are three types 1. pre condition : Application must satisfy before calling an external component 2. post condition : Application must satisfy this after the execution of the external component 3. invariant : Application must always satisfy this condition
Exceptions test abnormal conditions where as Assertions test the conditions assumed by the programmer.
Example 53 : Demo Assertions public class Tester { public static void main(String args[]) { Tester d = new Tester( ); d.check(5,0); } void check(int a, int b)
{ assert b!=0: "the value b can not be zero"; double c = a/b; System.out.println("c="+c); } }
compilation : javac -source1.4 Tester.java
running : java -ea Tester
Java.Util Package
Java Utility package is one of the most commonly used packages in the java program. The Utility Package of Java consist of the following components:
collections framework legacy collection classes
event model
date and time facilities
internationalization
miscellaneous utility classes such as string tokenizer, random-number generator and bit array
Here are some of the description of the utility classes of this package:
Data Structure Classes Data Structure Classes are very useful classes for implementing standard computer science data structures: including BitSet, Dictionary, Hashtable, Stack and Vector. The Enumeration interface of java.util package is used to count through a set of values.
Date syst The Date class is used to manipulate calendar dates in a system-independent fashion.
StringTokenizer This StringTokenizer class is used to convert a String of text into its tokens.
Properties The properties table contains key/value pairs where both the key and the value are Strings and the class is used by the System class to implement System properties.
Observer and Observable Classes that implement the Observer interface can "watch" Observable objects for state changes. When an Observable object changes it notifies all of its Observers of the change.
Random-Number Generator The Random Number Generator class is used to generate the random-numbers.
Enumeration The Enumeration interface defines a generic programming interface for iterating through a set of valu
Example 54 :: Demo of a stack class
// Demonstrate the Stack class.import java.util.*;class StackDemo {static void showpush(Stack st, int a) {st.push(new Integer(a));System.out.println("push(" + a + ")");System.out.println("stack: " + st);}static void showpop(Stack st) {System.out.print("pop -> ");Integer a = (Integer) st.pop();System.out.println(a);System.out.println("stack: " + st);}public static void main(String args[]) {Stack st = new Stack();System.out.println("stack: " + st);showpush(st, 42);showpush(st, 66);showpush(st, 99);showpop(st);showpop(st);showpop(st);try {showpop(st);} catch (EmptyStackException e) {
68
System.out.println("empty stack");}}}
Example 55 :: Demo of a Date class
// Show date and time using only Date methods.import java.util.Date;public class DateDemo {public static void main(String args[]) {// Instantiate a Date objectDate date = new Date();// display time and date using toString() System.out.println(date);// Display number of milliseconds since midnight, January 1,//1970 GMTlong msec = date.getTime();System.out.println("Milliseconds since Jan. 1, 1970 GMT = " +msec);}}
Chapter 6
Collections
69
Java provides the Collections Framework. In the Collection Framework, a collection represents the group of the objects. And a collection framework is the unified architecture that represent and manipulate collections. The collection framework provides a standard common programming interface to many of the most common abstraction without burdening the programmer with many procedures and interfaces. It provides a system for organizing and handling collections. This framework is based on:
Interfaces that categorize common collection types. Classes which proves implementations of the Interfaces.
Algorithms which proves data and behaviors need when using collections i.e. search, sort, iterate etc.
Following is the hierarchical representation for the relationship of all four interfaces of the collection framework which illustrates the whole implementation of the framework.
During the designing of a software (application) it need to be remember the following relationship of the four basic interfaces of the framework are as follows:
The Collection interface which is the collection of objects. That permits the duplication of the value or objects.
Set is the interface of the collections framework which extends the Collection but forbids duplicates.
An another interface is the List which also extends the Collection. It allows the duplicates objects on different position because it introduces the positional indexing.
And Map is also a interface of the collection framework which extends neither Set nor Collection.
Some interfaces and classes of the collection framework are as follows:
HashSet ClassTreeSet ClassArrayList ClassLinkedList ClassHashMap ClassTreeMap ClassVector ClassStack Class
Advantage of the Collections Framework:
The collections framework offers developers the following benefits:
It increases the readability of your collections by providing a standard set of interfaces which has to be used by many programmers in different applications.
It makes your code more flexible. You can make the code flexible by using many interfaces and classes of the collection framework.
It offers many specific implementations of the interfaces. It allows you to choose the collection that is most fitting and which offers the highest performance for your purposes.
This collection is a framework supported in java.util package. They are used to group elements in various ways. The framework has a set of interfaces, and some implementations to manipulate collections. Collection framework has many interfaces such as collection, Map, Iterator Collection classes ::
There are standard collection classes that implement collection interface.
AbstractCollection : implement Collection interface. It is used to organize a collection which can not be modified.
AbstractList : Extends AbstractCollection, and implement the List interface. It can access data randomly using an index value.
AbstractQueue : Extends AbstractCollection and impl parts of the queue interface.
AbstractSequentialList : Extends AbstractList into sequential LinkedList : Extends AbstractSequentialList where each element knows where is the next
AbstractSet : Extends AbstractCollection and imple the Set interface HashSet : Extends AbstractSet and imple the Set interface. It is used to create a collection and store it in a hash table. Every collection has a unique hash code. The type of storing is called hashing. Elements may be stored in any order and it does not gurantee order. TreeSet : Extends AbstractSet to implement a set stored in tree form. The elements are stored in a tree structure
Map classes : AbstractMap : Implement the Map interface HashMap : It extends the AbstractMap using a hash TreeMap : It extends AbstractMap using a tree
Apart from these , we see Arrays, Vector, Stack, Hashtable, Dictionary, properties, and other classes which are not technically members of this collection framework.
Example 56 : Demo of array class
import java.util.*; class arrays {
72
public static void main(String args[]) { int a[] = new int[10];
for(int i = 9; i > 0; i--) array[i] = -i;
for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println();
Arrays.sort(a);
for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println();
System.out.print("Found -5 at position " + Arrays.binarySearch(a, -5)); } }
Example 57 : Demo of Vector class
A Vector class is similar to ArrayList except that Vector class is synchronized. Multiple threads can not access it simultaneously. It implement the dynamic array. It predates collection framework. It has been rewritten to be compatible with collection framework
import java.util.*; class Testvector { public static void main(String args[]) { Vector v = new Vector(5); System.out.println("Capacity: " + v.capacity()); v.addElement(new Integer(10)); v.addElement(new Integer(11)); v.addElement(new Integer(22)); v.addElement(new Integer(33)); v.addElement(new Integer(44));
output : capacity : 5 capacity : 10 size : 7 First item 0 Last item 3.14 Found a 3 10 11 22 33 44 3.14 3.14 Example 58 : Demo of ArrayList ( Dynamic and can grow )
It holds only the objects, and it can grow or shrink at run time. import java.util.*; class arraylist { public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();74
al.add("Red");al.add("Blue");al.add("Yellow");
al.add(1, "White");
System.out.println("Using the add method");System.out.println(al);
al.remove("White");System.out.println(al);
String l = al.get(1); System.out.println(l);
System.out.println("Using the Iterator interface");String s;
Iterator e = al.iterator();
while (e.hasNext()) {
s = (String)e.next();System.out.print(s);
} }}
75
Example 59 : Demo of linkedlist import java.util.*; class linkedlist {
public static void main(String args[]){LinkedList<String> ls = new LinkedList<String>();
Example 60 : Demo of HashSet class It is set of unique elements, and it uses a hash for storing data. As it uses hash methods such as add, remove, size etc and they take same amount of time. No gurantee of order of storage.
import java.util.*; class hashset {
public static void main(String args[]){HashSet<String> h1 = new HashSet<String>();
h1.add("Red");h1.add("Blue");h1.add("Green");
System.out.println(h1);
int s = h1.size() ; System.out.println(s); if( h1.contains("Red")) System.out.print("Red present" );
} }
Example 61 : Demo of looping over all elements in a list ( Iterator )
import java.util.*; class iterator {
public static void main(String args[]){LinkedList<String> l = new LinkedList<String>();
l.add("Item 0");l.add("Item 1");l.add("Item 2");
Iterator<String> it = l.iterator();
77
while(it.hasNext()) {
System.out.print(it.next()); }
} }
Example 55: Demo of ListIterator It can Loop over in both the directions import java.util.*; class listiterator { public static void main(String args[]) {
Hash Maps allow the data to be stored as key/value pairs where key,value are objects. Map can be indexed with strings instead of numbers. On such Maps it is possible to access elements using strings or search them using string value. import java.util.*; class hashmap { public static void main(String args[]) { HashMap<String, String> hm = new HashMap<String, String>();
hm.put("Item 0", "Value 0");// to add key,value pair to map hm.put("Item 1", "Value 1"); hm.put("Item 2", "Value 2"); hm.put("Item 3", "Value 3"); Set s = hm.entrySet();// get corresponding set
System.out.print(hm.get("Item 0"));//search for corresponding value } }
79
Example 63 : Demo of Hashtable class
It imple the interfaces such as Map,Clonable,Serializable. It is used to store values, in the form of map key with a value. The "key" should implement the hashcode, and equals method to store and retrieve values in a hashtable. It was how maps were implemented before collection framework.
import java.util.*; class Testhashtable { public static void main(String args[]) { Hashtable<String, String> ht = new Hashtable<String, String>();
while(e.hasMoreElements()) { String s = (String) e.nextElement(); System.out.println("key " + s + "/" + "Val" + ht.get(s)); } } }
output : key C2 / val Chouhan key A4 / val Anuj ...e t c...
80
Example 64 : Demo of Hashtable class import java.util.*; class Testhashtable { public static void main(String args[]) { Hashtable<String, Integer> ht = new Hashtable<String, Integer>(4);
class TestMango { public static void main (String args[])
{ Mango ap;
System.out.println("Here are all Mango constant:"); Mango allmangos[] = Mango.values();
for(Mango a : allmangos) System.out.println(a);
System.out.println();
ap = Mango.valueOf(" Kesar"); System.out.println("ap contains"+ap); } }
82
Chapter 7
Multi Threading
Multithreading is a concept, where by it is possible to achieve concurrent execution of multiple units of a single program. A program in java can have multiple flow of controls and each flow of control is nothing but a small unit of execution, known as a thread. Thus a thread can run in parallel to the other threads.
In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor. For Example, When you use a word processor you perform a many different tasks such as printing, spell checking and so on. Multithreaded software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
For example, look at the diagram shown as:
In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread.
Advantages of multithreading over multitasking :
Reduces the computation time. Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than between processes.
A Thread runs inside a process and a process can contain one or more threads. Multithreading allows a program to do more than one task at a time. This means that one process can have a thread that performs a calculation, another thread that performs a service, and so forth.
A thread is not a complete program by itself, and can not run on its own. However, each thread has a begining, and an end, and a sequential flow of execution at a single point of time.
At any given point of time within the run time of the program, only one thread will be executed by the processor. The CPU time will be divided into slices, and it switches between threads and runs so fast that it appears as if all threads are running at the same time.
Differences between multiprocesing and multithreading :
Both fall in the category of Multitasking. They differ in the level at which concurrency is done. Concurrent processes in Multiprocesing have their own separate address space and hence they can not access memory or files of other processes.
Threads share resources like memory space, opened files. Though they are running seperately, they also work together to form a greater unit. It is better as a programming practice , to identify different parts of a program that can perform in paralell, and implement them into independent threads. In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime
Main Thread
When any standalone application is running, it firstly execute the main() method which runs in a thread, called the main thread. If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. The main() method execution can finish, but the program will keep running until the all threads have completed its execution.
Creating Threads
Thread can be implemented through any one of two ways:
Extending the java.lang.Thread Class Implementing the java.lang.Runnable Interface
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
1. Extend the java.lang.Thread Class. 2. Override the run( ) method in the subclass from the Thread class to define the code executed by
the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.
The following program demonstrates a single thread creation extending the "Thread" Class:
class MyThread extends Thread{
String s=null;
MyThread(String s1){ s=s1; start(); } public void run(){ System.out.println(s); }}public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread started...."); }}
85
Example 66 : Demo of creating a thread by extending Thread class
class SampThread extends Thread { public Sampthread(String name) { super ( name ); }
public void run() { System.out.println("Now in: " +Thread.currentThread() );
for(int i = 0; i<=5 ; i++) System.out.print(" " + i); } } public class Testthread { public static void main( String args[]) { SampThread t = new SampThread("First");
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
The following program demonstrates the thread creation implenting the Runnable interface:
class MyThread1 implements Runnable{ Thread t; String s=null;
MyThread1(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); }}public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); }}
However, this program returns the output same as of the output generated through the previous program.
There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:
1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this.
2. The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive.
87
Example 67: Demo of threads implementing Runnable interface
class SampThread implements Runnable { Thread t;
public SampThread(String name) { t = new Thread(this, name); t.start( ); }
public void run() { System.out.println("Now in :" +Thread.currentThread() );
public static void main( String args[]) { SampThread x = new SampThread("First"); System.out.println("It is:"+Thread.currentThread( )); } }
output : It is : Thread[main,5,main]
Now in: Thread[First,5,main]
0 1 2 3 4 5
88
Thread Life-cycle ::
During the life time of a thread it can enter into 5 states and it can move from one state to other in various ways.
1. Newborn 2. Runnable 3. Running 4. Blocked 5. Dead
1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. It will be in this state until
It dies It is blocked for IO It calls sleep(), wait(), yield() It is preempted by a higher priority thread Its time slice expires
4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. A Thread enter into this state when It calls sleep(), suspend(), wait() . It calls IO, or It is waiting for the monitor
Different states implementing Multiple-Threads are:
As we have seen different states that may be occur with the single thread. A running thread can enter to any non-runnable state, depending on the circumstances. A thread cannot enters directly to the running state from non-runnable state, firstly it goes to runnable state. Now lets understand the some non-runnable states which may be occur handling the multithreads.
1 Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread. static void sleep(long millisecond) throws InterruptedException
2 Waiting for Notification – A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread. final void wait(long timeout) throws InterruptedException
final void wait() throws InterruptedException
3 Blocked on I/O – The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources.
4 Blocked for joint completion – The thread can come on this state because of waiting the completion of another thread.
5 Blocked for lock acquisition – The thread can come on this state because of waiting to acquire the lock of an object.
Methods of Thread class ::
Methods that can be applied apply on a Thread:
Some Important Methods defined in java.lang.Thread are shown in the table:
Method Return Type
Description
90
getName( ) String Retrieve the name of the thread object or instance. start( ) Void Start the thread by calling its run method.
run( ) Void This method is the entry point to execute thread, like the main method for applications.
sleep( ) Void Suspends a thread for a specified amount of time (in milliseconds). isAlive( ) Boolean This method is used to determine the thread is running or not.
interrupt( ) void The method interrupt the threads on which it is invoked.
yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
join( ) void This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.
wait(), notify(),notifyAll() :: They are the methods of an object class. When a thread calls wait() , it enter into a blocked state. (i.e Wait queue). It becomes ready only when another thread, associated with that object gives a call notity(). All threads waiting for a given object become ready if the call is notifyAll()
yield() : If a thread is CPU intensive, it may prevent others to run. To Avoid this happening , the thread may call yield() , to allow others to get a chance. when yield() is called the thread moves to runnable state. Example 68 :: demo of thread methods
public class SetThreadName {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Main thread's original name " + t.getName() );t.setName("Gaint");System.out.println("Main thread's name is now " + t.getName() );
} }output : First thread here.. Third thread here.. Second thread here.. main thread here ... Second thread here.. First thread here..
..... First thread ending Third thread ending Second thread ending main thread here... main thread here... .. . . join() & isAlive() methods: The following program demonstrates the join() & isAlive() methods:class DemoAlive extends Thread { int value;
public DemoAlive(String str){ super(str); value=0; start(); }
public void run(){ try{ while (value < 5){ System.out.println(getName() + ": " + (value++)); Thread.sleep(250); } } catch (Exception e) {} System.out.println("Exit from thread: " + getName());
93
}}
public class DemoJoin{
public static void main(String[] args){ DemoAlive da = new DemoAlive("Thread a"); DemoAlive db = new DemoAlive("Thread b"); try{ System.out.println("Wait for the child threads to finish."); da.join();
if (!da.isAlive()) System.out.println("Thread A not alive.");
db.join();
if (!db.isAlive()) System.out.println("Thread B not alive."); } catch (Exception e) { } System.out.println("Exit from Main Thread."); }}
Example 70 : Demo of other methods join ( ), isAlive()
A thread calls join () method when it must wait for another thread to complete its task.
First ending Second ending Third ending First alive? false Second alive? false third alive? false
Thread priority ::
When a new thread is created its priority is equal to the creating thread priority. Every java thread has a priority between 1 and 10 and by deafult each thread is given a normal priority 5. The constants defined in the thread class are Thread.MIN_PRIORITY 1 Thread.MAX_PRIORITY 10 Thread.NORM_PRORITY 5 The methods setPriority(), getPriority() can be used to handle priority. This priority is used by the scheduler to allocate CPU time.
Some java systems support time slicing. It it is available then the sheduler ensures that several threads of equal priority get executed for a quantum time in a round robin fashion. Low priority thread never runs as long as there is a runnable high priority thread.
The scheduling is also preemptive. That is higher thread, preempts the lower one.
Example 71 : Demo of priority
class Counter implements Runnable {
Thread t;int c = 0;boolean goflag;
public Counter(int p) {
t = new Thread(this);t.setPriority(p);
}96
public void start() {
goflag = true;t.start();
}public void run()
{while (goflag) c++;
}
public void end() { goflag = false; } } public class PriorityDemo { public static void main(String args[]) {
Counter t1 = new Counter(Thread.NORM_PRIORITY + 2); Counter t2 = new Counter(Thread.NORM_PRIORITY + 1); Counter t3 = new Counter(Thread.NORM_PRIORITY - 1);
When more than one thread has to use a shared resource, java finds a way of ensuring that only one thread uses the resource at one point of time, and this is called synchronization. Java uses the concept called monitors(Semaphores). Monitor refers to portion of the code in a program related to a resource or data that can be occupied by only one thread at a time. Sucha region is also called critical section.
The monitor holds an exclusive lock, that can be owned by only one object at a time. It allows only one thread to execute a synchronized method. When the execution is done, the lock on the object is opened, and the monitor alows the highest priority thread asking for it, to proceed.
When a thread calls , a non static sync method, the thread acquires a lock on that object. The other threads calling the method enters into a wait state. If a thread calls a static sync method, other threads are free to call non static sync methods on the same object.
98
Synchronized methods ::
Methods can be synchronized using the following syntax
Shared sh1 = new Shared();CustomThread t1 = new CustomThread(sh1, "one");CustomThread t2 = new CustomThread(sh1, "two");CustomThread t3 = new CustomThread(sh1, "three");
try {t1.join();t2.join();t3.join();
}
catch(InterruptedException e) { } }
} output : Starting one starting three starting two ending three ending two endig one
public void run() { synchronized (sh) { sh.doWork(Thread.currentThread().getName()); }
} }
public class SynchDemo2 {
public static void main(String args[]) {
Shared sh1 = new Shared();
CustomThread t1 = new CustomThread(sh1, "one");CustomThread t2 = new CustomThread(sh1, "two");CustomThread t3 = new CustomThread(sh1, "three");
try {t1.join();t2.join();t3.join();
}
catch(InterruptedException e) { } }
}
output: Starting one ending one starting two ending two starting three
103
endig three
Dead locks ::
When two or more threads are waiting for locks to be freed , and the locks will never be freed. For example one thread of A tries to access the sync method of B, and B tries to access the sync of A then they will enter into Deadlock situation.
It occurs if the programmer is not carefull while writing the sync methods.
Deamon Threads ::
It is a thread that runs only to serve other threads. It runs in the background, when CPU time is available. For Ex in java garbage collector is deamon thread.
A thread can be made a deamon, by calling setDeamon(true) method. To find whether a thread is deamon or not isDeamon() method can be used. A deamon can create only a Deamon thread.
Communication among Threads:: (inter thread comm)
It is achieved by using the Object class methods such as wait(), notify(), notifyAll(). They are final methods of object class and can be called only within a sync code Example 75 : demo of inter thread communication
synchronized void put( int n ) { this.n = n; system.out.println(" put :" + n); } }
104
class Producer implements Runnable { Queue q;
Producer( queue q) { this.q = q; new Thread(this,"producer").start(); }
public void run( ) { int i = 0; while (i < 10 ) { q.put(i++); } } }
class Consumer implements Runnable { Queue q;
consumer( queue q) { this.q = q; new Thread(this,"consumer").start(); }
public void run( ) { int k = 0; while (k < 10 ) { q.get(); k++; } } }
public class Democomm105
{ public static void main( String args[]) { Queue sample = new Queue( ); Producer p = new Producer(sample); consumer c = new consumer(sample); system.out.println("Done"); } }
output :: put : 0 Got : 0 Put : 1 Got : 1 put : 2 Got : 2 put : 3 Got : 3 Put : 4 Got : 4 put : 5 Got : 5 put : 6 Got : 6 Put : 7 Got : 7 Got : 7 Got : 7 put : 8 put : 9 Got : 9
Not corect result. After producer put 7, the consumer started and got the same 7 three times in a row. Then producer resumed and puts 8, 9 simultaneously and consumer consumes 9 Example 70 : inter thread communication - correct results
synchronized void put( int n ) { if (flag) { this.n = n; system.out.println(" put : " + n); flag = false; notify( ); } else { try { wait( ); } catch ( Exception e) { } } } }
class Producer implements Runnable { Queue q;
Producer( queue q) { this.q = q; new Thread(this,"producer").start(); }
public void run( ) { int i = 0; while (i < 10 ) { q.put(i++); } } }
class Consumer implements Runnable {
107
Queue q;
consumer( queue q) { this.q = q; new Thread(this,"consumer").start(); }
public void run( ) { int k = 0; while (k < 10 ) { q.get(); k++; } } }
public class Democomm { public static void main( String args[]) {
Queue sample = new Queue( ); Producer p = new Producer(sample); consumer c = new consumer(sample); system.out.println("Done");
} }
output : put : 0 Got : 0 Put : 1 Got : 1 put : 2 Got : 2 put : 3 Got : 3 Put : 4 Got : 4 put : 5 Got : 5 put : 6 Got : 6 Put : 7 Got : 7 put : 7 Got : 7 put : 8 Got : 8 put : 9 Got : 9
108
Synchronizing classes :: Semaphore, CyclicBarrier, CountDownLatch, Exchanger are all classes added to java to act as synchronizers. Each of them have methods that the threads may call.
Concurrent programming :: While writing multithreaded programs, some of the issues that may create diffculties are
1. No way to back off from an attempt to acquire a lock that is already held or give up after waiting for a specified time, or cancel a lock attempt after an interrupt.
2. Sync is done in block structured fashion. No way to acquire lock in one method and release it in another.
Thre are some drawbacks in wait(), notify() and they are enhanced with new mechanisms, and placed as a part of java.util.concurrent package. This package provide all the standard concurrency utilities. using this package, helps scalable, easy to write and maintainableapplication developement but programmer is responsible to see that the applications a re free from deadlock, CPU starvation.
Chapter 8
Packages
It is a mechanism for grouping classes, interfaces and sub packages. The java API itself is implemeted as a group of packages. 1. To organize the classes into groups and units 2. To reduce problems with conflicts in names 3. To provide protection to members and methods 4. To identify classes.
Package categories in Java
Java supports two types of packages as shown below in the hierarchy structure:
Java packages can be categorized in the hierarchy structure shown as:
Packages in the Java language begin with "java" or "javax" as we can found in both hierarchy structure shown above. Note that, the package "java" also has subpackages in which the package "awt" is further has a subpackage called "event" that is imported to access classes and interfaces to handle the events fired on the awt-component in a program.
110
Java has a hierarchial naming convention for packages, known as dot ( .) notation.
For Ex, the JDK has a package called java at top level, and the next level includes names such as lang, io, awt, util etc
The dot reflects in the directory organization. Each level represents a smaller and more specific grouping of classes.
Accessing classes in a package:: Two ways 1. import statement 2. Use fully qualified approach ( no import needed)
Ex : 1 import packagename.*; import packagename.classname; or 2 java.awt.Font f = new java.awt.Font( );
A) The import, imports all public classes in the package, but not from sub packages. To do that explicite import of each sub package is needed.
B) import line comes after package definition line.
C) To resolve name conflicts of a class from more than one package, use full pack name while qualifying the object
Ex : java.util.Date d1 = new java.util.Date(); java.sql.Date d2 = new java.sql.Date();
Create Your Own Package
The package to which the source file belongs is specified with the keyword package at the top left of the source file, before the code that defines the real classes in the package. Suppose we have a source file called "HelloWorld.java" and we want to put this file in a package "mypackage" then the following code is written as shown in the given example:
package mypackage;class HelloWorld { public static void main (String args[]) { System.out.println("Hello World!"); }}
111
Before running this program make sure to do the following things:
1. Create a directory "mypackage" . 2. Save the source file as "HelloWorld.java" in the created directory.
3. Set the class path as set CLASSPATH = .; C:\;
4. Go to the "mypackage" directory and compile the program as
C:\mypackage>javac HelloWorld.java
5. Run the program.
If you try to run this program, you will get the following exceptions (or error):
This is, because the class "HelloWorld" belongs to the package "mypackage". So If we want to run it, we have to tell the JVM about its fully-qualified class name as (mypackage.HelloWorld) instead of its plain class name (HelloWorld). Fully-qualified class name is the name of the java class that includes its package name.
Now run the program as shown:
C:\mypackage>java mypackage.HelloWorldHello World!The ways to Compile the Package:Compile in the same directory: If you have a hierarchy of packages to compilation then you can compile the package without going to the subdirectories and specifying the complete directory path with the class . Suppose, you have a hierarchy of packages as " india.mycompany.mainpackage.mypackage" including the class "HelloWorld" then type the following command shown as:C:\javac C:\india\mycompany\mainpackage\mypackage\HelloWord.java
This command will reach to the last subdirectory and compile the class "HelloWorld".
Compile into the Different Directory: On the other hand, if you want to compile the same package available in the hierarchy manner to another directory (location) then syntax is shown as:
This command puts the folder "india" along with its subfolders and the class file "HelloWorld.class" to the new location as D:\myfolder.
How to import a package
There are two ways so that you can use the public classes stored in package. Declaring the fully-qualified class name. For example,
mypackage.HelloWorld helloworld = new mypackage.HelloWorld(); Using an "import" keyword: For example,
import world.*; // we can call any public classes inside the mypackage package
Lets see an example importing the created package into the another program file.
package importpackage;
public class HelloWorld { public void show(){ System.out.println("This is the function of the class HelloWorld!!"); }}
In this program the package "importpackage" is created under the "c:\nisha" directory that will be imported into another program file to call the function of the class "HelloWorld".Now make a program file named "CallPackage" under the "c:\nisha" directory importing the package "importpackage".
import importpackage.*;
113
class CallPackage{ public static void main(String[] args){ HelloWorld h2=new HelloWorld(); h2.show(); }}
Out of the program:
C:\nisha\importpackage>javac *.java
C:\nisha\importpackage>cd..
C:\nisha>javac CallPackage.java
C:\nisha>java CallPackageThis is the function of the class HelloWorld!!
Make sure to the directory structure for this program shown as:
Create Subpackages (i.e. A Package inside another package)
We can also put a package inside an another package. The packages that comes lower in the naming hierarchy are called "subpackage" of the corresponding package higher in the hierarchy i.e. the package that we are putting into another package is called "subpackage". The naming convention defines how to create a unique package name, so that packages that are widely used with unique namespaces. This allows packages to be easily managed. Suppose we have a file called "HelloWorld.java". and want to store it in a subpackage "subpackage", which stays inside package "importpackage". The "HelloWorld" class should look something like this:
package importpackage.subpackage;
public class HelloWorld { public void show(){ System.out.println("This is the function of the class HelloWorld!!"); }}
public void dispTeacher( ) { System.out.println("Name :" + name); System.out.println("Qual :" + qual); } } Example 78 : Demo of packages
/* Testpack.java file store in any directory under which Package college was a subdirectory */
import college.*; public class Testpack {
116
public static void main(String args[]) { Student s = new Student(); Teacher t = new Teacher(); s.setStudent("Preethi", "R10017"); t.setTeacher("Pushkal", "Ph.D"); s.dispStudent(); t.dispTeacher(); } }
During the compile time, when an object is encountered, for its class definition the compiler looks at all imported packages and if finds, it proceeds further with out including any code.
During run time, the interpretor calls a class loader, and this loader loads the corresponding class.
Chapter 9
Java Applets
WWW:: The WWW is a collection of electronic documents that are linked together. These documents are known as web pages and a collection of related web pages is known as web site.
117
A web site resides on a server computer that are located around the world and the information on the WWW is always accessible.
Web Browser: Web browser is a program that is used to access WWW. It allows the users to view the web pages and to navigate betwen them. They are also called universal clients as they are common to the clients for all web based applications
Web Server :It is a server program running on a computer whose purpose is to serve web pages to the other computers when requested. Ex : Apache , IIS, iPlanet
HTML : It is a markup language Used to create documents on WWW. It gives guidelines for displaying information through tags. Tags are enclosed within angular brackets < >.
URL : It is a unique address used to identify each web page or a resource on the internet. It indicates where the page is stored on the net. It is called the internet address of a resource on the WWW. Along with the protocol to access. They are used by browser to connect to a specific server and to get a specific document or page.
Ex : http://www.infosys.com/index.html protocol://ServerDomainName/Path name protocol://ip address/Path Name The URL may contain port to connect to, and also the data typed by the user in the form to be submitted to the application
Ex: http://eshop:8080/shopping/SendData?name = prasad&phone = 25678HTTP :Web browsers and web servers communicate with each other using HTTP protocol. It is a simple protocol, stateless and allows clients to communicate with server. It is an application level protocol and transmit any resources identified by a URL. It is called request/responce based protocol, because the clients sends a request to a server, and the server listen and respond back.
HTTP 1.0 was the original version. The client would initiate and close the connection to the server on each request. The performance is poor because it has to make new TCP/Ip connection for every request.
118
For example if a page index.html is accessed by the client and the page contain 10 image files in its body, the browser has to initiate and close the connection 11 times. The client has to open a new TCP/IP connection and places a request for the resource, and on receipt close the connection and repeat it for each picture to be downloaded.
HTTP 1.1 latest version, and here the connection once established is maintained until the browser is closed. It is called persistent connection. So many requests can occur within a single TCP/IP connection.
APPLETS They are small java programs used in internet computing. They can display graphics, play sounds, accept user inputs, create animation perform arithmetic operations and enable creation of interactive web documents. Applets are used when we need something dynamic to be included in a web page. They are event driven window based java programs.
1. Applets do not use function main() 2. They run inside a web page. 3. They can not read or write any files in the local system 4. They can not run any programs in the local system 5. They are restricted from using libraries of other languages. 6. They can not communicate with any site other than the one that served the web page.
Applets are executed in a web browser, or in a special window called "Appletviewer" provied by the JDK. Browsers allow many applets in a single page where as appletviewer show them in seperate windows.
119
Applet class :: It provide the foundation for creating applets and it is subclassed as shown below.
Image getImage() : Appletcontext getAppletContext() : Once an Applet's ".class" file is created it is uploaded to an ISP or viewed on the local machine, by setting its protection for read.
init() :It is called when the applet is loaded or reloaded for the first time into a browser. It is called only once in the life cycle. The browser calls this method after the constructor of the applet is called.
120
But most of the initilization is done in the init() such as creating helper objects, seting up fonts, images , reading and parsing parameters.
start() :It is called after the init() is completed. It is also called whenever the user leaves a page and returns back. It is called when you minimize and then maximize a page.
Unlike init() it can happen many times through the life cycle.
stop() :It runs when the user leaves the current web page. By default, when the user leaves the web page, or a window minimized, any threads the applet had started will continue running. By using this method we can suspend such threads, and restart them when the applet is viewed again. destroy() :It is called to terminate the applet. It runs either before the applet exits or before the browser exits. It is usefull for cleanup operations such as releasing memory after the applet is removed, killing threads, closing network,database connections or releasing all resources that were initialized during an applets initialization. Paint() :The paint() is used by applet to draw something to the screen. It can be called several times in the life cycle of an applet. It is a method inherited from Component class. It takes one parameter of type Graphics class. When paint() is called, an instance of Graphics class is created by the browser and handed over to the applet.
It gets executed every time the
1 applet is minimized, or maximized, or 2 when the applet is initialized and the browser is placed behind another window on the screen and then brought forward again. 3 Browser window is moved to a different position on screen.
121
Example 81 ::
import java.applet.Applet; import java.awt.*;
public class Appex extends Applet { public void paint(Graphics g) { g.drawString("Hello from Java!", 60, 100); } }
Testing Applets : There are two ways.
1. Using Applet tags in HTML pages and then view the applet through browser window by downloading web page. 2. Using Applet tags in source code as comments to view the the applet with applet viewer. Running in browser window: < html> <head> <title> First Applet </title></head> <body> <applet code = "Appex" width = 200 height = 200> </applet> </body> </html>
to run the applet save the above html file as a webpage and then open it through any browser.
122
Running using Appletviewer : c:\> appletviewer Appex The syntax of an applet tag
codeBase : It specify the directory which is to be searched for the applets .class file. Normally the directory of the HTMl file is searched for the .class file. This will be in the form of a URL. But applets ".class" file need not be in the same host where HTML file is loaded.
Ex : Codebase = http://www.au.ac.in
Then HTML file can be anywhere but ".class", file is searched from the above URL.
getCodeBase(), getDocumentBase() can give the directory of applet codes ".class" file, and HTML document files.
code : It refers to the name of applets, ".class" file. It is relative to the base URL but not absolute URL
Name : It referes to the name of the applets instance It is used by applets to communicate with each other on the same HTML page. the method getApplet() defined under AppletContext interface can be used to get the instance name. width, height : They refer to the size of panel in the browser window.
param : It specify name ,value pairs. The value can be obtained using getParameter() method.
public class Appex extends Applet { public void paint(Graphics g) { g.drawString(getParameter("msg"), 60, 100); } }
Example 84 :: Demo of Console IO
import java.applet.*; import java.awt.*; public class Appex extends Applet { public void paint(Graphics g) { g.drawString("Hello from Java!", 60, 100); System.out.println("Hello from Java!"); } }
u = getDocumentBase(); // get document base msg = "Document base: " + u.toString(); g.drawString(msg, 10, 40); } }
Example 86 :: Demo of image loading
steps : create an image object associate a graphics file with the image object display the image
import java.applet.*; import java.awt.*; public class Appex extends Applet { public void init() { Image p; p = getImage(getCodeBase(),"images/running.gif"); }
public void paint(Graphics g) { g.drawImage(p,0,0,100,100,this); } }
getImage() takes two parameters. A base URL, and a string giving the path or filename in relation to URL.
Example 87 :: Demo of Audio clip
import java.applet.*; import java.awt.*; public class Appex extends Applet {
126
public void init() { AudioClip p; p = getAudioClip(getCodeBase(),"songs/jana.audio"); }
It can be used to get information from the applets execution env. With in an applet once the context is obtained, we can bring other documents into view by showDocument() method.
getCodeBase(), getDocumentBase() can be used to get URL objects of applets byte code, HTML files.
Example 89 : Communication with a browser :
The example below is an applet which request the browser to how another web page. The ShowDemo.java, applet will instruct the browser to display the Samppage.html. For testing we have a html page by name showtest.html which can be viewed by internet explorer.
Component is an abstract class. It provide support for managing events, drawing of components, handling keyboard and mouse inputs, positioning ,sizing windows and painting output.
It is responsible for remembering the current foreground and background colors and font. Methods commonly used are ::
Container::It has additional methods, and allow other components, or container to be nested within it. A container is responsible for laying the position of components by using layout managers. commonly used methods are :
remove() setLayout()
Window:The window class creates a top-level window. A top-level window is not contained within any other objects; It sits directly on the desktop. Generally, you won't create Window objects directly. Instead, its subclass Frame or dialog are used to have window creation.
methods commonly used are : show() hide() addWindowListener( ) Frame:Frame is a subclass of Window and has a title bar, menu bar, borders and resizing corners.
methods :: setSize( ) setTitle( ) Dialog ::
They are the pop up windows which can accept input from the user. They are two types 1. Modal 2. Modeless
Panel::It is subclass of Container. It adds no new methods but simply implements container. Panel is the super class of Applets. When screen output is directed to an applet, it is drawn on the surface of a Panel object. A Panel is a window that does not contain a title bar, menu bar or border. It can not be a top level window. ( When you run an applet using an applet viewer, the applet viewer provides the title and border ).
134
Event Handlers :An event is generated when an action occurs such as mouse click on a button, or enter key pressed on a text field. They are handled by listener classes which implement listener interfaces.
Canvas ::
It is a blank window but not a part of Applet or Frame. It is a drawing surface used for drawing images and graphics operations. ABSTRACT WINDOWING TOOLKIT - UI components
Label :: A text string to label other components Button :: A simple push button. Canvas :: A base class for creating your own controls.
Checkbox :: A combination of check box and radio buttons. Choice :: A drop-down list control. List :: A list box.
Menu :: A drop-down menu from the window's toolbar. Panel :: An area where we group controls, paint images or graphics. Scrollbar:: Horizontal and vertical scroll bars.
TextField:: A single-line text entry field. TextArea :: A multiple-line text entry field
Label ::
Some of the methods defined in the Label class are::
Method Action String getText() Returns a string containing this label's text void setText(String) Changes the text of this label
Example 92 : Demo of Label135
import java.awt.*;
public class LabelTest extends Applet {
Label l1,l2,l3; Font f1;
public void init( ){
f1 = new Font ( "Helvetica" , Font.BOLD, 14); setFont(f1);
public class ButtonTest extends Applet { Button b1,b2;
public void init( ){
136
b1 = new Button ("Rewind");add(b1);
b2 = new Button ("Play");add(b2);
} }
CheckBox ::
Methods
String getLabel() Returns a string containing checkbox's label
void setLabel(String) Changes the text of the checkbox's label
boolean getState() Returns true or false, based on whether the checkbox is selected or not void setState(Boolean state) Changes the checkbox's state to selected (true) or unselected (false)
Example 94 : Demo of Checkbox
import java.applet.*;import java.awt.*;
public class CheckboxTest extends Applet { Checkbox c1,c2,c3;
public void init( ){
c1 = new Checkbox("Shoes");add(c1);
c2 = new Checkbox("Socks", true);add(c2);
c3 = new Checkbox("Shirt");add(c3);
}137
}Example 95 : Demo of Radio box
import java.awt.*;
public class RadioTest extends java.applet.Applet {
CheckboxGroup cg;Checkbox c1,c2,c3;
public void init( ){ cg = new CheckboxGroup ( );
c1 = new Checkbox("Red", cg, false); add(c1);
c2 = new Checkbox("Blue", cg, false); add(c2);
c3 = new Checkbox("Yellow", cg, false); add(c3);}
}
Choice ::
int getItemCount() Gets number of items in the control String getItem(int index) Gets strings at specified index
int getSelectedIndex() Gets index of the currently selected item String getSelectedItem() Gets string representation of Choice
Example 96 : Demo of Choice
import java.awt.*;public class ChoiceTest extends java.applet.Applet { Choice ch;
String getText() gets the text contained.void setText (String text) sets the text.void setEchoChar(char echoChar) Sets the echo character.
Example 97 : Demo of TextField
import java.awt.*;
public class TextFieldTest extends java.applet.Applet {
Label l1,l2; TextField t1,t2;
public void init( ){ l1 = new Label("name"); add(l1);
t1 = new TextField(20); add(t1);
l2 = new Label("password"); add(l2);
t2 = new TextField(20);
t2.setEchoChar('*'); add(t2);
139
} }
TextArea::
int getColumns() Returns the number of columns in the TextArea int getRows() Returns the number of rows in the TextArea insert (String text, int index) inserts text at the specified position. void replaceRange(String text, int r, int c) Replaces the existing text from the indicated start to end positions with text specified.
Example 98 : Demo of TextArea
import java.awt.*;
public class TextAreaTest extends java.applet.Applet { String letter = " Java Is simple\n " +
" It is object oriented, \n " + " It is machine independant ";
TextArea ta;
public void init( ){
ta = new TextArea(letter, 10, 45);add(ta);
} }
List ::int [ ] getSelectedIndexs() Gets index of the currently selected item String[ ] getSelectedItems() Gets string representation of Choice
ScrollBar::int getValue() Gets current value of Scrollbarvoid setValue(int value) Sets value of Scrollbar to a given value
Example 100 : Demo of Scrollbar
import java.awt.*;public class Scroll extends Applet { Scrollbar b1 = new Scrollbar(Scrollbar.VERTICAL, 10, 1, 1, 100);
public void init( ){
add(b1);}
}
Example 10 1 : Demo of Frame window
import java.awt.*;import java.applet.Applet;
public class FrameTestApplet extends Applet {
Frame w; Label l1, TextField t1;
public void init ( )141
{ // constructs frame with title
w= new Frame (" My New window ");
//sets the layout of frame
w.setLayout (new FlowLayout( ));
l1 =new Label ("Name: "); w.add (l1);
t1 = new TextField (20); w.add (t1);
w.resize (300,200); w.show( );
} }
Example 102 : Standlone programming with GUI
public class Demotest extends Frame { Label l1,l2; TextField t1,t2;
public Demotest( ){ l1 = new Label("Name"); add(l1);
t1 = new TextField(20); add(t1);
l2 = new Label("Password"); add(l2);
t2 = new TextField(20); t2.setEchoChar('*'); add(t2);
142
resize(200,200); show();
}
public static void main(String args[]) { Demotest s; s = new Demotest(); } }
Layout Managers
Flow Layout ::
It arranges components horizontally from left to right like words in a page. It is default for Panels. If the components do not fit in one row then a new row is started.
Border Layout ::
It arranges components around the four borders of a container. The four sides are referred to as North, South, East and West. The middle area is called the center. Every Frame has BorderLayout, as its default layout manager.
For containers other than a Frame, to install a BorderLayout, we do the following:
setLayout( new BorderLayout() )
Grid Layout ::It is used to set a matrix of components in a rectangular grid along a number of rows and columns. Each cell in the grid is the same height as the other cells, and each width is the same width as the other cells.
setLayout(new GridLayout (3,4));
Card Layout ::
It presents different screens to a user based on a stack of cards. One can flip to the first, second or last card using methods defined by CardLayout. Each container in the group is card.
A name is given to each card and we can display a card by using a method show( ) as :
143
show( container of all cards, name of card);
We can add a container to a card by add() method add(name , container); GridBag Layout::
It is similar to the GridLayout layout manager because the Panel is divided into a grid of cells with rows and columns. In GridBagLayout, however the individual components,can be resized by assigning weights. The helper class GridBagConstraints holds all the information needed by the GridBagLayout class to properly position and size each UI component. The following is a list of the GridBagConstraints member variables and their default values that are used to define UI components placement:
The constraints can be created by the GridBagConstraints object using its constructor and set the following constraints for the individual components using setConstraints( ) method.
import java.awt.*;public class DemoCard extends Applet {
CardLayout ca = new CardLayout( );Label [ ] lb = new Label[5];
146
// An array of Labels to display as static text on each card
public void init( ){
// Assign the static text to each element in the array
lb[0] = new Label("Personal Details");lb[1] = new Label("Financial Details");lb[2] = new Label("Contact Details");lb[3] = new Label("Dispatch Details");lb[4] = new Label("Credit Details");
setLayout(ca);
for (int i = 0; i < 5; i++){
// Add each element to the Card Layout.
add("Card " + i, lb[i]);
//Display each element of the Card on to the applet.
ca.show(this,"Card " + i);}
} }
Example 107 : Demo of grid bag layout
public class Demogridbag extends Applet {
Button b1,b2,b3,b4,b5,b6;
GridBagLayout gl; GridBagConstriants gbc;
public void init( ) {
b1 = new Button("Java");b2 = new Button("Oracle");b3 = new Button("XML");b4 = new Button("JScript");
147
b5 = new Button("J2EE"); b6 = new Button("C++"); gl = new GridBagLayout( ); gbc = new GridBagConstraints( );
class Canarea extens Canvas { public void paint( Graphics g) { setForeGround(color.green); g.fillOval(30,0,80,80); g.drawString("hello Java",50,100); } }
public class DemoCan extends Applet { public void init( ) { Canarea c = new Canarea( ); setBackground(color.red); c.setSize(200,200); c.setBackground(color.blue); c.setVisible(true); add(c); } }
Example 109 : Panel demo
public class Demopan extends Frame { Panel p, sp1, sp2; public Demopan( )
public static void main(String args[]) { Demopan s; s = new Demopan(); } }
150
Chapter 11
Delegation Event Modelling
When an event occurs programmer has 3 options
1. Ignore the event 2. Let the component manage the event 3. Delegate its handling to some other object called Listener According to delegation modeling, For example when a Button click occurs , then the listener if connected can listen to the event, and then invoke a method action performed.
Button click | | Listener listens,and creates an ActionEvent object | | Passes this object to actionPerformed( ) method
Control Listener Methods and Events received -------- ------------- ------------------------------------------
Button ActionListener actionPerformed(ActionEvent e) List Menultem TextField
Checkbox ItemListener itemStateChanged(ItemEvent e) Choice List Checkbox MenuItem
It occurs, 1. When a button is clicked 2. When a menu item is selected 3. When a list item is double clicked 4. When enter key pressed in text field method :: getSource( ) gives the source that made this event
ItemEvent :: It occurs, 1. When a check box is select/deselected 2. when a choice item is select/deselected 3. When a list item select/deselected 4. Whena checkbox menu item select/deselected method :: getItemSelectable( ) gives reference to the item selected component. getItem() gives reference to the item that caused the event
152
AdjustmentEvent :: It occurs,
1. When a scroll bar thumb is moved
method :: getAdjustable( ) gives the object that caused the event getValue() gives the new value TextEvent :: It occurs,
1. When content of text is changed in TextField, TextArea MouseEvent :: It occurs, 1. When user clicks or moves the mouse pointer
method :: getX(), getY() gives x,y screen coordinates of mouse position getClickCount() gives click count for an event
WindowEvent :: It occurs, 1. When a window minimized, opened, activated etc.,
FocusEvent :: It occurs, 1. When a component gains or loses focus KeyEvent :: 1. It is generated by the user during interaction from keyboard
method :: getkeyCode() gives the key code for a given char getKeyChar() gives char defined by a key code
153
Example 111 : Demo Button Events
public class Demobutt extends Applet implements ActionListener {
TextField t1, t2, t3;Label l1,l2,l3;
Button b1,b2; GridLayout gl; public void init() {
gl = new GridLayout(4,2); setLayout(gl);
l1 = new Label("Firstnumb" );add(l1);
t1 = new TextField(10);add(t1);
l2 = new Label("Secondnumb" );add(l2);
t2 = new TextField(10);add(t2);
l3 = new Label("Result " );add(l3);
t3 = new TextField(10);add(t3);
b1 = new Button("ADD");add(b1);b1.addActionListener(this);
b2 = new Button("SUB");add(b2);b2.addActionListener(this);}
public void actionPerformed(ActionEvent e) {
154
if(e.getSource() == b1) {
int p = Integer.parseInt( t1.getText() ) + Integer.parseInt( t2.getText() ); t3.setText( String.valueOf(p) ); }
if(e.getSource() == b2) {
int p = Integer.parseInt( t1.getText() ) - Integer.parseInt( t2.getText() ); t3.setText( String.valueOf(p) ); }
t1 = new TextField();con.gridwidth = GridBagConstraints.REMAINDER;gr.setConstraints(t1, con);add(t1);
} public void actionPerformed(ActionEvent e) { String m = ((Button) e.getSource()).getActionCommand();
t1.setText("You clicked " + m ); } }
Adapter classes ::
They are the classes that have already implemented the event interfaces with empty methods. Then we may override any method of choice as per the need. For Ex. MouseListener has 5 methods that we must implement, but when a MouseAdpater class is used in its place then, we may override only the required methods.
Example 123 :: Demo of inner adapter class
public class Demoapp extends Applet {
String s = "Hello to Java!";
public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { s = "Bye to Java!"; repaint(); } } ); }
public void paint(Graphics g)168
{ g.drawString(s,60,100); }
}
Creating window Applications
Example 124 : Demo frame window
public class TestWin extends Applet implements ActionListener {
Button b1, b2; Demowin wind;
public void init() { b1 = new Button("Display the window"); add(b1); b1.addActionListener(this);
b2 = new Button("Hide the window"); add(b2); b2.addActionListener(this);
wind = new Demowin("Java window"); wind.setSize(300, 200); }
In java there is an abstract class called MenuComponent, for menu related classes. A MenuBar class, implements a menubar which is attached to a frame window
Menu class, implements a single pull down menu, that is attached to a menu bar or other menu.
MenuItem class, implements items that can be selected from a pull down Menu. CheckboxMenuItem class implements menu items, that may be cheked on or off for toggle purpose.
There is a seperate MenuContainer interface providing a set of methods, which are implemented by MenuBar class and Menu class. Frames also implement this class.
172
Example 125 : Demo of Menus
public class Demomenu extends Applet implements ActionListener { Button b1; Testwind menuWindow;
public void init() { b1 = new Button("Display the menu window"); add(b1); b1.addActionListener(this);
menuWindow = new Testwind("SampleMenus"); menuWindow.setSize(200, 200); }
A Dialog class can create a Dialog box. It is a sub class of window class. It will not have menubar, and can not be resized. They are popup windows, and accept input from user and always depend on other windows. Hnece it is always created from an existing window.
There are two types.
Modal :: It does not allow the user to interact with any other window while it is displyed, and it is on top of all
Modeless:: It allow the user to interact with other windows. for Ex a message box displaying the status of installation process, is modeless dialogue as the user can perform other jobs while installation is under progress.
Example 128 : Demo of Dialog Boxes
class mydialogue extends Dialogue implements ActionListener {
setLayout( new FlowLayout( ) ); l = new Label("selected quit option"); add(l); b1 = new Button("OK"); add(b1); b1.addActionListener(this);
180
b2 = new Button("Cancel"); add(b2); b2.addActionListener(this);
} public void actionPerformed(ActionEvent e) { dispose( ); } }
class myFrame extends Frame implements ActionListener
{ myFrame( String title ) { super(title); Menubar mb = new MenuBar( ); setMenuBar(mb);
Menu m = new Menu("File"); MenuItem mi1,mi2;
mi1 = new MenuItem("New"); mi2 = new MenuItem("Quit");
mb.add(m);
mi2.addActionListener(this); }
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mi2) {
mydialogue d = new mydialogue(this, "Demo Dialogue"); d.setVisible(true); dispose();
} }
181
}
public class Demodialogue extends Applet { myFrame f;
public void init( ) { f = new myFrame(" frame window"); f.setSize(300,300); }
public void start( ) { f.setVisible(true); }
public void stop( ) { f.setVisible(false); } }
Example 129 : Demo of mini calculator
class glass extends Panel
{ TextField t1;
glass( ) { t1 = new TextField(20); add(t1); } }
class digits extends Panel { Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
Button bp,bs,bm,bd,bpo,be,bon;182
digits( ) { setlayout( new GridLayout(5,4));
b0 = new Button("0"); add (b0); b1 = new Button("1"); add (b1); b2 = new Button("2"); add (b2); b3 = new Button("3"); add (b3); b4 = new Button("4"); add (b4);
b5 = new Button("5"); add (b5); b6 = new Button("6"); add (b6); b7 = new Button("7"); add (b7); b8 = new Button("8"); add (b8); b9 = new Button("9"); add (b9);
bp = new Button("+"); add (bp); bs = new Button("-"); add (bs); bm = new Button("*"); add (bm); bd = new Button("/"); add (bd); bpo = new Button("."); add (bpo);
Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the internal memory and an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file.
A Stream is an abstraction for the source or destination of data. The source or destination can be anything , disk, memory buffer, network connection.
A Stream will have methods to operate on the data from the source or destination tied with them.
Types of Stream
An Input stream reads data where as an output stream write data. Byte streams read or write bytes where as charcter streams read or write characters.
Stream methods are synchronized and they will wait for the data to be avialable then perform operation, and return. Lowlevel streams work with raw bytes, as stored by the file system andusefull for taking an image of the data stored.
Highlevel streams work with charcter and primitive types , objects and provide meaningful entries for the programmer. It is possible to chain streams to provide new functionality.
Byte Streams
194
They can handle only 8-bit Bytes. They are abstracted by classes InputStream and OutputStream . There are specialized classes derived from above abstract classes ,to handle reading and writing bytes.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below:
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below:
OutputStream is also inherited from the Object class. Each class of the outputStreams provided by the java.io package is intended for a different purpose.
The FileInputStream handles byte oriented inputs from files. The BufferedInputStream can use methods to move backwards in a buffered stream. In a BufferedOuptutStream we dont haver to write data to disk for each byte, but it can buffered and force a flush operation at once.The DataInputStream can handle data in primitive types.
Example 140 : Demo of of FileInputStream
195
import java.io.*; public class DemoTest {
public static void main(String args[]) throws Exception{ FileInputStream f = new FileInputStream ("DemoTest.java");
int len = f.avilable(); System.out.println("Available bytes: " + len); System.out.println("Reading 1/5 of file...."); byte b[] = new byte[len/5];
public static void main(String args[]) throws Exception{byte data[] = "This is a string of text.".getBytes();
FileOutputStream f1 = new FileOutputStream("file1.txt");
for (int i = 0; i < data.length; i++) { f1.write(data[i]);}
FileOutputStream f2 = new FileOutputStream("file2.txt"); f2.write(data);
FileOutputStream f3 = new FileOutputStream("file3.txt"); f3.write(data, 5, 10);
f1.close();f2.close();f3.close();
}}
Example 142 : Demo of DataOutputStream & DataInputStream
They permit reading or writing of primitive data types. After read we have to use methods to convert them to character, or string inorder to understand import java.io.*;public class DemoDataIO { public static void main(String[] args) throws IOException { DataOutputStream out = new DataOutputStream( new FileOutputStream("datas.txt" )); double[] prices = { 9.99, 4.99, 15.99, 3.99 }; int[] units = { 12, 6, 10, 9 }; String[] descs = { "mangos", "oranges ", "apples", "corn"};
197
for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]); out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); }
out.close();
// now read the data from the file
DataInputStream in = new DataInputStream( new FileInputStream("datas.txt"));
double price; int unit; String desc; double total = 0.0;
try {
while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab desc = in.readLine(); System.out.println( price ); System.out.println( unit ); System.out.println( desc ); total = total + unit * price; } } catch (EOFException e) { } in.close(); }
198
}
Character Streams
They support Reader, Writer Abstract classes for reading or writing 16 bit charcter inputs or outputs. These abstract classes have child classes to support operations.
FileWriter f2 = new FileWriter("file2.txt"); f2.write(data); FileWriter f3 = new FileWriter("file3.txt"); f3.write(data, 5, 10); f3.append(" made in java ");
f1.close();f2.close();f3.close();}
}
Example 144 : Demo of BufferedReader
We use this class to create character based stream that reads from a file line by line instead of character by character.
import java.io.*;
public class DemoTest{ public static void main(String args[]) throws Exception
{ FileReader f = new FileReader("file3.txt");
BufferedReader bf = new BufferedReader(f); while( true )
200
{ String x = bf.readLine( ); if ( x == null ) break; else System.out.println(x); }
bf.close( ); f.close( ); } }
Example 145 : Demo of InputStreamReader
It is used to read the data typed from the keyboard.
import java.io.*;
class InputStreamReaderDemo {
public static void main(String args[]) {
try {
int c;
InputStreamReader ir = new InputStreamReader(System.in);
while ( (c = ir.read() ) != -1)
{ System.out.print( (char) c);
}}
catch (IOException e) { }
} }Object Serialization
It is a process of writing objects to a stream, and reading them back when wanted.
201
We use ObjectInputStream, ObjectOutputStream classes respectively which are derived from InputStrem, OutputStream classes to handle the Objects which are called object streams.
Example 146 : Demo of Object streams.
To serailize an object it should implement a Serializable interface.
import java.io.*;
class NewString implements Serializable { String d;
public NewString( String p) { d = p; } public void dispdata( ) { System.out.println(d); } }
public class DemoTest { public static void main(String args[]) {
NewString i1, o1;
i1 = new NewString(""); o1 = new NewString("Hello from Java!");
try {
FileOutputStream fo = new FileOutputStream ("testobj.dat"); ObjectOutputStream ofo = new ObjectOutputStream(fo);
ofo.writeObject(o1); ofo.flush();
ofo.close();
202
FileInputStream fi= new FileInputStream ( testobj.dat"); ObjectInputStream ofi = new ObjectInputStream(fi) ;
i1 = (NewString)ofi.readObject(); i1.dispdata();
ofi.close(); }
catch(Exception e) { }
System.out.println(i1);}
}
Example 147 : Demo of Object streams.
To serailize an object it should implement a Serializable interface.
import java.io.*;import java.util.*;
class Student implements Serializable { int htno; String name;
public Student(int x, String p) { htno = x; name = p; }
public Student( ) { }
public int getHtno( ) { return htno; }
203
public String getName( ) { return name; }
} public class DemoObj { public static void main(String args[]) {
Student i1, i2, o1,o2; o1 = new Student(213, "Preethi");
o2 = new Student(123, "Pushkal"); try {
FileOutputStream fo = new FileOutputStream ("student.dat"); ObjectOutputStream ofo = new ObjectOutputStream(fo);
ofo.writeObject(o1); ofo.writeObject(o2);
ofo.flush(); ofo.close();
FileInputStream fi= new FileInputStream("student.dat"); ObjectInputStream ofi = new ObjectInputStream(fi) ;
StreamTokenizer It is used to break the input stream into tokens, such as words.
Example 148 : Demo of StreamTokenizer.
import java.io.*;
class DemoTest { public static void main(String args[]) throws Exception { FileReader f = new FileReader("file.txt"); StreamTokenizer st = new StreamTokenizer(f); String s;
They are used to store the path and the name of the file or a Directory. It is not useful in retrieving or storing data. The File object can be used to create, rename, delete a file.
A directory is just a list of files. Each file in java is an object of File class.
File class can identify information such as last modification, date, time and navigation through subdirectories.
Example 149 : Demo of File Class.
import java.io.*; class FileDemo { public static void main(String args[])
{205
File f1 = new File("file.txt");
System.out.println("File: " + f1.getName()); System.out.println( (f1.isFile() ? + is a file"); System.out.println("Size: " + f1.length()); System.out.println("Path: " + f1.getPath()); System.out.println("Parent: " + f1.getParent()); System.out.println("Absolute Path: " + f1.getAbsolutePath()); System.out.println("File was last modified: " + f1.lastModified()); System.out.println(f1.exists() ? "File exists" : "File does not exist");
System.out.println(f1.canRead() ? "File can be read from" : "File cannot be read from");
System.out.println(f1.canWrite() ? "File can be written to" : "File cannot be written to");
System.out.println(f1.isDirectory() ? "File is a directory" : "File is not a directory");
System.out.println(f1.isFile() ? "is a true file" : Is not a special file");
System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");}
}
Reflection API
Reflection API is a powerful technique to find-out the environment as well as to inspect the class itself. The classes of Reflection API are the part of the package java.lang.reflect and the methods of Reflection API are the parts of the package java.lang.class.
It allows the user to get the complete information about interfaces, classes, constructors, fields and various methods being used.
Retrieving the class name through Reflection APIA more generic way, how to retrieve the name of the class that reflects the package name by using the getName() method. import java.lang.reflect.*;public class Democlass { public static void main(String[] args) { Class cls = java.lang.Integer.class; String info;
206
info = cls.getName(); // It will show java.lang.Integer System.out.println(info); } }
Getting the method name used in the Application
we describe how to retrieve method name by using the getMethods() method. Define a class named "Demomethod" and then create an object of this class and get the reference of java.util.Integer.class into it. Now retrieve the method name by using the getMethods() method.
import java.lang.reflect.*;
public class Demomethod { public static void main(String[] args) { Class cls = java.lang.Integer.class; Method m = cls.getMethods()[0]; String info; info = m.getName(); System.out.println(info); } }
Getting information about Constructor
Now we discuss, how to retrieve the information about the constructor by using the getConstructors() method. Declare a class "Democon" and then create an object of this class and take the reference of the class java.util.Integer.class into it. Make a Constructor named con. Now retrieve the name of the constructor by using the getConstructors() method.
import java.lang.reflect.*;
public class Democon { public static void main(String[] args) { Class cls = java.lang.String.class; Constructor con = cls.getConstructors()[0]; String name; name = con.getName(); //It'll show java.lang.String System.out.println(name); }}