Java Notes
Java Notes
Java Notes
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.
1
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.
Languages like C and Pascal converts the source code into machine code for one specific type of
machine and the machine language vary from system to system . But Java compiler produce code for a
virtual machine . JVM converts the byte code into machine code for the computer one wants to run.
The JVM is a part of JRE that is required by every operating system.
Each operating system and CPU architecture requires a JRE. JRE consists of a set of base classes i.e. Java
API as well as a JVM. JVM is java interpreter as it converts the byte code into machine code for the
computer one wants to run.
JRE consists of a number of classes based on JavaAPI and JVM, and without JRE, it is impossible to run
Java.
2
Save the file with same name as the public class just adding the extension “.java” e.g.
FirstProgram.java.
a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create
desktop applications, applets, server applications. These programs developed using Java SE can be
run on almost every popular operating system.
b) JEE - Java Enterprise Edition helps in web application service, component model and enterprise
class service oriented architecture(SOA).
c) JME - Java Micro Edition or JME is an accumulation of Java APIs that are used for the development
of software for devices like mobile phones, PDAs, TV set-top boxes, game programming.
Demonstartion Programs
4
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];
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);
}
}
To know the length of the Array, we use field length, as shown.
Example 5 : Demo of 1 D array - Linear search
6
Example 6 : Demo of 1 D array - Sorting of n integers
7
Example 8 : Demo of Recursive functions
if ( n < 0) return 1;
else
return n * fact ( n – 1);
}
}
8
Chapter 2
Inheritance: Inheritance provide the facility to derive one class by another using simple syntax. You
can say that it is a process of creating new class and use the behavior of the existing class by
extending them for reuse the existing code and adding the additional features as you need.
Encapsulation: Encapsulation is the ability to bundle the property and method of the object and also
operate them. It is the mechanism of combining the information and providing the abstraction as
well.
Polymorphism: Polymorphism is the way that provide the different functionality by the functions
having the same name based on the signatures of the methods. There are two type of
polymorphism first is run-time polymorphism and second is compile-time polymorphism.
Dynamic binding: It is the way that provide the maximum functionality to a program for a specific
type at runtime. There are two type of binding first is dynamic binding and second is static binding.
Class: A class provide a feature to defines the properties and behavior (variables and methods) as an
ADT , that can be used by all its objects. It is a blue print for the creation of objects.
Object: Class itself does nothing but the real functionality is achieved through their objects. Object is an
instance of the class. It takes the properties (members) and uses the behavior (methods) defined in the
class.
The Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been
described below :
Encapsulation:
Encapsulation is the process of binding together the methods and data variables as a single entity. It
keeps both the data and functionality code safe from the outside world. It hides the data within the
class and makes it available only through the methods. Java provides different accessibility scopes
(public, protected, private ,default) to hide the data from outside.
Here we provide a example in which we create a class "Check" which has a variable "amount" to store
the current amount. Now to manipulate this variable we create a methods and to set the value of
amount we create setAmount() method and to get the value of amount we create getAmount() method
9
Here is the code for "Mainclass" class :
class Check
{
private int amount=0;
public int getAmount()
{
return amount;
}
public void setAmount(int amt)
{
amount=amt;
}
}
{
int amt=0;
Check obj = new Check();
obj.setAmount(200);
amt = obj.getAmount();
System.out.println("Your current amount is :"+amt);
}
}
Here the data variable "amount" and methods setAmount() and getAmount() are enclosed together
with in a single entity called the "Check" class. These two methods are used to manipulate this variable
i.e. set and get the current value of amount.
class DemoCalc
{
int a , b;
public DemoCalc()
{
a = 5; b = 10;
}
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.
class DemoOver
{
int a , b;
/* default constructor */
public DemoOver()
{
a = 5; b = 10;
}
/* constructor with parameter */
public DemoOver( int k1, ink k2)
{
a = k1; b = k2;
}
public int sum ()
11
{
int x;
x = a + b;
return x;
}
}
this key word : It is used to resolve the ambiguity between a formal parameter and a
datamember.
class Demothis
{
int a , b;
/* constructor with parameter */
Instance variables: They are the datamembers in a class and get a copy of memory for each
object instance. With one object instance if they are modified , the other instances are not
effected.
class DemoInvar
{
int a,b;
public DemoInvar( )
{
a=5; b=7;
}
class DemoClvar
{
static int a ;
int b;
public DemoClvar( )
{
a = 5; b = 7;
}
Class methods : Such methods belong the class but not to the objects. They are called with
class name.
class DemoClmd
{
15
Example 15 : Demo of class method
class DemoMathop
{
static float multiply(float x, float y)
{
return x*y;
}
}
}
class DemoNest
{
int a,b;
public DemoNest( )
{
a=15; b=7;
}
}
public class TestDemoNest
{
public static void main(String args[])
{
DemoNest m1 = new DemoNest();
m1.disp();
}
}
System.out.println() ::
The "java.lang" package is built into every program. A package is a libaries of classes.
The java.lang package has a System Class, which includes a static nested class called "out" and
this out class, has a method by name println().
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)
18
StringBuffer methods
s1.charAt(n)
s1.append(s2), s1.replace(m,n,s2)
s1.setCharAt(n,'x')
s1.insert(n,s2)
n = s.length;
19
for ( i=0; i< n-1; i++)
for (j=i+1; j<n ; j++)
if ( s[i].compareTo(s[j]) > 0 )
{
temp = s[i]; s[i] = s[j];
s[j] = temp;
}
for ( i =0; i< n; i++)
System.out.println(s[i]);
}
}
s1.replace(6,10,"to");
System.out.println(s1);
s1.delete(6,8);
System.out.println(s1);
sb.append(" to learn");
System.out.println(sb);
}
}
StringBuilder class ::
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 Integer
float Float
char Character
ib2 = 35;
ib2 = ib2 + 1; // unbox and rebox
System.out.println("value" + ib2) ;
}
}
class Abox
{
static int getval( Integer ib)
{
return ib; // unbox the return vaule
}
}
25
Example 28 : Demo of variable numer of parameters
for ( int k : i)
System.out.println("it Is" + k);
}
public static void main( String args[])
{
mthvar();
mthvar(25,35);
mthvar(10,20,30,40);
}
}
for ( int k: a)
if ( k > max) max = k;
System.out.println("maximum" + max);
}
}
26
Chapter 4
class A
{
public void fun1(int x)
{
System.out.println("in A is :" + x);
}
}
class B extends A
{
public void fun2(int x,int y)
{
fun1(6); // prints "int in A"
System.out.println("in B is :" + x " and "+y);
}
}
In the above example, class B extends class A and so acquires properties and behavior of class A. So we
can call method of A in class B.
Thus inheritance is aechanism used to create new class by extending the definition of
another class. This process of extending one class to create new class is called subclassing.
27
Types::
/* Demo of inheritance */
class DemoCalc
{
int a,b;
public DemoCalc()
{
a = 5; b = 10;
}
public int sum ()
{
int x;
x = a + b;
return x;
}
}
class A
{
A( )
{
System.out.println("In constructor of A");
}
}
class B extends A
{
B( )
{
System.out.println("In constructor of B");
}
}
public class TestApp
{
public static void main(String args[])
{
B b1 = new B();
}
}
output :: In construtor of A
In construtor of B
29
Example 32 : constructor with param under inheritance - 1
class A
{
A( )
{
System.out.println("In constructor of A");
}
}
class B extends A
{
B(String s )
{
System.out.println("In string constructor of B");
System.out.println(s);
}
}
output :: In construtor of A
In string construtor of B
java is simple
30
Example 33 : constructor with param under inheritance - 2
class A
{
A( )
{
System.out.println("In constructor of A");
}
A(String s )
{
System.out.println("In string constructor of A");
System.out.println("In A" + s);
}
}
class B extends A
{
B(String s )
{
super(s);
System.out.println("In string constructor of B");
System.out.println("In B" + s);
}
}
31
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.
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).
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;
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.
class Animal
{
public void breath( )
{
System.out.println(" Breathing...");
}
}
class Fish extends Animal
{
public void breath( )
{
System.out.println("Bubbling...");
}
}
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
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args)
{
B subobj = new B(1, 5);
subobj.Show();
}
}
Use of super to call super class constructor: The second use of the keyword super in java is to call super
class constructor in the subclass. This functionality can be achieved just by using the following
command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class. super must
be the first statement executed inside a super class constructor. If we want to call the default
constructor then we pass the empty parameter list.
class Animal
{
public void breath( )
{
System.out.println(" Breathing...");
}
}
class Fish extends Animal
{
public void breath( )
{
System.out.println("Bubbling...");
}
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.
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;
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
Example 38 : Demo of abstract class -- 1
abstract class A
{
abstract public void disp( );
}
class B extends A
{
public void disp( )
{
system.out.println("java is simple");
}
}
abstract class A
{
abstract String getData( );
public void disp( )
{
System.out.println( getData( ) );
}
}
class B extends A
{
String getData( )
{
String s = "java is simple";
return(s);
}
}
public class TestApp
39
{
public static void main(String args[])
{
B b1 = new B( );
b1.disp( );
}
}
Note : constructors, private, static methods can NOT be abstract.
Final modifier ::
To stop overriding
To stop Inheritance
creating constants
To stop overriding ::
class Animal
{
final void breath( )
{
System.out.println(" Breathing...");
}
}
class Fish extends Animal
{
public void breath( ) ......???? ( not allowed )
{
System.out.println("Bubbling...");
}
}
To stop inheritance ::
To create constants::
class A
{
void disp( )
{
System.out.println("from 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( ) ; //The disp of A is avilable to obj B
}
}
Every class in java is derived automatically from java.lang.Object class. All classes in java
are subclasses
class A
42
{
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");
}
}
}
}
output :: printing A
43
ref is class A
printing B
ref is class B
printing C
ref is class C
Java has a built in process called garbage collector. It occurs automatically , although we
can not predict when it will happen. Java itself dispose of the memory that no longer has
reference to it. However to make it happen we can set references to null
class A
{
void disp( )
{
System.out.println("from A");
}
}
public class TestApp
{
public static void main(String args[])
{
int a[ ] = { 10,20,30 };
A b1 = new A(); int l ;
b1.disp();
l = a.length;
System.out.println ( "l=" + l );
}
}
class Tester
{
44
public int k;
Tester( int i )
{
k = i;
}
}
class A
{
int m1;
Tester t;
A( )
{
m1 = 5;
t = new Tester(2500);
}
void disp( )
{
System.out.println("from A");
}
}
public class TestApp
{
public static void main(String args[])
{
A b1 = new A();
b1.disp();
b1 = null;
}
}
interfaces :
45
They provide templates of behaviour, that other classes can implement. They define the
design and classes that implement the interface must provide the implementation of the
design.
In Abstract classes some methods may have definition, and leaving few undefined. In
interfaces no method can be defined.
The data members in Abstract class can be variables or constants but they are only
constants in an interface. A class can extend only one abstarct class. But a class may
implement multiple interfaces, and thus provide an indirect way to multiple inheritance.
class Printer
{
public void print()
{
// set the params
// print data .....
}
}
interface Copier
{
public void copyDocument( Document d);
}
interface Fax
{
public void transmitDocument(Document d);
}
Note : A method inside an interface can not be declared private or protected. They can
carry public abstract modifiers only. The members must be public, static final making them
constants.
46
interface Examp
{
public static final int a = 3;
int b = 5; // effectively public static final
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.
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.
import java.io.*;
interface StudentInter
{
void getData( ) throws IOException;
void showData();
int calcTot();
47
float calcPercent();
void menu();
}
switch( n )
{
case 1: tot = s.calcTot();
System.out.println("total =" + tot);
break;
Classes that partially implement an interface must be abstract as they are only expanding
few methods.
49
Example 43 :
interface A
{
void dispone();
void disptwo();
}
abstract class B implements A
{
void disptwo()
{
system.out.println("expanded from b);
}
}
class C extends B
{
void dispone( )
{
System.out.println("expanded from c");
}
}
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.
class A
{
class B
50
{
public void disp( )
{
system.out.print("inside B ..");
}
}
B b1;
A( )
{
b1 = new B( );
b1.disp( );
}
}
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.
import java.io.*;
public class TestApp
{
public static void main(String args) throws IOException
{
ProcessBuilder pb1;
pb1 = new ProcessBuilder("notepad.exe","first.java");
pb1.start( );
}
51
}
52
Chapter 5
Exception Handling
Exception is a runtime error , that may cause abnormal termination of the program
during its execution. When an error occurs within a java method , the method creates an
exception object and hands it off ( Throwing) to the runtime system. This exception object
contain information about exception, its type, state of the program when it occured.
The runtime system searches for appropriate block of code to handle the exception.
If there is no appropriate handler, with in that block the serach progresses up through
the call stack, until an appropriate handler is found. If no such handler is found, the runtime
system stops and the program terminates.
To prevent interuption of the programs flow from exceptions such as the ones shown
above, handlers are used to catch such exceptions and handle them appropriately through
cleanup or message notification.
53
There are three types of Exceptions:
1. Checked Exceptions - These are the exceptions which occur during the compile time of the
program. The compiler checks at the compile time that whether the program contains handlers
for checked exceptions or not. These exceptions do not extend RuntimeException class and
must be handled to avoid a compile-time error by the programmer. These exceptional
conditions should be anticipated and recovered by an application. Furthermore Checked
exceptions are required to be caught.
ClassNotFoundException
NoSuchMethodException
InterruptedException
Unchecked Exceptions - Unchecked exceptions are the exceptions which occur during the
runtime of the program. Unchecked exceptions are internal to the application and extend the
java.lang.RuntimeException that is inherited from java.lang.Exception class. These exceptions
cannot be anticipated and recovered like programming bugs, such as logic errors or improper
use of an API. These type of exceptions are also called Runtime exceptions that are usually
caused by data errors, like arithmetic overflow, divide by zero etc.
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.
As you have come to know that exceptions are Objects that means an object is thrown when you throw
an exception. Moreover only those objects could be thrown whose classes are derived from Throwable.
It is interesting to note here that the objects of your own design could also be thrown provided that they
should be the subclass of some member of the Throwable family. Also the throwable classes which are
defined by you must extend Exception class.
55
Handling Exceptions in java
It is done using five key words try, catch, throw, throws, finally
try
{
// statements that may throw exception
}
catch( Exceptiontype-1 e)
{
// statements to handle
}
catch( Exceptiontype-2 e)
{
// statements to handle
}
finally
{
// clean up code or exit code(optional)
}
The code in the finally block always gets executed regardless of what happens with in the
try block. It is used to close files, data base connections , Sockets etc.
When exception occurs the method may instantiate an exception object and hand it to the
run time system to deal with it.
The 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 ::
The Throwable class provides a set of methods apart from various constructors
Throwable() :
Throwable(String message) :
A stack Trace is a list of methods excecuted in sequence that lead to the exception.
Example 46 ::
try
{
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
c = a/b;
System.out.println("c="+ c);
}
catch ( NumberFormatException e)
{
system.out.println("Invalid argumets");
}
catch ( ArithmeticException e)
{
system.out.println("Second Arg can not be zero");
}
catch ( ArayIndexOutOfBoundsException e)
{
57
system.out.println("pass proper args");
}
The order of catch blocks are important when there are multiple catch blocks. The
exception subclasss must come before any of its super class. Otherwise the subclass
exception never gets executed.
try
{
a = Integer.parseInt(args[0]);
b = integer.parseInt(args[1]);
c = a/b;
System.out.println("c="+ c);
}
catch ( Exception e)
{
System.out.println("It is " + e");
}
catch ( ArithmeticException e)
{
System.out.println("Second Arg can not be zero");
}
System.out.println("program ends here..");
}
}
Each time a try in entered , the context of the Exception is pushed on to the stack. If an
inner try does not have a catch for an exception, the stack is unwound and catch belonging to
next try is inspected for a match.
try
{
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
try
{
c = a/b;
System.out.println("c="+ c);
}
catch ( ArithmeticException e)
{
System.out.println("Sec.Arg cannot be zero");
}
catch ( NumberFotmatException e)
{
System.out.println("Invalid argumets");
}
catch ( ArayIndexOutOfBoundsException e)
{
System.out.println("pass proper args");
59
}
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 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
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
import java.io.*;
class AgeException extends Exception
{
int age;
AgeException(String mesg)
{
super(mesg);
}
AgeException( )
{
super( );
}
}
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() );
}
}
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.
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");
}
catch ( ArithmeticException e)
{
System.out.println("rethrowing now..");
throw e;
}
}
}
65
To Print a Stack Trace Message
Jjava provides a method getMessage() method that is used with an object of the Exception class to
print errors to debug the process. Instead of this this method we can get more information about the
error process if we use print a stack trace from the exception using the printStackTrace() method that is
the method of the Throwable class and prints the stack trace to the console and provides the line
numbers of statements that called the methods in the current stack.
try {
// ......
}
catch (IOException e) {
// ...........
System.out.print("GotException:"+ e.printStackTrace( ) ;
}
They can be used to test the assumptions made by the programmer and create software
according to user requirements
Exceptions test abnormal conditions where as Assertions test the conditions assumed by the
programmer.
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:
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.
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
68
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.
INTERFACES CLASSES
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 ::
AbstractList : Extends AbstractCollection, and implement the List interface. It can access
data randomly using an index value.
LinkedList : Extends AbstractSequentialList where each element knows where is the next
71
ArrayDeque : Implements dynamic deque, by extending AbstractList and,
impl the Deque Interface
Apart from these , we see Arrays, Vector, Stack, Hashtable, Dictionary, properties, and
other classes which are not technically members of this collection framework.
import java.util.*;
class arrays
{
public static void main(String args[])
{
int a[] = new int[10];
72
for(int i = 9; i > 0; i--)
array[i] = -i;
Arrays.sort(a);
A Vector class is similar to ArrayList except that Vector class is synchronized. Multiple
threads can not access it simultaneously. It implement the dynamic array. It predates
collection framework. It has been rewritten to be compatible with collection framework
import java.util.*;
class Testvector
{
public static void main(String args[])
{
Vector v = new Vector(5);
System.out.println("Capacity: " + v.capacity());
v.addElement(new Integer(10));
v.addElement(new Integer(11));
v.addElement(new Integer(22));
v.addElement(new Integer(33));
v.addElement(new Integer(44));
v.addElement(new Double(3.14));
v.addElement(new Float(3.14));
73
System.out.println("Capacity: " + v.capacity());
System.out.println("Size: " + v.size());
System.out.println("First item:"+(Integer)v.firstElement());
if(v.contains(new Integer(33)))
System.out.println("Found 3.");
Iterator e = v.iterator();
while (e.hasNext())
{
s = (String)v.next();
System.out.print(s);
}
}
}
output :
capacity : 5
capacity : 10
size : 7
First item 0
Last item 3.14
Found a 3
10 11 22 33 44 3.14 3.14
Example 58 : Demo of ArrayList ( Dynamic and can grow )
It holds only the objects, and it can grow or shrink at run time.
import java.util.*;
class arraylist
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
al.add("Red");
al.add("Blue");
al.add("Yellow");
74
al.add(1, "White");
al.remove("White");
System.out.println(al);
String l = al.get(1);
System.out.println(l);
Iterator e = al.iterator();
while (e.hasNext())
{
s = (String)e.next();
System.out.print(s);
}
}
}
75
Example 59 : Demo of linkedlist
import java.util.*;
class linkedlist
{
public static void main(String args[])
{
LinkedList<String> ls = new LinkedList<String>();
ls.add("Blue");
ls.add("Green");
ls.add("Yellow");
ls.add("Orange");
ls.addFirst("Red");
ls.addLast("Black");
ls.add(1, "Grey");
System.out.println(ls);
ls.remove("Black");
System.out.println(ls);
ls.removeLast();
System.out.println(ls);
System.out.println("Updating linked list items");
ls.set(0, "java");
ls.set(1, "C");
ls.set(2, "C++");
ls.set(3, "Oracle");
ls.set(4, "ASP.net");
System.out.println(ls);
}
}
76
Example 60 : Demo of HashSet class
It is set of unique elements, and it uses a hash for storing data. As it uses hash methods such
as add, remove, size etc and they take same amount of time. No gurantee of order of storage.
import java.util.*;
class hashset
{
public static void main(String args[])
{
HashSet<String> h1 = new HashSet<String>();
h1.add("Red");
h1.add("Blue");
h1.add("Green");
System.out.println(h1);
int s = h1.size() ;
System.out.println(s);
if( h1.contains("Red"))
System.out.print("Red present" );
}
}
import java.util.*;
class iterator
{
public static void main(String args[])
{
LinkedList<String> l = new LinkedList<String>();
l.add("Item 0");
l.add("Item 1");
l.add("Item 2");
Iterator<String> it = l.iterator();
77
while(it.hasNext())
{
System.out.print(it.next());
}
}
}
import java.util.*;
class listiterator
{
public static void main(String args[])
{
LinkedList<String> li = new LinkedList<String>();
li.add("Item 0");
li.add("Item 1");
li.add("Item 2");
li.add("Item 3");
while(lite.hasNext())
{
lite.set("This is " + lite.next());
78
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>();
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry mp = (Map.Entry) it.next();
System.out.println(mp.getKey() + "/" + mp.getValue());
79
Example 63 : Demo of Hashtable class
It imple the interfaces such as Map,Clonable,Serializable. It is used to store values, in the form
of map key with a value. The "key" should implement the hashcode, and equals method to
store and retrieve values in a hashtable. It was how maps were implemented before collection
framework.
import java.util.*;
class Testhashtable
{
public static void main(String args[])
{
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("B1", "Billgates");
ht.put("C2", "Chouhan");
ht.put("P3", "Pushkal");
ht.put("A4", "Anuj Singh");
Enumeration e = ht.keys();
while(e.hasMoreElements())
{
String s = (String) e.nextElement();
System.out.println("key " + s + "/" + "Val" + ht.get(s));
}
}
}
80
Example 64 : Demo of Hashtable class
import java.util.*;
class Testhashtable
{
public static void main(String args[])
{
Hashtable<String, Integer> ht = new Hashtable<String, Integer>(4);
ht.put("Billgates", Integer(55));
ht.put("Chouhan",Integer( 60));
ht.put("Pushkal", Integer(52));
ht.put("Anuj", Integer(46));
Collection.sort(v);
Enumeration e = v.elements();
// sorted list
while(e.hasMoreElements())
{
String s = (String) e.nextElement();
System.out.println("key " + s + "/" + "Val" + ht.get(s));
}
}
}
81
Example 65 : Demo of enumeration
enum Mango {
Brooks, Manilla, Alphanso, Kesar, Maya
}
class TestMango
{
public static void main (String args[])
{
Mango ap;
System.out.println("Here are all Mango constant:");
Mango allmangos[] = Mango.values();
for(Mango a : allmangos)
System.out.println(a);
System.out.println();
ap = Mango.valueOf(" Kesar");
System.out.println("ap contains"+ap);
}
}
82
Chapter 7
Multi Threading
Multithreading is a concept, where by it is possible to achieve concurrent execution of
multiple units of a single program. A program in java can have multiple flow of controls and
each flow of control is nothing but a small unit of execution, known as a thread. Thus a thread
can run in parallel to the other threads.
In the multithreading concept, several multiple lightweight processes are run in a single process/task or
program by a single processor. For Example, When you use a word processor you perform a many
different tasks such as printing, spell checking and so on. Multithreaded software treats each process as
a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution
running concurrently. It allows a program to be more responsible to the user. When a program contains
multiple threads then the CPU can switch between the two threads to execute them at the same time.
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.
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.
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
84
I. Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure
you have to follow these steps:
The following program demonstrates a single thread creation extending the "Thread" Class:
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[]){
t.start( );
System.out.println("It is:"+Thread.currentThread( ));
}
}
output :
It is : Thread[main,5,main]
0 1 2 3 4 5
86
II. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
The following program demonstrates the thread creation implenting the Runnable interface:
MyThread1(String s1){
s=s1;
t=new Thread(this);
t.start();
}
public void run(){
System.out.println(s);
}
}
public class RunableThread{
public static void main(String args[]){
MyThread1 m1=new MyThread1("Thread started....");
}
}
However, this program returns the output same as of the output generated through the previous
program.
There are two reasons for implementing a Runnable interface preferable to extending the Thread Class:
1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if
you implement Runnable interface then you can do this.
2. The class implementing the Runnable interface can avoid the full overhead of Thread class
which can be excessive.
87
Example 67: Demo of threads implementing Runnable interface
output : It is : Thread[main,5,main]
0 1 2 3 4 5
88
Thread Life-cycle ::
During the life time of a thread it can enter into 5 states and it can move from one state to
other in various ways.
1. 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
Different states implementing Multiple-Threads are:
As we have seen different states that may be occur with the single thread. A running thread can enter to
any non-runnable state, depending on the circumstances. A thread cannot enters directly to the running
state from non-runnable state, firstly it goes to runnable state. Now lets understand the some non-
runnable states which may be occur handling the multithreads.
1 Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to
runnable state later, if a particular event occurs. On this state a thread sleeps for a specified
amount of time. You can use the method sleep( ) to stop the running state of a thread.
3 Blocked on I/O – The thread waits for completion of blocking operation. A thread can enter on
this state because of waiting I/O resource. In that case the thread sends back to runnable state
after availability of resources.
4 Blocked for joint completion – The thread can come on this state because of waiting the
completion of another thread.
5 Blocked for lock acquisition – The thread can come on this state because of waiting to acquire
the lock of an object.
Return
Method Description
Type
90
getName( ) String Retrieve the name of the thread object or instance.
start( ) Void Start the thread by calling its run method.
This method is the entry point to execute thread, like the main
run( ) Void
method for applications.
sleep( ) Void Suspends a thread for a specified amount of time (in milliseconds).
isAlive( ) Boolean This method is used to determine the thread is running or not.
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.
}
}
}
}
try
{
for(int i= 0; i< 10; i++)
{
System.out.println((Thread.currentThread()).getName()+ " thread here...");
Thread.sleep(1000);
}
}
92
catch (InterruptedException e)
{
}
}
}
output :
First thread here..
Third thread here..
Second thread here..
main thread here ...
Second thread here..
First thread here..
.....
93
}
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.");
}
}
A thread calls join () method when it must wait for another thread to complete its task.
CustomThread(String name)
{
super(name);
start();
}
public void run()
{
try
{
for(int i= 0; i< 4; i++)
{
94
System.out.println((Thread.currentThread()).getName()+" thread here...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) { }
System.out.println((Thread.currentThread()).getName() + ending.");
}
}
public class Demoalive
{
public static void main(String args[])
{
CustomThread t1 = new CustomThread("first");
CustomThread t2 = new CustomThread("second");
CustomThread t3 = new CustomThread("third");
try
{
t1.join();
t2.join();
t3.join();
}
catch (InterruptedException e) { }
output :
First ending
Second ending
Third ending
First alive? false
Second alive? false
third alive? false
Thread priority ::
When a new thread is created its priority is equal to the creating thread priority. Every java
thread has a priority between 1 and 10 and by deafult each thread is given a normal priority 5.
The constants defined in the thread class are
Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread.NORM_PRORITY 5
The methods setPriority(), getPriority() can be used to handle priority. This priority is used by
the scheduler to allocate CPU time.
Some java systems support time slicing. It it is available then the sheduler ensures that
several threads of equal priority get executed for a quantum time in a round robin fashion. Low
priority thread never runs as long as there is a runnable high priority thread.
The scheduling is also preemptive. That is higher thread, preempts the lower one.
public Counter(int p)
{
t = new Thread(this);
t.setPriority(p);
}
96
public void start()
{
goflag = true;
t.start();
}
public void run()
{
while (goflag)
c++;
}
t1.start();
t2.start();
t3.start();
try {
Thread.sleep(5000);
}
catch (InterruptedException e) { }
t1.end();
t2.end();
t3.end();
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 ::
class Shared
{
void doWork(String s)
{
try {
Thread.sleep((long) (Math.random() * 500));
}
catch (InterruptedException e) { }
}
}
99
public class SynchDemo
{
public static void main(String args[])
{
try {
t1.join();
t2.join();
t3.join();
catch(InterruptedException e) { }
}
}
output : Starting one
starting three
starting two
ending three
ending two
endig one
class Shared
{
try {
Thread.sleep((long) (Math.random() * 500));
}
catch (InterruptedException e) { }
try {
t1.join();
t2.join();
t3.join();
catch(InterruptedException e) { }
}
}
101
output Starting one
ending one
starting two
ending two
starting three
ending three
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.
class Shared
{
void doWork(String s)
{
System.out.println("Starting " + s);
try {
Thread.sleep((long) (Math.random() * 500));
}
catch (InterruptedException e) { }
try {
t1.join();
t2.join();
t3.join();
}
catch(InterruptedException e) { }
}
}
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.
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
class Queue
{
int n;
Producer( queue q)
{
this.q = q;
new Thread(this,"producer").start();
}
consumer( queue q)
{
this.q = q;
new Thread(this,"consumer").start();
}
output ::
put : 0 Got : 0 Put : 1 Got : 1 put : 2 Got : 2
put : 3 Got : 3 Put : 4 Got : 4 put : 5 Got : 5
put : 6 Got : 6 Put : 7 Got : 7 Got : 7 Got : 7
put : 8 put : 9 Got : 9
Not corect result. After producer put 7, the consumer started and got the same 7 three times
in a row. Then producer resumed and puts 8, 9 simultaneously and consumer consumes 9
Example 70 : inter thread communication - correct results
class Queue
{
boolean flag = true;
int n;
106
synchronized void put( int n )
{
if (flag)
{
this.n = n;
system.out.println(" put : " + n);
flag = false;
notify( );
}
else
{
try
{
wait( );
}
catch ( Exception e) { }
}
}
}
Producer( queue q)
{
this.q = q;
new Thread(this,"producer").start();
}
consumer( queue q)
{
this.q = q;
new Thread(this,"consumer").start();
}
}
}
output :
put : 0 Got : 0 Put : 1 Got : 1 put : 2 Got : 2
put : 3 Got : 3 Put : 4 Got : 4 put : 5 Got : 5
put : 6 Got : 6 Put : 7 Got : 7 put : 7 Got : 7
put : 8 Got : 8 put : 9 Got : 9
108
Synchronizing classes ::
Semaphore, CyclicBarrier, CountDownLatch, Exchanger are all classes added to java to act as
synchronizers. Each of them have methods that the threads may call.
Concurrent programming ::
While writing multithreaded programs, some of the issues that may create diffculties are
1. No way to back off from an attempt to acquire a lock that is already held or give up after
waiting for a specified time, or cancel a lock attempt after an interrupt.
2. Sync is done in block structured fashion. No way to acquire lock in one method and
release it in another.
Thre are some drawbacks in wait(), notify() and they are enhanced with new mechanisms, and
placed as a part of java.util.concurrent package. This package provide all the standard
concurrency utilities. using this package, helps scalable, easy to write and
maintainableapplication developement but programmer is responsible to see that the
applications a re free from deadlock, CPU starvation.
Chapter 8
Packages
It is a mechanism for grouping classes, interfaces and sub packages. The java API itself is
implemeted as a group of packages.
Java supports two types of packages as shown below in the hierarchy structure:
109
Build-In Packages in Core Java:
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.
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.
C) To resolve name conflicts of a class from more than one package, use full pack name while
qualifying the object
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!");
}
}
C:\mypackage>javac
HelloWorld.java
If you try to run this program, you will get the following exceptions (or error):
C:\mypackage>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError:
HelloWorld (wrong name: mypackage/HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
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.
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
C:\javac -d <target_directory> <complete_directorypath>
Suppose, you want to save the compiled package to the location "D:\myfolder" then type the following
command shown as:
This command puts the folder "india" along with its subfolders and the class file "HelloWorld.class" to
the new location as D:\myfolder.
There are two ways so that you can use the public classes stored in package.
Lets see an example importing the created package into the another program file.
package importpackage;
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();
}
}
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:
We can also put a package inside an another package. The packages that comes lower in the naming
hierarchy are called "subpackage" of the corresponding package higher in the hierarchy i.e. the package
that we are putting into another package is called "subpackage". The naming convention defines how to
create a unique package name, so that packages that are widely used with unique namespaces. This
allows packages to be easily managed. Suppose we have a file called "HelloWorld.java". and want to
store it in a subpackage "subpackage", which stays inside package "importpackage". The "HelloWorld"
class should look something like this:
package importpackage.subpackage;
import importpackage.subpackage.*;
class CallPackage{
public static void main(String[] args){
HelloWorld h2=new HelloWorld();
h2.show();
}
}
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:
package college;
public class Student
{
String rno, name;
115
public void setStudent(String rno,String name)
{
this.rno = rno; this.name= name;
}
package college;
import college.*;
public class Testpack
116
{
public static void main(String args[])
{
Student s = new Student();
Teacher t = new Teacher();
s.setStudent("Preethi", "R10017");
t.setTeacher("Pushkal", "Ph.D");
s.dispStudent();
t.dispTeacher();
}
}
During the compile time, when an object is encountered, for its class definition the compiler
looks at all imported packages and if finds, it proceeds further with out including any code.
During run time, the interpretor calls a class loader, and this loader loads the corresponding
class.
Chapter 9
Java Applets
WWW::
The WWW is a collection of electronic documents that are linked together. These documents
are known as web pages and a collection of related web pages is known as web site.
117
A web site resides on a server computer that are located around the world and the
information on the WWW is always accessible.
Web Browser:
Web browser is a program that is used to access WWW. It allows the users to view the web
pages and to navigate betwen them. They are also called universal clients as they are common
to the clients for all web based applications
Web Server :
It is a server program running on a computer whose purpose is to serve web pages to the
other computers when requested.
Ex : Apache , IIS, iPlanet
HTML :
It is a markup language Used to create documents on WWW. It gives guidelines for displaying
information through tags. Tags are enclosed within angular brackets < >.
URL :
It is a unique address used to identify each web page or a resource on the internet. It indicates
where the page is stored on the net. It is called the internet address of a resource on the
WWW. Along with the protocol to access. They are used by browser to connect to a specific
server and to get a specific document or page.
Ex : http://www.infosys.com/index.html
protocol://ServerDomainName/Path name
protocol://ip address/Path Name
The URL may contain port to connect to, and also the data typed by the user in the form to be
submitted to the application
HTTP 1.0 was the original version. The client would initiate and close the connection to the
server on each request. The performance is poor because it has to make new TCP/Ip connection
for every request.
118
For example if a page index.html is accessed by the client and the page contain 10 image files
in its body, the browser has to initiate and close the connection 11 times. The client has to
open a new TCP/IP connection and places a request for the resource, and on receipt close the
connection and repeat it for each picture to be downloaded.
HTTP 1.1 latest version, and here the connection once established is maintained until the
browser is closed. It is called persistent connection. So many requests can occur within a single
TCP/IP connection.
APPLETS
They are small java programs used in internet computing. They can display graphics, play
sounds, accept user inputs, create animation perform arithmetic operations and enable
creation of interactive web documents. Applets are used when we need something dynamic
to be included in a web page. They are event driven window based java programs.
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
void init() :
void start() :
void stop() :
void destroy() :
void paint() :
URL getCodeBase() :
URL getDocumentBase():
Image getImage() :
Appletcontext getAppletContext() :
Once an Applet's ".class" file is created it is uploaded to an ISP or viewed on the local machine,
by setting its protection for read.
init() :
It is called when the applet is loaded or reloaded for the first time into a browser. It is called
only once in the life cycle. The browser calls this method after the constructor of the applet is
called.
120
But most of the initilization is done in the init() such as creating helper objects, seting up
fonts, images , reading and parsing parameters.
start() :
It is called after the init() is completed. It is also called whenever the user leaves a page and
returns back. It is called when you minimize and then maximize a page.
Unlike init() it can happen many times through the life cycle.
stop() :
It runs when the user leaves the current web page. By default, when the user leaves the web
page, or a window minimized, any threads the applet had started will continue running. By
using this method we can suspend such threads, and restart them when the applet is viewed
again.
destroy() :
It is called to terminate the applet. It runs either before the applet exits or before the browser
exits. It is usefull for cleanup operations such as releasing memory after the applet is removed,
killing threads, closing network,database connections or releasing all resources that were
initialized during an applets initialization.
Paint() :
The paint() is used by applet to draw something to the screen. It can be called several times in
the life cycle of an applet. It is a method inherited from Component class. It takes one
parameter of type Graphics class. When paint() is called, an instance of Graphics class is
created by the browser and handed over to the applet.
121
Example 81 ::
import java.applet.Applet;
import java.awt.*;
Testing Applets :
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.
< html>
<head> <title> First Applet </title></head>
<body>
<applet code = "Appex" width = 200 height = 200>
</applet>
</body>
</html>
to run the applet save the above html file as a webpage and then open it through any
browser.
122
Running using Appletviewer :
< applet>
[codebase = urlBase]
code = classfile
width = pixels
height = pixels
[name = applet instance Name]
........
[param name = paraName value = "paramvalue"]
</applet>
codeBase : It specify the directory which is to be searched for the applets .class file.
Normally the directory of the HTMl file is searched for the .class file. This will be in the form of
a URL. But applets ".class" file need not be in the same host where HTML file is loaded.
Ex : Codebase = http://www.au.ac.in
Then HTML file can be anywhere but ".class", file is searched from the above URL.
getCodeBase(), getDocumentBase() can give the directory of applet codes ".class" file,
and HTML document files.
code : It refers to the name of applets, ".class" file. It is relative to the base URL but not
absolute URL
Name : It referes to the name of the applets instance It is used by applets to communicate
with each other on the same HTML page. the method getApplet() defined under
AppletContext interface can be used to get the instance name.
width, height : They refer to the size of panel in the browser window.
param : It specify name ,value pairs. The value can be obtained using getParameter()
method.
import java.applet.*;
124
import java.awt.*;
/* <APPLET CODE=Appex.class WIDTH=200 HEIGHT=200 >
</APPLET> */
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!");
}
}
125
msg = "Code base: " + u.toString();
g.drawString(msg, 10, 20);
steps :
create an image object
associate a graphics file with the image object
display the image
import java.applet.*;
import java.awt.*;
public class Appex extends Applet
{
public void init()
{
Image p;
p = getImage(getCodeBase(),"images/running.gif");
}
getImage() takes two parameters. A base URL, and a string giving the path or filename in
relation to URL.
import java.applet.*;
import java.awt.*;
public class Appex extends Applet
{
126
public void init()
{
AudioClip p;
p = getAudioClip(getCodeBase(),"songs/jana.audio");
}
import java.applet.*;
import java.awt.*;
import java.net.*;
String sf;
AudioClip ac;
URL u = null;
String msg = " ";
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.
The example below is an applet which request the browser to how another web page. The
ShowDemo.java, applet will instruct the browser to display the Samppage.html. For testing
we have a html page by name showtest.html which can be viewed by internet explorer.
A. showtest.html
< html>
<head> <title> Action page </title></head>
<body>
<applet code = "ShowDemo" width = 300 height = 300>
<param name = dname value = "file:\\c:\Samppage.html">
</applet>
</body>
128
</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 = " ";
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.*;
import java.awt.*;
import java.applet.*;
130
public class ImageApplet extends Applet implements Runnable
{
Image img;
boolean drawn = false; // determines whether to draw
Thread t;
if (drawn)
{
drawn = false;
}
else
{
g.drawImage(img, 20,20,this);
drawn = true;
}
131
}
132
Chapter 10
The AWT has a set of classes that provide user interface elements such as window, menu,
button,list, etc. and controls for colors, and fonts.
AWT Hierarchy ::
Component
|
Container
|
_____________
| |
Panel Window
_|______
| | |
Applet Dialog Frame
Component::
It is responsible for remembering the current foreground and background colors and font.
Methods commonly used are ::
add( )
addXxxListener()
removeXxxListener
repaint()
setVisible()
setSize()
133
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.
show()
hide()
addWindowListener( )
Frame:
Frame is a subclass of Window and has a title bar, menu bar, borders and resizing corners.
methods :: setSize( )
setTitle( )
Dialog ::
They are the pop up windows which can accept input from the user. They are two types
1. Modal 2. Modeless
Panel::
It is subclass of Container. It adds no new methods but simply implements container. Panel is
the super class of Applets. When screen output is directed to an applet, it is drawn on the
surface of a Panel object. A Panel is a window that does not contain a title bar, menu bar or
border. It can not be a top level window. ( When you run an applet using an applet viewer, the
applet viewer provides the title and border ).
134
Event Handlers :
An event is generated when an action occurs such as mouse click on a button, or enter key
pressed on a text field. They are handled by listener classes which implement listener
interfaces.
Canvas ::
It is a blank window but not a part of Applet or Frame. It is a drawing surface used for
drawing images and graphics operations.
Label ::
Method Action
Label l1,l2,l3;
Font f1;
l3 = new Label("Course");
add(l3);
}
}
Button ::
import java.awt.*;
import java.applet.*;
}
}
CheckBox ::
Methods
boolean getState() Returns true or false, based on whether the checkbox is selected or not
void setState(Boolean state) Changes the checkbox's state to selected (true) or unselected
(false)
import java.applet.*;
import java.awt.*;
c1 = new Checkbox("Shoes");
add(c1);
c3 = new Checkbox("Shirt");
add(c3);
}
137
}
Example 95 : Demo of Radio box
import java.awt.*;
CheckboxGroup cg;
Checkbox c1,c2,c3;
Choice ::
import java.awt.*;
public class ChoiceTest extends java.applet.Applet
{
Choice ch;
public void init( )
138
{
ch = new Choice( );
ch.add("apples");
ch.add("oranges");
ch.add("strawberies");
ch.add("bananas");
add(ch );
}
}
TextField ::
import java.awt.*;
Label l1,l2;
TextField t1,t2;
t1 = new TextField(20);
add(t1);
l2 = new Label("password");
add(l2);
t2 = new TextField(20);
t2.setEchoChar('*');
add(t2);
139
}
}
TextArea::
insert (String text, int index) inserts text at the specified position.
import java.awt.*;
TextArea ta;
List ::
int [ ] getSelectedIndexs() Gets index of the currently selected item
String[ ] getSelectedItems() Gets string representation of Choice
import java.awt.*;
add(lt);
}
}
ScrollBar::
int getValue() Gets current value of Scrollbar
void setValue(int value) Sets value of Scrollbar to a given value
import java.awt.*;
public class Scroll extends Applet
{
Scrollbar b1 = new Scrollbar(Scrollbar.VERTICAL, 10, 1, 1, 100);
import java.awt.*;
import java.applet.Applet;
Frame w;
Label l1,
TextField t1;
w.resize (300,200);
w.show( );
}
}
public Demotest( )
{
l1 = new Label("Name");
add(l1);
t1 = new TextField(20);
add(t1);
l2 = new Label("Password");
add(l2);
t2 = new TextField(20);
t2.setEchoChar('*');
add(t2);
142
resize(200,200);
show();
}
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.
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.
Card Layout ::
It presents different screens to a user based on a stack of cards. One can flip to the first,
second or last card using methods defined by CardLayout. Each container in the group is card.
A name is given to each card and we can display a card by using a method show( ) as :
143
show( container of all cards, name of card);
GridBag Layout::
It is similar to the GridLayout layout manager because the Panel is divided into a grid of cells
with rows and columns. In GridBagLayout, however the individual components,can be resized
by assigning weights. The helper class GridBagConstraints holds all the information needed
by the GridBagLayout class to properly position and size each UI component. The following is a
list of the GridBagConstraints member variables and their default values that are used to
define UI components placement:
The constraints can be created by the GridBagConstraints object using its constructor and
set the following constraints for the individual components using setConstraints( ) method.
• gridx, gridy
• weightx, weighty
• gridwidth, gridheight
• fill
• GridBagConstraint.NONE
• GridBagConstraint.HORIZONTAL ,
• GridBagConstraint.VERTICAL
• GridBagConstraint.BOTH
• Insets
• Anchor
• ipadx,ipady
import java.awt.*;
public class Demoflow extends Applet
{
Button b1,b2,b3,b4;
144
FlowLayout fl;
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);
}
}
import java.awt.*;
public class Demogrid extends Applet
{
Button b1,b2,b3,b4;
GridLayout gr;
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;
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);
}
}
import java.awt.*;
public class DemoCard extends Applet
{
CardLayout ca = new CardLayout( );
Label [ ] lb = new Label[5];
146
// An array of Labels to display as static text on each card
setLayout(ca);
GridBagLayout gl;
GridBagConstriants gbc;
b1 = new Button("Java");
b2 = new Button("Oracle");
b3 = new Button("XML");
b4 = new Button("JScript");
147
b5 = new Button("J2EE");
b6 = new Button("C++");
gl = new GridBagLayout( );
gbc = new GridBagConstraints( );
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);
}
}
public Demopan( )
149
{
setSize(300,300);
setVisible(true);
setTitle("Panel Demo");
setBackground(Color.yellow);
setLayout( new FlowLayout ( ) );
p = new Panel( );
p.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);
}
150
Chapter 11
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
151
Scrollbar AdjustmentListener adjustmentValueChanged( AdjustmentEvent e)
ActionEvent ::
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
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
TextEvent :: It occurs,
MouseEvent :: It occurs,
1. When user clicks or moves the mouse pointer
WindowEvent :: It occurs,
1. When a window minimized, opened, activated etc.,
FocusEvent :: It occurs,
1. When a component gains or loses focus
KeyEvent ::
1. It is generated by the user during interaction
from keyboard
153
Example 111 : Demo Button Events
Button b1,b2;
GridLayout gl;
l1 = new Label("Firstnumb" );
add(l1);
t1 = new TextField(10);
add(t1);
l2 = new Label("Secondnumb" );
add(l2);
t2 = new TextField(10);
add(t2);
t3 = new TextField(10);
add(t3);
b1 = new Button("ADD");
add(b1);
b1.addActionListener(this);
b2 = new Button("SUB");
add(b2);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
154
if(e.getSource() == b1)
{
int p = Integer.parseInt( t1.getText() ) + Integer.parseInt( t2.getText() );
t3.setText( String.valueOf(p) );
}
if(e.getSource() == b2)
{
int p = Integer.parseInt( t1.getText() ) - Integer.parseInt( t2.getText() );
t3.setText( String.valueOf(p) );
}
}
}
Example 112 : Demo CheckBox Events
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
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
}
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!");
}
}
}
t1 = new TextField(20);
add(t1);
}
public void itemStateChanged(ItemEvent e)
{
String k = ((Checkbox) e.getItemSelectable()).getLabel();
t1.setText("Radio button " + k + " clicked!");
}
}
157
Example 115 : Demo List Events- single select
l1 = new List(4);
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);
l1.addActionListener(this);
}
t1.setText( n );
}
}
}
String s[];
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);
if(e.getSource() == b1)
{
s = l1.getSelectedItems();
159
t1.setText(ot);
}
}
}
Choice c1;
Button b1;
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
}
161
Example 118 : Demo Scroll Events
t1 = new TextField();
add("Center", t1);
}
if(e.getAdjustable() == vS1)
{
vS2.setValue(vS1.getValue());
162
t1.setText("From Vertical " + vS1.getValue());
}
if(e.getAdjustable() == hS2)
{
hS1.setValue(hS2.getValue());
t1.setText("From Horizontal " + hS2.getValue());
}
if(e.getAdjustable() == vS2)
{
vS1.setValue(vS2.getValue());
t1.setText("From Vetical " + vS2.getValue());
}
}
}
{
String str=" ";
int X=0,Y=0;
X=0; Y=10;
str= "Mouse Clicked";
repaint( ) ;
}
164
public class Demokey extends Applet implements KeyListener
{
String text = "";
CardLayout cl;
CardPanel p1, p2, p3;
add("first", p1);
add("second", p2);
add("third", p3);
cl.show(this, "first");
}
switch(++index)
{
case 1: cl.show(this, "first");
break;
con.weighty = 1;
con.fill = GridBagConstraints.BOTH;
con.weightx = 1;
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();
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.
if(e.getSource() == b2) {
wind.setVisible(false);
}
}
169
}
Demowin(String title)
{
super(title);
setLayout( new FlowLayout() );
addMouseListener(this);
}
} );
else
170
{
l.setText( "Right mouse down at"+e.getX()+","+ e.getY() );
}
}
{
l.setText( "Mouse clicked at " + e.getX()+","+e.getY() );
}
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.
172
Example 125 : Demo of Menus
Label l;
Testwind(String title)
{
super(title);
l = new Label("Hello from Java!");
173
mb = new MenuBar();
m = new Menu("File");
mb.add(m);
setMenuBar(mb);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
setVisible(false);
}
} );
174
Example 126 : Demo of Menus, submenu, CheckMenuitem etc.,
MenuBar mb;
Menu m, s;
Label l;
CheckboxMenuItem mi3;
Testwind(String title)
{
super(title);
l = new Label("Hello from Java!");
mi3.addItemListener(this);
m.add(mi3);
m.addSeparator();
si1.addActionListener(this);
si2.addActionListener(this);
si3.addActionListener(this);
s.add(si1);
s.add(si2);
s.add(si3);
mi2.add(s);
m.addSeparator();
mb.add(m);
setMenuBar(mb);
176
addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
setVisible(false);
}
} );
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == mi1)
label.setText("You chose item 1");}
else
if(e.getSource() == mi2)
{
mi2.setEnabled(false);
l.setText("You chose item 2");
}
else
if(e.getSource() == si1)
l.setText("You chose sub item 1");
else
if(e.getSource() == si2)
l.setText("You chose sub item 2");
else
if(e.getSource() == si3)
l.setText("You chose sub item 3");
else
if(e.getSource() == mi4)
setVisible(false);
}
}
else
l.setText("Item 3 is not checked");
}
}
}
pp.add(mi1);
pp.addSeparator();
pp.add(mi2);
pp.addSeparator();
178
pp.add(mi3);
pp.addSeparator();
pp.add(mi4);
add(pp);
add(l);
addMouseListener(this);
}
if(e.getSource() == mi1)
l.setText("You chose item 1");
179
else if(e.getSource() == mi4)
l.setText("You chose item 4");
}
}
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.
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.
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( );
}
}
{
myFrame( String title )
{
super(title);
Menubar mb = new MenuBar( );
setMenuBar(mb);
mb.add(m);
mi2.addActionListener(this);
}
if (e.getSource() == mi2)
{
}
}
181
}
{
TextField t1;
glass( )
{
t1 = new TextField(20);
add(t1);
}
}
Button bp,bs,bm,bd,bpo,be,bon;
182
digits( )
{
setlayout( new GridLayout(5,4));
}
}
public class Democal extends Applet implements ActionListener
{
float m,n; char f;
glass p; digits d;
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);
}
{
if( e.getSource( ) == d.bo)
p.t1.setText( (p.t1.getText( ) + d.b0.getlabel( ) );
184
if( e.getSource( ) == d.b3)
p.t1.setText( (p.t1.getText( ) + d.b3.getlabel( ) );
185
if( e.getSource( ) == d.bm)
{
m = Float.parseFloat(p.t1.getText( ) );
p.t1.setText(" ");
f = 'm';
}
if( e.getSource( ) == d.bd)
{
m = Float.parseFloat(p.t1.getText( ) );
p.t1.setText(" ");
f = 'd';
}
if ( f == 's')
{
n = (m - Float.parseFloat(p.t1.getText( ) ) );
p.t1.setText( String.valueOf(n));
}
if ( f == 'm')
{
n = (m * Float.parseFloat(p.t1.getText( ) ) );
p.t1.setText( String.valueOf(n));
}
if ( f == 'd')
186
{
n = (m / Float.parseFloat(p.t1.getText( ) ) );
p.t1.setText( String.valueOf(n));
}
}
}
}
Example 130 : Demo of Menus
Testwind(String title)
{
super(title);
t = new TextField(20);
mb = new MenuBar();
m1 = new Menu("study");
m2 = new Menu("Place");
setMenuBar(mb);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == mi1)
t.setText("Your study is MCA");}
else
if(e.getSource() == mi2)
t.setText("Your study is B.Tech");
else
if(e.getSource() == mi3)
t.setText("You are in Univ");
else
if(e.getSource() == mi4)
t.setText("You are in affl coll");
}
b2 = new Button("hide");
add(b2);
b2.addActionListener(this);
if(e.getSource() == b2)
{ w.setVisible(false); }
}
}
Coursemenu( )
{
setLayout( new GridLayout(4,1));
cg = new CheckboxGroup( );
c1 = new Checkbox("Basics", cg, false);
add(c1) ;
189
c2 = new Checkbox("Web", cg, false);
add(c2) ;
{
Checkbox i1,i2,i3,i4,i5,i6;
Contentmix( )
{
setLayout( new GridLayout(3,2) );
{
Coursemenu p1; Contentmix p2;
190
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);
p2.i3.setState(true);
p2.i4.setState(true);
p2.i5.setState(false);
p2.i6.setState(false);
p2.i3.setState(false);
p2.i4.setState(false);
191
p2.i5.setState(true);
p2.i6.setState(true);
}
}
int x=0,y=0,w=0;
Thread p = null;
try
{
192
Thread.sleep(500);
}
catch(InterruptedException e)
{ }
}
}
public void paint(Graphics g)
{
g.drawString("java", x,y);
}
}
193
Chapter 11
Java uses streams to handle I/O operations through which the data is flowed from one location
to another. For example, an InputStream can flow the data from a disk file to the internal memory and
an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text
file or a binary file.
A Stream is an abstraction for the source or destination of data. The source or destination can
be anything , disk, memory buffer, network connection.
A Stream will have methods to operate on the data from the source or destination tied
with them.
Types of Stream
An Input stream reads data where as an output stream write data. Byte streams read or write
bytes where as charcter streams read or write characters.
Stream methods are synchronized and they will wait for the data to be avialable then perform
operation, and return. Lowlevel streams work with raw bytes, as stored by the file system 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.
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);
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
Example 141 : Demo of of FileOutputStream
import java.io.*;
f1.close();
f2.close();
f3.close();
}
}
They permit reading or writing of primitive data types. After read we have to use methods to
convert them to character, or string inorder to understand
import java.io.*;
public class DemoDataIO
{
public static void main(String[] args) throws IOException
{
DataOutputStream out = new DataOutputStream( new FileOutputStream("datas.txt" ));
double[] prices = { 9.99, 4.99, 15.99, 3.99 };
int[] units = { 12, 6, 10, 9 };
String[] descs = { "mangos", "oranges ", "apples", "corn"};
197
for (int i = 0; i < prices.length; i++)
{
out.writeDouble(prices[i]);
out.writeChar('\t');
out.writeInt(units[i]);
out.writeChar('\t');
out.writeChars(descs[i]);
out.writeChar('\n');
}
out.close();
double price;
int unit;
String desc;
double total = 0.0;
try {
while (true)
{
price = in.readDouble();
in.readChar(); // throws out the tab
unit = in.readInt();
in.readChar(); // throws out the tab
desc = in.readLine();
System.out.println( price );
System.out.println( unit );
System.out.println( desc );
total = total + unit * price;
}
}
catch (EOFException e)
{
}
in.close();
}
198
}
Character Streams
They support Reader, Writer Abstract classes for reading or writing 16 bit charcter inputs or
outputs. These abstract classes have child classes to support operations.
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.
import java.io.*;
class Demotest
{
public static void main(String args[]) throws Exception
199
{
char data[ ] ={ 'T', 'h', 'i', 's', ' ' ,
f1.close();
f2.close();
f3.close();
}
}
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.*;
bf.close( );
f.close( );
}
}
import java.io.*;
class InputStreamReaderDemo
{
public static void main(String args[])
{
try
{
int c;
{
System.out.print( (char) c);
}
}
catch (IOException e)
{ }
}
}
Object Serialization
It is a process of writing objects to a stream, and reading them back when wanted.
201
We use ObjectInputStream, ObjectOutputStream classes respectively which are derived from
InputStrem, OutputStream classes to handle the Objects which are called object streams.
import java.io.*;
i1 = new NewString("");
o1 = new NewString("Hello from Java!");
try
{
ofo.writeObject(o1);
ofo.flush();
ofo.close();
202
FileInputStream fi= new FileInputStream ( testobj.dat");
ObjectInputStream ofi = new ObjectInputStream(fi) ;
i1 = (NewString)ofi.readObject();
i1.dispdata();
ofi.close();
}
catch(Exception e) { }
System.out.println(i1);
}
}
import java.io.*;
import java.util.*;
public Student( )
{ }
203
public String getName( )
{
return name;
}
}
public class DemoObj
{
public static void main(String args[])
{
Student i1, i2, o1,o2;
o1 = new Student(213, "Preethi");
o2 = new Student(123, "Pushkal");
try
{
ofo.writeObject(o1);
ofo.writeObject(o2);
ofo.flush();
ofo.close();
i1 = (Student)ofi.readObject();
i2 = (Student)ofi.readObject();
ofi.close();
}
catch(Exception e)
{ }
System.out.println(i1);
System.out.println(i2);
}
}
204
StreamTokenizer
It is used to break the input stream into tokens, such as words.
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.
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
205
File f1 = new File("file.txt");
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.
206
String info;
info = cls.getName(); // It will show java.lang.Integer
System.out.println(info);
}
}
we describe how to retrieve method name by using the getMethods() method. Define a class named
"Demomethod" and then create an object of this class and get the reference of java.util.Integer.class
into it. Now retrieve the method name by using the getMethods() method.
import java.lang.reflect.*;
Now we discuss, how to retrieve the information about the constructor by using the
getConstructors() method. Declare a class "Democon" and then create an object of this class
and take the reference of the class java.util.Integer.class into it. Make a Constructor named
con. Now retrieve the name of the constructor by using the getConstructors() method.
import java.lang.reflect.*;
Now we tell how to retrieve an object name that reflects the package name by using the
object.getClass() method.
Create a class "Demoobject" with an object Checkbox. Now retrieve an object name that
reflects the package name by using the ob.getClass() method.
import java.lang.reflect.*;
import java.awt.*;
208