Escolar Documentos
Profissional Documentos
Cultura Documentos
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 and can get access to the files
from any remote machine rather than writing codes on their local system.
6. Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM.
7. Secure
Java 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. Performance
Java 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. Multithreaded
Multithreading programming is a very interesting concept in Java.
10. Interpreted
One 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.
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 ::
Demonstartion Programs
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 );
}
}
Structure of Arrays
Array 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
integers
String[] 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];
Array Initialization
After 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 is
String 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);
}
}
Chapter 2
{
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.
{
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
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
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')
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()
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
wrapper
22
int
float
char
Integer
Float
Character
{
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
System.out.println(ib1 + " " +i1);
ib2 = 35;
ib2 = ib2 + 1; // unbox and rebox
System.out.println("value" + ib2) ;
ib3 = Abox.getval(55); // Autobox
System.out.println(" value returned" + ib3);
}
}
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);
}
}
25
26
Chapter 4
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
Multilevel Inheritance
Hybrid Inheritance
Multiple Inheritance
Hirarchial 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
30
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.
There are two types of polymorphism :
1. Compile-time polymorphism
2. Runtime Polymorphism
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){
System.out.println("int in Class B is : "+ x);
33
}
}
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[])
{
Fish f = new Fish();
34
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()
{
super.Show();
35
{
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");
}
}
public class TestApp
{
public static void main(String args[])
37
{
A a1 = new A(); B b1 = new B();
C c1 = new C();
A oref;
oref = a1;
oref = b1;
oref = c1;
}
oref.disp();
oref.disp();
oref.disp();
}
output ::
printing A
printing B
printing C
Abstract class
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
{
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++; .....????!
a = 50; .....????!
is-a relation ::
not allowed
not allowed
class A
{
void disp( )
{
System.out.println("from A");
}
}
class B extends A
{
B( )
{
disp( );
}
}
// B is-a A
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( ) ;
}
}
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) ::
Class getClass() ::
int hashCode() ::
{
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() );
ref is class A
printing B
ref is class B
printing C
ref is class C
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");
}
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);
}
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.
float calcPercent();
void menu();
}
class Student implements StudentInter
{
int rno, m1,m2;
string name;
public void getData( ) throws IOException
{
DataInputStream d = new DataInputstream( System.in );
System.out.print( "Enter Rollno :" );
rno = Integer.parseInt( d.readLine( ) );
System.out.print( "Enter Name :" );
name = d.readLine( );
System.out.println( "Enter Sub 1 Mark :" );
m1 = Integer.parseInt( d.readLine( ) );
System.out.println("Enter Sub 2 Mark :" );
m2 = Integer.parseInt( d.readLine( ) );
}
public void showData( )
{
System.out.println ( "Rollno = " + rno);
System.out.println ( "Name = " + name);
System.out.println ( "mark1 = " + m1);
System.out.println ( "mark2 = " + m2);
}
public int calcTot( )
{
return ( m1 + m2);
}
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;
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.
{
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.
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.
1:
2:
3:
4:
java Divide 4 2
java Divide 4
java Divide a 2
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
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.
Here is the list of unchecked exceptions.
ArrayIndexOutOfBoundsException
ArithmeticException
NullPointerException
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.
54
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
Arithmetic errors such as
ArithmeticException
YES
a divide by zero
Arrays index is not within
ArrayIndexOutOfBoundsException
YES
array.length
ClassNotFoundException
Related Class not found YES
InputOuput field not
IOException
YES
found
Illegal argument when
IllegalArgumentException
YES
calling a method
One thread has been
InterruptedException
interrupted by another YES
thread
NoSuchMethodException
Nonexistent method
YES
Invalid use of null
NullPointerException
YES
reference
Invalid
string
for
NumberFormatException
YES
conversion to number
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
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
catch ( ArayIndexOutOfBoundsException e)
{
System.out.println("pass proper args");
59
}
System.out.println("program ends here..");
}
}
Redirecting Exceptions using "throws" ::
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.
2.
3.
{
...
}
}
It is thrown by using keyword throw. It is also possible to override the methods such as
getmessage(), toString() etc.
Example 51 : demo of custom exceptions
import java.io.*;
class AgeException extends Exception
{
int age;
AgeException(String mesg)
{
super(mesg);
}
AgeException( )
{
super( );
}
}
class youngAgeException extends AgeException
{
youngAgeException(int a1, String mesg)
{
super("you are too young for" + mesg);
age = a1;
}
youngAgeException( )
{
super( "too young");
}
}
class invalidAgeException extends AgeException
{
invalidAgeExecption(String mesg)
{
super(mesg);
}
invalidAgeException(int a1 )
62
{
super( "Invalidformat");
age = a1;
}
}
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;
try
{
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
calc(a,b);
}
catch ( ArithmeticException e)
{
System.out.println("Handled in main");
System.out.println("...Invalid argumets !");
}
catch ( NumberFormatException e)
{
System.out.println("Invalid argumets");
}
catch ( ArayIndexOutOfBoundsException e)
{
System.out.println("pass proper args");
}
System.out.println("program ends here..");
}
{
try
{
int c1 = a1/b1;
System.out.println("c1="+ c1);
}
catch ( ArithmeticException e)
{
System.out.println("rethrowing now..");
throw e;
}
}
}
65
{
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.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
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.
67
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
System.out.println("empty stack");
}
}
}
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:
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.
CLASSES
Collection Interface
Iterator Interface
HashSet Class
TreeSet Class
70
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
ArrayList Class
LinkedList Class
HashMap Class
TreeMap Class
Vector Class
Stack Class
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
ArrayList
ArrayDeque
AbstractSet
HashSet
TreeSet
Map classes
HashMap
TreeMap
Apart from these , we see Arrays, Vector, Stack, Hashtable, Dictionary, properties, and
other classes which are not technically members of this collection framework.
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
76
while(it.hasNext())
{
System.out.print(it.next());
}
}
}
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
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry mp = (Map.Entry) it.next();
System.out.println(mp.getKey() + "/" + mp.getValue());
// it prints the key, value pairs
}
System.out.print(hm.get("Item 0"));//search for corresponding value
}
}
79
80
81
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.
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 :
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.
83
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:
84
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....");
}
}
86
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
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
other in various ways.
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
89
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 nonrunnable 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
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
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.
Blocked for joint completion The thread can come on this state because of waiting the
completion of another thread.
Blocked for lock acquisition The thread can come on this state because of waiting to acquire
the lock of an object.
Return
Type
Description
90
getName( )
start( )
sleep( )
isAlive( )
interrupt( )
void
yield( )
void
join( )
void
run( )
String
Void
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() );
}
}
Example 69 : Demo of Multiple threads
class CustomThread extends Thread
{
91
CustomThread(String name)
{
super(name);
start();
}
public void run()
{
try
{
for(int i = 0; i < 4; i++)
{
System.out.println((Thread.currentThread()).getName()+
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
}
catch (InterruptedException e)
{
}
}
}
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.");
}
}
}
}
output :
thread 1 counted 1861102033
thread 2 counted 1749869293
thread 3 counted 29565226
Synchronization ::
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. Such
a 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
modifer synchronized rettype name( parameters )
{
}
Example 72 :: Demo why synchronization ?
class Shared
{
void doWork(String s)
{
System.out.println("Starting " + s);
try {
Thread.sleep((long) (Math.random() * 500));
}
catch (InterruptedException e) { }
System.out.println("Ending " + s);
}
}
class CustomThread extends Thread
{
Shared sh;
public CustomThread(Shared sh, String s)
{
super(s);
this.sh = sh;
start();
}
public void run()
{
sh.doWork(Thread.currentThread().getName());
}
}
99
}
}
class CustomThread extends Thread
{
Shared sh;
public CustomThread(Shared sh, String s)
{
super(s);
this.sh = sh;
start();
}
public void run()
{
sh.doWork(Thread.currentThread().getName());
}
}
101
A sub class can override a sync method of its super class The overriden method need not be
sync.
If a non sync method of an object uses the super( ) to call a sync method of its parent class,
the object is blocked until the invocation is complete.
Sychronized statements ::
A part of the code can be placed under a monitor using the syntax shown below.
synchronized < object > < statements >
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
class Queue
{
int n;
synchronized int get( )
{
system.out.println(" got : " + n);
return n;
}
synchronized void put( int n )
{
this.n = n;
system.out.println(" put :" + n);
}
}
104
{
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
put : 3
put : 6
put : 8
Got : 0
Got : 3
Got : 6
put : 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
class Queue
{
boolean flag = true;
int n;
synchronized int get( )
{
if ( !flag)
{
system.out.println(" got : " + n);
notify( );
}
else
{
try
{
wait( );
}
catch ( Exception e) { }
}
return n;
}
106
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++;
}
}
}
Got : 0
Got : 3
Got : 6
Got : 8
Put : 1
Put : 4
Put : 7
put : 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.
109
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!");
}
}
Before running this program make sure to do the following things:
111
1.
2.
3.
4.
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.HelloWorld
Hello 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:
112
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 CallPackage
This is the function of the class HelloWorld!!
Make sure to the directory structure for this program shown as:
package importpackage.subpackage;
public class HelloWorld {
public void show(){
System.out.println("This is the function of the class HelloWorld!!");
}
}
114
Now import the package "subpackage" in the class file "CallPackage" shown as:
import importpackage.subpackage.*;
class CallPackage{
public static void main(String[] args){
HelloWorld h2=new HelloWorld();
h2.show();
}
}
Out of the program:
C:\nisha>javac
C:\nisha\importpackage\subpackage\HelloWorld.java
C:\nisha\importpackage\subpackage>cd..
C:\nisha\importpackage>cd..
C:\nisha>javac CallPackage.java
C:\nisha>java CallPackage
This is the function of the class HelloWorld!!
Make sure to the directory structure for this program shown as:
{
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
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.
java.lang.Object
|
java.awt.Component
|
java.awt.Container
|
java.awt.Panel
|
java.applet.Applet
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
import java.applet.*;
import java.awt.*;
/* <APPLET CODE=Appex.class WIDTH=200 HEIGHT=200 > </APPLET> */
public class Appex extends Applet
{
String msg = " ";
public void init()
{
setBackground(Color.blue);
msg = msg+"init() : ";
}
public void start()
{
msg = msg+"start() : ";
}
public void stop()
{
msg = msg+"stop() : ";
}
public void destroy()
{
msg = msg+"destroy() : ";
}
public void paint(Graphics g)
{
msg = msg+"paint() : ";
g.drawString(msg,60,100);
}
}
Example 83 :: Demo of passing parameters
import java.applet.*;
124
import java.awt.*;
/* <APPLET CODE=Appex.class WIDTH=200 HEIGHT=200 >
<PARAM NAME = msg VALUE = "Java is simple!">
</APPLET> */
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!");
}
}
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
}
catch(MalformedURLException e)
{
msg = "malformed URL string ";
}
ac = getAudioClip(u);
}
}
public void paint(Graphics g)
{
g.drawString("playing" ,10,50);
ac.loop();
g.drawString(msg,10,100);
}
}
AppletContext interface :
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.
</html>
B. ShowDemo.java
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ShowDemo extends Applet
{
String doc;
AppletContext ac;
URL u = null;
String msg = " ";
public void init()
{
ac = getAppletContext();
doc = getParameter("dname");
}
public void start()
{
if doc != null
{
try
{
u = new URL(doc);
}
catch(MalformedURLException e)
{
msg = "malformed URL string ";
}
ac.showDocument( u, "newWindow");
}
}
public void paint(Graphics g)
{
g.drawString("Communicating" ,10,50);
g.drawString(msg,10,100);
}
129
}
C. Samppage.html :
< html>
<head> <title> Displaying new page </title></head>
<body>
This is to demonstrate applets power to show
other documents
</body>
</html>
Example 90 ::
/* <applet code="statusdemo.class" width=200 height =200>
</applet> */
import java.applet.*;
import java.awt.*;
public class statusdemo extends Applet
{
public void init()
{
setBackground(Color.pink);
}
public void paint(Graphics g)
{
g.drawString(" text in applet window " ,10,20);
showStatus("It shows text in a seperate status window");
}
}
Example 91 : Image display- threads
/* <applet code=ImageApplet width=300 height=200>
</applet> */
import java.awt.*;
import java.applet.*;
130
}
}
132
Chapter 10
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.
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
String getText()
void setText(String)
Action
Returns a string containing this label's text
Changes the text of this label
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);
l1 = new Label("Welcome ");
add(l1);
l2 = new Label("To Learn Java");
add(l2);
l3 = new Label("Course");
add(l3);
}
}
Button ::
Methods ::
String getLabel( ) ,
void setLabel(String )
import java.awt.*;
import java.applet.*;
public class ButtonTest extends Applet
{
Button b1,b2;
public void init( )
{
136
void setLabel(String)
boolean getState()
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()
{
ch = new Choice( );
ch.add("apples");
ch.add("oranges");
ch.add("strawberies");
ch.add("bananas");
add(ch );
}
}
TextField ::
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()
int getRows()
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
Example 99 : Demo of List
import java.awt.*;
public class ListTest extends Applet
{
List lt = new List(3,true);
140
ScrollBar::
int getValue()
Gets current value of Scrollbar
void 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( ));
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
GridBagConstraint.VERTICAL
GridBagConstraint.BOTH
Insets
Anchor
ipadx,ipady
Example 103 : Demo of flowlayout
import java.awt.*;
public class Demoflow extends Applet
{
Button b1,b2,b3,b4;
144
FlowLayout fl;
public void init( )
{
b1 = new Button("Java");
b2 = new Button("Oracle");
b3 = new Button("XML");
b4 = new Button("JavaScript");
fl = new FlowLayout(FlowLayout);
setLayout(fl);
add(b1);
add(b2);
add(b3);
add(b4);
}
}
Example 104 : Demo of gridlayout
import java.awt.*;
public class Demogrid extends Applet
{
Button b1,b2,b3,b4;
GridLayout gr;
public void init( )
{
b1 = new Button("Java");
b2 = new Button("Oracle");
b3 = new Button("XML");
b4 = new Button("JavaScript");
gr = new GridLayout(2,2);
setLayout(gr);
add(b1);
145
add(b2);
add(b3);
add(b4);
}
}
Example 105 : Demo of Borderlayout
import java.awt.*;
public class Border extends Applet
{
BorderLayout br;
Button b1,b2,b3,b4,b5;
public void init()
{
br = new BorderLayout();
b1 = new Button("java");
b2 = new Button("oracle");
b3 = new Button("sybase");
b4 = new Button("c++");
b5 = new Button("IT");
setLayout(br);
add("North", b1);
add("South", b2);
add("East", b3);
add("West", b4);
add("Center", b5);
}
}
Example 106 : Demo of Cardlayout
import java.awt.*;
public class DemoCard extends Applet
{
CardLayout ca = new CardLayout( );
Label [ ] lb = new Label[5];
146
b5 = new Button("J2EE");
b6 = new Button("C++");
gl = new GridBagLayout( );
gbc = new GridBagConstraints( );
setLayout(gl);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gl.setConstraints(b1,gbc);
add(b1);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gl.setConstraints(b2,gbc);
add(b2);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gl.setConstraints(b3,gbc);
add(b3);
gbc.weightx = 0.0;
gbc.weighty = 1.0;
gbc.gridheight = 2;
gbc.gridwidth = 1;
gl.setConstraints(b4,gbc);
add(b4);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
gl.setConstraints(b5,gbc);
add(b5);
gbc.gridwidth = GridBagConstraints.REMAINDER;
148
gbc.gridheight = 1;
gl.setConstraints(b6,gbc);
add(b6);
}
}
{
setSize(300,300);
setVisible(true);
setTitle("Panel Demo");
setBackground(Color.yellow);
setLayout( new FlowLayout ( ) );
p = new Panel( );
p.setLayout( new FlowLayout ( ) );
sp1 = new Panel( );
sp1.setLayout( new FlowLayout ( ) );
sp2 = new Panel( );
sp2.setLayout( new FlowLayout ( ) );
p.setSize(250,250);
p.setVisible(true);
p.setBackground(Color.red);
add(p);
sp1.setVisible(true);
sp1.setBackground(Color.blue);
p.add(sp1);
sp2.setVisible(true);
sp2.setBackground(Color.pink);
p.add(sp2);
}
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
-------------
Button
List
Menultem
TextField
ActionListener
actionPerformed(ActionEvent e)
Checkbox
ItemListener
Choice
List
Checkbox MenuItem
itemStateChanged(ItemEvent e)
DialogFrame
windowOpened(WindowEvent e)
windowClosing(WindowEvent e)
windowMinimized(WindowEvent e)
WindowListener
151
Scrollbar
AdjustmentListener
adjustmentValueChanged( AdjustmentEvent e)
Canvas
Dialog
Frame
Panel
Window
MouseListener
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mouseClicked(MouseEvent e)
Component
KeyListener
keyTyped(KeyEvent e)
keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
Component
FocusListener
focusGained(FocusEvent e)
focusLost(FocusEvent e)
TextComponent
TextListener
textValueChanged(TextEvent e)
::
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
:: It occurs,
1. When a component gains or loses focus
KeyEvent
::
1. It is generated by the user during interaction
from keyboard
153
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) );
}
}
}
Example 112 : Demo CheckBox Events
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE=checks.class WIDTH=200 HEIGHT=200 >
</APPLET> */
public class checks extends Applet implements ItemListener
{
Checkbox c1, c2, c3;
TextField t1;
public void init()
{
c1 = new Checkbox("1");
add(c1);
c1.addItemListener(this);
c2 = new Checkbox("2");
add(c2);
c2.addItemListener(this);
c3 = new Checkbox("3");
add(c3);
c3.addItemListener(this);
t1 = new TextField(20);
add(t1);
155
}
public void itemStateChanged(ItemEvent e)
{
if(e.getItemSelectable() == c1 && c1.getState() )
{
t1.setText("Check box 1 selected !");
}
else
if(e.getItemSelectable() == c2 && c2.getState() )
{
t1.setText("Check box 2 selected!");
}
else
if(e.getItemSelectable() == c3 && c3.getState() )
{
t1.setText("Check box 3 selected!");
}
}
}
Example 113 :Demo Radio Events
public class radios extends Applet implements ItemListener
{
CheckboxGroup cg;
Checkbox r1, r2, r3;
TextField t1;
public void init()
{
cg = new CheckboxGroup();
r1 = new Checkbox("CSE", false, cg);
add(r1);
r1.addItemListener(this);
r2 = new Checkbox("ECE", false, cg);
add(r2);
r2.addItemListener(this);
156
List l1;
TextField t1;
Button b1;
String s[];
public void init()
{
t1 = new TextField(40);
add(t1);
l1 = new List(4, true);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
l1.add("Item 6");
l1.add("Item 7");
l1.add("Item 8");
l1.add("Item 9");
add(l1);
b1 = new Button("Show selections");
b1.addActionListener(this);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
String ot = new String("You selected:");
if(e.getSource() == b1)
{
s = l1.getSelectedItems();
for(int i = 0; i < s.length; i++)
{
ot += " " + s[i];
}
159
t1.setText(ot);
}
}
}
Example 117 : Demo Choice Events
public class choice extends Applet implements ItemListener, ActionListener
{
TextField t1, t2;
Choice c1;
Button b1;
public void init()
{
t1 = new TextField(20);
t2 = new TextField(20);
b1 = new Button("Remove Listeners");
add(t1);
add(t2);
c1 = new Choice();
c1.add("Item 1");
c1.add("Item 2");
c1.add("Item 3");
c1.add("Item 4");
add(c1);
add(b1);
c1.addItemListener(this);
b1.addActionListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if( e.getItemSelectable() == c1 )
{
String n = ((Choice)e.getItemSelectable)).getSelectedItem();
t1.setText("You chose " + n);
}
160
}
public void actionPerformed(ActionEvent e)
{
if( e.getSource() == b1 )
{
ItemListener[] al = c1.getItemListeners();
for (int i=0; i<al.length; i++)
{
c1.removeItemListener(al[i]);
t2.setText("Listener Removed");
}
}
}
}
161
repaint( ) ;
}
public void mouseExited(MouseEvent e)
{
X=0; Y=10;
str= "Mouse Exited";
repaint ( ) ;
}
public void mousePressed(MouseEvent e)
{
X=e.getX(); Y=e.getY( ) ;
str= "Mouse Down";
repaint( ) ;
}
public void mouseReleased(MouseEvent e)
{
X = e.getX() ; Y=e.getY() ; str="Mouse Up"; repaint();
}
public void mouseDragged(MouseEvent e)
{
X=e.getX(); Y=e.getY(); str="Dragging Mouse ";
showStatus ( "Dragging at"+ e.getX()+ ","+ e.getY() );
repaint();
}
public void mouseMoved(MouseEvent e)
{
showStatus ( "Moving mouse at"+ e.getX()+"," + e.getY() );
}
public void paint(Graphics g)
{
g.drawString(str, X, Y);
}
}
Example 120 : demo Key Events
164
cl.show(this, "second");
break;
case 3:
cl.show(this, "third");
break;
}
166
if(index == 3) index = 0;
repaint();
}
}
Example 122 : Demo Gridbag Layout
public class Demogridbag extends Applet implements ActionListener
{
Button b1, b2, b3;
TextField t1;
public void init()
{
GridBagLayout gr = new GridBagLayout();
GridBagConstraints con = new GridBagConstraints();
setLayout(gr);
con.weighty = 1;
con.fill = GridBagConstraints.BOTH;
con.weightx = 1;
b1 = new Button("Button 1");
gr.setConstraints(b1, con);
b1.setActionCommand("button 1");
add(b1);
b1.addActionListener(this);
con.weightx = 2;
b2 = new Button("Button 2");
gr.setConstraints(b2, con);
b2.setActionCommand("button 2");
add(b2);
b2.addActionListener(this);
con.weightx = 1;
b3 = new Button("Button 3");
con.gridwidth = GridBagConstraints.REMAINDER;
gr.setConstraints(b3, con);
b3.setActionCommand("button 3");
add(b3);
b3.addActionListener(this);
167
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.
{
g.drawString(s,60,100);
}
}
}
class Demowin extends Frame implements MouseListener,WindowListener
{
Label l;
Demowin(String title)
{
super(title);
setLayout( new FlowLayout() );
l = new Label("Hello from Java! This is a frame window.");
add(l);
addMouseListener(this);
// This is to exit when the window is closed
addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
setVisible(false);
// we can also use, System.exit(0);
}
} );
}
{
l.setText( "Right mouse down at"+e.getX()+","+ e.getY() );
}
}
public void mouseClicked(MouseEvent e)
{
l.setText( "Mouse clicked at " + e.getX()+","+e.getY() );
}
public void mouseReleased(MouseEvent e)
{
l.setText("The mouse button went up.");
}
public void mouseEntered(MouseEvent e)
{
l.setText("The mouse entered.");
}
public void mouseExited(MouseEvent e)
{
l.setText("The mouse exited.");
}
}
Menu:
Object
|
MenuComponent
|
____________
|
|
MenuItem
MenuBar
|
_______________
|
|
CheckboxMenuItem Menu
|
171
|
PopupMenu
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
mb = new MenuBar();
m = new Menu("File");
mi1 = new MenuItem("Item 1");
m.add(mi1);
mi1.addActionListener(this);
mi2 = new MenuItem("Item 2");
m.add(mi2);
mi2.addActionListener(this);
mi3 = new MenuItem("Item 3");
m.add(mi3);
mi3.addActionListener(this);
mb.add(m);
setMenuBar(mb);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
setVisible(false);
}
} );
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == mi1)
l.setText("You chose item 1");
else
if(e.getSource() == mi2)
l.setText("You chose item 2");
else if(e.getSource() == mi3)
l.setText("You chose item 3");
}
}
174
mb = new MenuBar();
m = new Menu("File");
mi1 = new MenuItem("Item 1");
mi1.addActionListener(this);
m.add(mi1);
mi2 = new MenuItem("Item 2");
mi2.addActionListener(this);
m.add(mi2);
m.addSeparator();
mi3 = new CheckboxMenuItem("Check Item");
mi3.addItemListener(this);
m.add(mi3);
m.addSeparator();
s = new Menu("Sub menus");
si1 = new MenuItem("Sub item 1");
si2 = new MenuItem("Sub item 2");
si3 = new MenuItem("Sub item 3");
si1.addActionListener(this);
si2.addActionListener(this);
si3.addActionListener(this);
s.add(si1);
s.add(si2);
s.add(si3);
mi2.add(s);
m.addSeparator();
mi4 = new MenuItem("Exit");
mi4.addActionListener(this);
m.add(mi4);
mb.add(m);
setMenuBar(mb);
176
if(e.getSource() == mi3)
{
if( ( (CheckboxMenuItem) e.getItemSelectable() ).getState() )
l.setText("Item 3 is checked");
else
l.setText("Item 3 is not checked");
}
}
}
MouseListener
pp.add(mi3);
pp.addSeparator();
pp.add(mi4);
add(pp);
l = new Label("Hello from Java!");
add(l);
addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
if(e.getModifiers() != 0) {
pp.show( this, e.getX(), e.getY() );
}
}
public void mouseClicked(MouseEvent e){ }
public void mouseReleased(MouseEvent e){ }
public void mouseEntered(MouseEvent e){ }
public void mouseExited(MouseEvent e){ }
Dialog Box
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
{
label l; Button b1,b2;
mydialogue( par, title)
{
super(par, title, true);
setSize(200,200);
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");
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
add (b0);
add (b1);
add (b2);
add (b3);
add (b4);
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
add (b5);
add (b6);
add (b7);
add (b8);
add (b9);
d.b0.addActionListener(this);
d.b1.addActionListener(this);
d.b2.addActionListener(this);
d.b3.addActionListener(this);
d.b4.addActionListener(this);
d.b5.addActionListener(this);
d.b6.addActionListener(this);
d.b7.addActionListener(this);
d.b8.addActionListener(this);
d.b9.addActionListener(this);
d.bp.addActionListener(this);
d.bs.addActionListener(this);
d.bm.addActionListener(this);
d.bd.addActionListener(this);
d.bpo.addActionListener(this);
d.be.addActionListener(this);
d.bon.addActionListener(this);
}
public void actionperformed(ActionEvent e)
{
if( e.getSource( ) == d.bo)
p.t1.setText( (p.t1.getText( ) + d.b0.getlabel( ) );
184
{
n = (m / Float.parseFloat(p.t1.getText( ) ) );
p.t1.setText( String.valueOf(n));
}
}
}
}
Example 130 : Demo of Menus
class Testwind extends Frame implements ActionListener
{
MenuBar mb;
Menu m1,m2;
TextField t;
MenuItem mi1, mi2,mi3, mi4;
Testwind(String title)
{
super(title);
t = new TextField(20);
setLayout(new GridLayout(1, 1));
add(t);
mb = new MenuBar();
m1 = new Menu("study");
mi1 = new MenuItem("MCA");
mi1.addActionListener(this);
m1.add(mi1);
else
if(e.getSource() == mi3)
t.setText("You are in Univ");
else
if(e.getSource() == mi4)
t.setText("You are in affl coll");
}
}
public class Demomenu extends Applet implements ActionListener
{
Button b1,b2;
Testwind w;
188
p1.c1.additemListener(this);
p1.c2.additemListener(this);
p1.c3.additemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if( e.getItemSelectable() == p1.c1 )
{
p2.i1.setState(true);
p2.i2.setState(true);
p2.i3.setState(false);
p2.i4.setState(false);
p2.i5.setState(false);
p2.i6.setState(false);
p1.t1.setText("course fee Rs 4500/-");
}
if( e.getItemSelectable() == p1.c2 )
{
p2.i1.setState(false);
p2.i2.setState(false);
p2.i3.setState(true);
p2.i4.setState(true);
p2.i5.setState(false);
p2.i6.setState(false);
p1.t1.setText("course fee Rs 9500/-");
}
if( e.getItemSelectable() == p1.c3 )
{
p2.i1.setState(false);
p2.i2.setState(false);
p2.i3.setState(false);
p2.i4.setState(false);
191
p2.i5.setState(true);
p2.i6.setState(true);
p1.t1.setText("course fee Rs 14500/-");
}
}
}
Thread.sleep(500);
}
catch(InterruptedException e)
{ }
}
}
public void paint(Graphics g)
{
g.drawString("java", x,y);
}
}
193
Chapter 11
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 and
usefull 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];
f.read(b);
// convert byte array into string
System.out.println(new String(b, 0, b.length ));
System.out.println("Skipping ");
f.skip(len/5);
System.out.println("Reading next 1/5 of file....");
if (f.read(b) != len/5)
{
System.out.println("Could not get ");
}
else {
System.out.println(new String(b, 0, b.length) );
}
f.close();
}
}
196
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.
Object
|
Reader
|
______ | _________
|
|
BufferedReader InputStreamReader
|
FileReader
Object
|
Writer
|
_________________________________________
|
|
|
BufferedWriter OutputStreamWriter
PrintWriter
|
FileWriter
The InputStreamReader can read data from keyboard thorugh System.in, and its counter part is
OutputStreamWriter.
FileReader, FileWriter classes can handle streams from files. BufferedReader can read line by
line instead of character by char.
PrinWriter can send formated outputs.
Example 143 : Demo of FileWriter
import java.io.*;
class Demotest
{
public static void main(String args[]) throws Exception
199
{
char data[ ] ={ 'T', 'h', 'i', 's', ' ' ,
'i', 's', ' ' ,
'a', ' ' ,
'B' , o', o', k };
FileWriter f = new FileWriter("file1.txt");
for (int i = 0; i < data.length; i++)
{
f.write(data[i]);
}
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
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
System.out.println(i1);
System.out.println(i2);
}
}
204
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;
while(st.nextToken() != StreamTokenizer.TT_EOF)
{
if(st.ttype == StreamTokenizer.TT_WORD)
System.out.println(st.sval);
}
f.close();
}
}
File Streams
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
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 API
A 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;
206
String info;
info = cls.getName(); // It will show java.lang.Integer
System.out.println(info);
}
}
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);
}
}
207
208