0% found this document useful (0 votes)
37 views

Unit 4-Java IN R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Unit 4-Java IN R&R

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 88

TYPE CASTING

Type casting:
Converting one data type into another data type is called “type casting” or
simply “casting”. By using Type casting we can convert primitive data type into
another primitive data type and referenced data type into another referenced
data type. But we cannot convert primitive data type into a referenced data type
by using casting.

Casting Primitive Data Types:


The primitive data types are classified into two types, lower types and
higher types. Naturally, the lower types which use less memory and can represent
the lesser number of digits in values. The higher types use more memory and can
represent more number of digits.
To convert a primitive data type to another primitive data type can be done
in can two ways,
1. Widening
2. Narrowing
Widening: Converting a lower data type into higher data type is called widening.
Example: 1
char ch= ‘a’;
int num=(int)ch;//num contains 65,the ASCII
value of ‘A’
In the above example we are converting char type variable into int type

Example: 2
int x=9500;
float sal=(float)x; // sal contains 9500.0
In the above example we are converting int type variable x into float.

Narrowing: Converting higher data type into a lower data type is called narrowing
Example: 1
int n=66;
char ch=(char)n; // ch contains ‘B’
In the above example we are converting int type n value into char type.

Example: 2
double d=12.6789;
int n=(int d); //n stores 12.
In the above example we are converting double type into int type.
Casting Referenced Data Types:
A class is a referenced data type. Converting a class type into another class type is
also possible through casting. But the classes should have some relationship
between them by the way of inheritance.

University super class

College sub class

Department sub-sub class


In the diagram we can convert a college class into university class and department
class into college class. Since the college and department classes are the sub
classes. Department, college and university have a relation by way of inheritance.

Widening the referenced data types:


To widening the referenced data types we take the super class and sub
class. We do widening by using super class reference to refer to sub class. In this
case, we convert the sub class object type as super class type.
Narrowing in referenced data types:
Narrowing represents converting super class type into sub class type. To
perform this task we have to create object to the subclass and use narrowing.
Program:
//Narrowing using sub class object
class One
{
void show1()
{
System.out.println(“super class method”);
}
}
class Two extends one
{
void show2()
{
System.out.println(“Sub class method”);
}
}
class Cast
{
public static void main(String args[])
{
One.o;
o=new Two();
Two t=(Two)o;
// type as Two’s type
t.show1();
t.show2();
}
}
Output:

C:\> javac Cast.java

C:\> java Cast

Super class method

Sub class method

Cloning The Class Objects:

The process of creating an exact copy of an existing copy is called ‘cloning’. In


cloning, already an object should exist and when we clone the object, a bit wise
copy of the object will result. The original object and the cloned object will bw
exactly the same bit to bit. If the original object has some data in it, it also
automatically comes into cloned object.

*Program: Write a program to make cloning Employee class object by writing our
own myClone() method, from where Object class clone() is called.
//cloning example
class Employee
{
//instance variables defined
int id;
String name;
Employee(int id, String name)//constructor to initialize
variables
{
this.id=id;
this.name=name
}
void getData() //method to display the details
{
System.out.println(“Id=”+id);
System.out.println(“Name=”+name);
}
//clone the present class object
public object myClone() throws
CloneNotSupportedException
{
return super.clone();
}
}
class CloneDemo
{
public static void main(String args[])
{
Employee e1=new Employee(10, “Srinivas”);
System.out.println(“Original object:”);
e1.getData();
Employee e2=(Employee)e1.myClone();
System.out.println(“Cloned object:”);
e2.getData();
}
}
Output:
C:\> CloneDemo.java

C:\>java CloneDemo

Original object:

Id =10

Name=Srinivas

Cloned object:

Id= 10

Name= Srinivas

ABSTRACT CLASSES
We know that class is a model for creating objects. A class contains description of
properties or variables and actions or methods of its objects. If an object has
properties and actions as mentioned in the class, then the object is belongs to the
class. If method is written in the class, it is available as it is to all of the class
objects.
Program: Write a program where Myclass’s calculate() method is available to
all the objects and hence every object can calculate the square value.
// All the objects sharing the same method
class Myclass
{
//method to calculate square value
void calculate(double x)
{
System.out.println(“square=”+(x*x));
}
}
class Common
{
public static void main(String args[])
{
//create 3 objects
Myclass obj1=new Myclass();
Myclass obj2=new Myclass();
Myclass obj3=new Myclass();
// call calculate() method from the objects
obj1.calculate(3);
obj2.calculate(4);
obj3.calculate(5);
}
}
Output:

C:\> javac Common.java

C:\> java Common

Square=9.0

Square=16.0

Square=25.0

Abstract Method And Abstract Class:


An abstract method does not contain any body. It contains only the method
header. So we can say it is an incomplete method. An abstract class is a class that
generally contains some abstract methods. Both the abstract class and abstract
methods should be declared by using the keyword ‘abstract’.
Since, abstract class contains incomplete methods, it is not possible to
estimate the total memory required to create the object. So, JVM cannot create
the objects to an abstract class. By using the concept of inheritance, all the
abstract methods should be implemented (body should be written) in the sub
classes. Then, it is possible to create objects to the sub classes since they are
complete classes.
Program: Write a program to create one abstract class and abstract method ehich
has got various implementations in sub classes.
// All the objects need different implementation of the
same method
abstract class Myclass
{
Abstract void calculate(double x);//this is abstract
method
}
class Sub1 extends Myclass
{
void calculate(double x)//calculate square value
{
System.out.println(“square=”+(x*x));
}
}
class Sub2 extends Myclass
{
void calculate(double x)//calculate square root value
{
System.out.println(“square root=”+Math.sqrt(x));
}
}
class Sub3 extends Myclass
{
void calculate(double x)//calculate cube value
{
System.out.println(“Cube=”+(x*x*x));
}
}
class Different
{
public static void main(String args[])
{
//create sub class objects
Sub1 obj.1=new Sub1();
Sub2 obj.2=new Sub2();
Sub3 obj.3=new Sub3();
//let the objects call and use calculate() method
obj1.calculate(3);//calculate square
obj2.calculate(4);//calculate squareroot
obj3.calculate(5);//calculate cube value
}
}
Output:
C:\> javac Different.java

C:\> java Different

Square=9.0

Square root=2.0
Cube=125.0

*Program: Write a java Program for calculating electricity bill for commercial and
domestic plans by using abstract class

//calculating electricity bill for commercial and domestic plans


abstract class Plan
{
//take rate as protected to access it in sub class
protected double rate;
public abstract void getRate();//depending on the Plan we declare abstract method
public void calculateBill(int units)//calculate the electricity bill by taking the units
{
System.out.println(“Bill amount for”+units+”units”);
System.out.println(rate*units);
}
}
class CommercialPlan extends Plan
{
public void getRate()//store commercial rate as Rs.5.00 per unit
{
Rate=5.00;
}
}
class DomesticPlan extends Plan
{
public void getRate()//store domestic rate as Rs.2.60 per unit
{
Rate=2.60;
}
}
class Calculate
{
public static void main(String args[])
{
Plan p; //create reference p to abstract class
System.out.println(“Commercial connection:”);//bill for 250 units
p= new CommercialPlan(); //use reference to refer the sub class object
p.gerRate();
p.calculateBill(250);
System.out.println(“Domestic connection:”);// bill for 150 units
p=new DomesticPlan(); // use reference to refer the sub class object
p.getRate();
p.calculateBill(150);
}
}
Output:
C:\> javac Calculate.java
C:\> java Calculate
Commercial connection
Bill amount for 250 units: 1250.0
Domestic connection:
Bill amount for 150 units: 390.0

INTERFACES
INTERFACE:
An interface contains only abstract methods which are all incomplete methods.
So it not possible to create an object to an interface. In this case, we can create
separate classes where we can implement all the methods of the interface. These
classes are called implementation classes. Since, implementation classes will have
the all the methods of body, it is possible to create objects to the implementation
classes. The flexibility lies in the fact that every implementation class can its own
implementation of the abstract methods of the interface.

Abstract
methods

Interface

Implement all Implement all


the methods of the methods of
interface interface

Implementation Implementation
Class 1 class 2
Object of class 1 Object of class 2

Features of Interface:
The following are the features of interface
 An interface will have 0 or more abstract methods which are all the public
and abstract by default.
 An interface have the variables are constant because those variables are
defined under public static and final by default.
 None of the methods in an interface can be private, protected or static.
 We can’t create an object to an interface, but we can create a reference of
interface type.
 An interface can extend another interface
 It is possible to write a class within an interface.
 An interface cannot implement another interface.

 Program: Write a java program to create an interface that connects to a


database and retrieves the data from the database.

Interface MyInter
{
void connect(); // abstract public
void disconnect();
}
class OracleDB implements MyInter
{
public void connect()
{
System.out.println(“Connecting to oracle database….”);
}
public void disconnect()
{
System.out.println(“Disconnected from Oracle.”);
}
}
class SybaseDB implements MyInter
{
public void connect()
{
System.out.println(“Connecting to Sybase database…”);
}
public void disconnect()
{
System.out.println(“Disconnected from Sybase database…”;
}
}
class InterfaceDemo
{
public static void main(String args[])throws Exception
{
Class c=Class.forName(args[0]);
MyInter mi=(MyInter)c.newInstance();
mi.connect();
mi.disconnect();
}
}

Output:

C:\> javac InterfaceDemo.java

C:\> java Interface OracleDB

Connecting to Oracle database…

Disconnected from Oracle

C:\> javac InterfaceDemo SybaseDB

Connecting to Sybase database

Disconnected from Sybase database

Multiple Inheritance using Interfaces:


We know that multiple inheritance, sub classes are derived from multiple super
classes. If two super classes have same name for their members (variables and
methods) then which member is inherited into the sub class is the main confusion
in multiple inheritance. This is the reason, java does not support the concept of
multiple inheritance. This confusion is reduced by using multiple interfaces to
achieve multiple inheritance.

Program: Write a java program to achieve the multiple inheritance using multiple
interfaces

interface Father
{
float HT=6.25f;
void height();
}
interface Mother
{
float HT=5.8f;
void height();
}
class Child implements Father, Mother
{
public void height()
{
//child got average height of its parents
float ht=(Father.HT+Mother.HT)/2;
System.out.println(“Child’s height=”+ht);
}
}
class Multi
{
public static void main(String args[])
{
Child ch=new Child();
Ch.height();
}
}
Output:
C:\> javac Multi.java

C:\> java Multi

Child’s height=6.0

Callbacks using Interfaces


The mechanism of calling a function from another function is called
‘callback’. Memory address of a function is represented as ‘function pointer’ in
the languages like ‘C’ and C++. So callback is achieved by passing function pointer
of function1 () to function2 (). But, the picture is slightly different in java. Since,
we don’t have pointer concept in java, we can achieve callbacks with the help of
interfaces. Instead of passing memory address of a function, we can pass
interface reference that refers to the location of a function.
Program: Write a java program to achieve callback mechanism through interfaces
in java.
//create an interface
interface Tax
{
double stateTax();
}
class AP implements class Tax
{
public double stateTax()
{
System.out.println(“According to AP Govt rules”);
return 5000.50;
}
}
//implementation class for Karnataka state tax
class Karnataka implements Tax
{
public double stateTax()
{
System.out.println(“According to Karnataka Govt
rules”);
return 2000.00;
}
}
class TaxApp
{
public static void main(String args[]) throws Exception
{
Class c=Class.forname(args[]);
Tax ref=(Tax)c.newInstance();
calculateTax(ref);
}
static void calculateTax(Tax t)
{
double ct=1000.00;
double st=t.stateTax();
System.out.println(“Total tax=”+(ct+st));
}
}
Output:
C:\> javac TaxApp.java

C:\> java TaxApp Ap

According to AP Govt rules

Total tax=6000.5
Abstract classes vs Interfaces:
Abstract class Interface
An abstract class is written when there are An interface is written when all the features
some common features shared by all the are implemented differently in different
objects. objects.
we have to provide sub classes for this class. We have to leave the implementation to the
third party vendors.
It has abstract methods and concrete methods It contains only abstract methods.
This class contains instance variables also. An interface contains only constants.
Abstract methods implemented in sub classes. Its methods implemented in implementation
class
“abstract” keyword is used to declaration. “interface” keyword is used to declaration.

PACKAGES
PACKAGES:
A package represents a dictionary that contains related group of classes and
interfaces. For example when we write a statement like this:

Import java.io.*;
We are importing classes of ’java.io’ package. Here, java is a dictionary name and
‘io’ is another sub dictionary within it. And the ’*’ represents all the classes and
interfaces of that io sub dictionary.
The following are the advantages of package concept:
 Packages are useful to arrange related classes and interfaces into a group.
 Packages hide the classes and interfaces in a separate sub dictionary, So
that accidental deletion of classes and interfaces will not take place.
 The classes and interfaces of a package are isolated from the classes and
interfaces of another package.
 A group of packages is called a library. The classes and interfaces of a
package are like books in library and can be reused several times.

Different Types of Packages


There are different types of packages in java. They are:
 Built-in packages
 User-defined packages
Built-in packages:
These are the packages which are already available in java language. These
packages provide nearly all the necessary classes and interfaces and methods for
the programmer to perform any task in his programs. This makes the
programming easy.
 Java.lang: lang stands for language. This package got primary classes and
interfaces essential for developing a basic java program. It consists of
wrapper classes which are useful to convert primitive data type into
objects.java.lang package which contain methods to execute an application
and find the total memory and free memory available in JVM.
 Java.util: Util stands for utility. This package contains useful classes and
interfaces like Stack, LinkedList, Hashtable, Vector, Arrays, etc.
 Java.io: ‘io’ stands for input and output. This package contains streams. A
stream represents flow of data from one place to another place.
 Java.awt: ‘awt’ stands for abstract window toolkit. This package helps to
develop GUI (Graphics User Interface) where programs with colorful screen,
paintings and images etc., can be developed.
 Javax.swing: This package helps to develop GUI like java.awt. The ‘x’ in
javax represents that is an extended package which means it is package
developed from another package by adding new feature to it.
 Java.net: ‘net’ stands for network. Client server programming can be done
by using this package. Classes related to obtaining authentication for
network.
 Java.applet: Applets are the programs which come from a server into a
client and get executed on the client machine on a network. Applet class of
this package is useful to create and use applets.
 Java.text: This package has two important classes, ‘Dateformat’ to format
dates and and times, and ‘NumberFormat’ which is useful to format
numeric values.
 Java.sql: sql stands for structural query language. This package helps to
connect to database like Oracle or Sybase, retrieve the data from them abd
use it in a java program.

User-defined Packages
The users of a java language can also create their own packages. They are
called user-defined packages. User defined packages can also be imported into
other classes and used exactly in the same way as the Built-in packages.

package packagename; //to create a package

package packagename.subpackagename;//to create a subpackage

The preceding statements in fact create a dictionary with the given package
name. We should of course add our classes and interfaces to this directory. One
point we should understand that while creating the class in a package is to declare
all the members and the class as public, except the instance variables. The reason
is only that the public members are available at outside the package to other
program.
Every we refer to a class of a package, we should write the package name
before the class name as pack.packagename in the program.this is inconvenient
for the programmer. To overcome this, we can use import statement only once in
the beginning of the program, as:
import pack.Addition;
*Program: Write a java program to create a package and store Addition class and
Subtraction class in it.
//using the package pack
import pack.Addition;
import pack.Subtraction;
class Use
{
Public static void main(String argd[])
{
//create Addition class object
Addition obj=new Addition(10,15.5);
//call the sum() method
obj.sum();
//call the sub() method and pass values
Double res=Subtraction.sub(10,15.5);
System.out.println(“Result=”res);
}
}
Output:
C:\> javac Use.java
C:\> java Use
Sum= 25.5
Result= -5.5

When we want to use classes of the same package, we need not write separate
import statements as shown in before program. We can single import statement
like follws
import pack.*;
Here, * represents all the classes and interfaces of a particular package, in this
case, it is the package pack.

The JAR files


A JAR (Java Archive) file is a file that contains compresses version of .class files,
audio files, image files or directories. We can imagine a.jar file as a zipped file
(.zip) that created by using WinZip software. Even, WinZip software can be used
to extract the contents of a .jar file. The difference is that a .jar file can be used as
it is but whereas the .zip file cannot be used directly. The files should be extracted
first from a .zip file, and then used.
To create .jar file, javasoft people have provided jar command, which can
be used in the following way:
jar cf jarfilename inputfiles
Here cf represents create file. For example, assuming our package pack
is available in C:\ directory, to convert it into a jar filewith the name pack.jar,
we can give the command as:
C:\> jar cf pack.jar pack
Now set the CLASSPATH permanently to the pack.jar file by following the
procedure shown here
 First, go to start Settings Control Panel
 In Control Panel, select System and double click on it, System properties
dialog box appers
 In this, select Advanced tab and then click on Environment variables button
 Go to User variables and click on New button
 Set the CLASSPATH variable to pack.jar and also to the current directory, by
typing at:
 Variable name: CLASSPATH
 Variable value:E:\temp\pack.jar
 Then click on the OK button
 Then click on the OK button in the Environment variables window and
system Properties windows.
 Close the control Panel.
After setting the CLASSPATH permenantly as shown in the preceding steps to the
pack.jar file, it is available anywhere in that computer system. Our program
(Use.java) which uses the package may present in any directory, it can be
compiled and run without any problem.

Interfaces in a Package
It is also possible to write interfaces in a package. But whenever, we create an
interface the implementation classes should also be created. We cannot create an
object to the interface but we can create objects for the implementation classes
and use them.

Program: Write a java program where interface reference to the object of


implementation class.
// defining interface and implementation class
Import mypack.myDate;
Import mypack.DateImpl;
Class DateDisplay
{
Public static void main(String args[]);
{
//MyDate interface reference is used to refer to
DateImpl object
MyDate obj=new DateImpl();
//call showDate()
Obj.showDate();
}
}
Output:
C:\> javac DateDisplay.java
C:\> java DateDisplay
Tue Aug 07 21:14:13 IST 2007

Creating a Sub Package in a Package


We can create a sub package in a package in the format:

package pack1.pack2;
Here, we are creating a pack2 which is created inside the pack1. To use the
classes and interfaces of pack2, we can write import statement as:

import pack1.pack2;

Program: Write a program to create a sub package in the package.


//creating a sub package tech in the package dream
package dream.tech
public class Sample
{
public void show()
{
System.out.println(“Welcome to Dream.tech)
}
}
import dream.tech .Sample
class Use
{
public static void main(String args[])
{
//create an object to Sample class
Sample s=new Sample();
//call the show() method
s.show();
}
}
Output:
C:\> javac Use.java
C:\> java Use
Welcome to Dream.tech
Access specifiers in java:
An access specifier is a keyword that used to specify how to access a member of a
class or class itself. It means, we can use access specifiers with the members of a
class or with the class also. There are four access specifiers in java: private, public,
Protected and default. We do not use default keyword for specifying the default
access specifier. If no other specifier is used, then java compiler will take it as
default access specifier.
 Private: Private member of a class are not accessible anywhere at the
outside the class. They are accessible only within the class by methods of
the class.
 Public: Public members of a class are accessible everywhere outside the
class. So any other class has right to access the information when we definr
under public keyboard.
 Protected: Protected members of a class are accessible outside class but in
general, with in the same directory.
 Default: If no access specifier is written by the programmer then. The java
compiler uses a default access specifier default members are accessible
outside the class with in the same directory.
EXCEPTION HANDLING

ERRORS IN A JAVA PROGRAM


There are three types of errors in a java program:
Compile-time errors: These are syntactical errors found in the code, due to
which a program fails to compile. For example, forgetting a semicolon at the
end of a java statement, or writing a statement without proper systax will
result in compile-time error. Let us see the following program to understand
this better.
Run-time errors: These errors are represent inefficiency of the computer
system to execute a particular statement. For example, insufficient memory to
store something or inability of the microprocessor to execute some statement
come under run-time errors.
Program: Write a java program to write main () method without its parameter:
String args[]. Hence JVM cannot detect it and cannot execute the code.
//Run-time error
class Err
{
public static void main()
{
System.out.println(“Hello”);
System.out.println(“Where is error”);
}
}
Output:
C:\> javac Err.java
C:\> java Err
Exception in thread “main”
java.lang.NoSuchMethodError:main
Logical errors: These errors depict flaws in the logic of the program. The
programmer might be using wrong formula or the design of the program itself is
wrong. Logical errors or not detected either by java compiler or JVM.
Program: Write a java program to detected the logical error.
class Err
{
public static void main(String args[])
{
double sal=5000.00
sal=sal*15/100; //wrong.Use:sal+=sal*15/100;
System.out.println(“Incremented salary=”+sal);
}
}
Output:
C:\> javac Err.java
C:\> java Err
Incremented Salary=750.0

Exceptions
Basically, an exception is a runtime error. All exceptions occur only at the runtime
but some exceptions are detected at compile time and some others at run time.
The exceptions that are checked at compilation time by the java compiler are
called ‘checked exceptions’ while the exceptions that are checked by the JVM are
called ‘unchecked exceptions’.
Unchecked exceptions and errors are considered as unrecoverable and the
programmer cannot do anything when they occur. The programmer can write a
java program with unchecked exceptions and errors and can compile the
program. He cannot see their effect only when he runs the program.

public static void main(String args[]) throws


IOException

Here IOException is an example for checked exception. So, we threw it out of


main() method without handling it. This done by throws clause written after
main() method in the above statement.
All exceptions are declared as classes in java. Of course, everything is a class
in java. Even the errors are also represented by classes. All these classes are
descending from a super class called Throwable.

Exception Handling
When there is an exception, the user data may be corrupted. This should be
tackled by the programmer carefully designing the program. For this, he should
perform the following 3 steps:
Step 1: The programmer should observe the statements in his program where
there may be a possibility of exceptions. Such statements should be written inside
a try block. A try block looks like as follows:

try
{
Statements;
}
The greatness of try block is that even if some exception arises inside it, the
program will not be terminated. When JVM understands that there is an
exception, it stores the exception details in an exception stack and then jumps
into a catch block.
Step 2: The programmer should write the catch block where he should display the
exception details to the user. This helps the user to understand that there is some
error in the program. The programmer should also display a message regarding
what can be done to avoid this error. Catch block looks like as follows;
catch(Exceptionclass ref)
{
Statements;
}
Step 3: Lastly, the programmer should perform cleanup operations like closing the
files and terminating the threads. The programmer should write this code in the
finally block. Finally block looks like as follows:
finally
{
statements;
}
The specialty of finally block is that the statements inside the finally
block are executed irrespective of whether there is an exception or not.
Program: Write a program for exception handling using try, catch and finally
block.
//exception handling using try, catch, finally blocks
class Ex
{
public static void main(String args[])
{
try
{
//open the files
System.out.println(“open files”);
//do some processing
int n=args.length;
System.out.println(“n=”+n);
int a=45/n;
System.out.println(“a=”+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
//display any message to the user
System.out.println(“Please pass data while running this
program”);
}
finally
{
//close the files
System.out.println(“Close files”);
}
}
}
Output:
C:\> javac Ex.java
C:\> java EX 11 22 44
Open files
n=3
a=15
Close files

C:\> java Ex
Open files
n=0
java.lang.ArthimeticException:\by zero
Please pass data while running this program
Close files

Handling Multiple Exceptions


Most of times there is possibility of more than one exception present in the
program. In this case, the programmer should write multiple catch blocks to
handle each one of them.

*Program: Write a java program for multiple exception handling.


//Handling multiple exceptions in the same catch block
class Ex1
{
public static void main(String args[])
{
try
{
//open the files
System.out.println(“Open files”);
//do some processing
int n=args.length;
System.out.println(“a=”+a);
int b[]={10,20,30};
b[50]=100;
}
catch(ArithmeticException|
ArrayIndexOutOfBoundsException ae)
{
//display the exception details
System.out.println(ae);
}
finally
{
//close the files
System.out.println(“close files”);
}
}
}
Output:
C:\> javac Ex1.java
C:\> java Ex1
Open files
n=0
java.lang.ArthmeticException: / by zero
close files

C:\> java Ex1 11 22


Open files
n=2
a=2
java.lang.ArrayIndexOutOfBoundsException: 50
Close files

throw Clause
There is also a ‘throw’ statement available in java to throw an exception
explicitly and catch it. Let us see how can it can be used.
Program: Write a java program for throw clause for throwing the
NullPointerException.
//using throw
class Sample
{
static void demo()
{
Try
{
System.out.println(“Inside demo()”);
Throw new NullPointerException(“Exception
data”);
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}
Output:
C:\> javac ThrowDemo.java
C:\> java ThrowDemo
Inside demo()
java.lang.NullPointerException: Exception data
Types Of An Exception
The following are the types of exceptions
 Built-in exception
 User-defined exception
Built-in exceptions:
Built-in exceptions are the exceptions which are already available in Java. These
exceptions are suitable to explain certain error situations. The following are the
Built-in exception classes:
 ArithmeticException
 ArrayIndexOutOfBoundsEXception
 ClassNotFoundException
 FileNotFoundException
 IOException
 InterruptedException
 NoSuchFieldException
 NoSuchMethodException
 NullPointerException
 NumberFormatException
 RuntimeException
 StringIndexOutOfBoundException
User-defined Exception:
Sometimes the built-in exceptions in Java are not able to describe a certain
situation. In such cases, like the built-in exception, the user(programmer) can also
create his own exceptions which are called ‘user-defined exceptions’.
Program: Write a java program to throw a User Defined Exception
//user defined exception
//to throw whenever balance amount is below Rs.1000
class MyException extends Exception
{
//store account information
private static int accno[]={1001, 1002, 1003, 1004,
1005};
private static String name[]={“Phani”, ”Manasa”,
“Haritha”, “Poornima”
“Keerthi”};
private static double
bal[]={10000.00,12000.00,5600.50,999.00,1100.55};
//default constructure
MyException()
{
}
//parameterized constructor
MyException(String str)
{
super(str);
}
//write main()
public static void main(String args[])
{
try
{
//display the heading for the table
System.out.println(“ACCNO”+”\t”+”CUSTOMER”+”\
t”+”BALANCE”);
//Display the acc information
for(int i=0;i<5;i++)
{
System.out.println(accno[i]+”/t”+name[i]
+”\t”+bal[i]);
//display own exception if balance<1000
if(bal[i]<1000)
{
MyException me=new MyException(“Balance amt
is less”);
throw me;
}
} //end of for
} //end of try
catch(MyException me)
{
me.printStackTrace();
}
}//end of main
}//end of MyException class

Output:
C:\> javac MyException.java
C:\> java MyException
ACCNO COSTOMER BALANCE
1001 Phani 10000.0
1002 Manasa 12000.0
1003 Haritha 5600.5
1004 Poornima 999.0
MyException: Balance amt is less
At MyException.main(MyException.java:39)

WRAPPER CLASSES
Wrapper class is a class whose objects wraps or contain a primitive data type.
When we create an object to a wrapper class it contains a field in this field, we
can store a primitive data type. In the other words we can wrap a primitive value
in the other class object.
A wrapper class contains a field where it stores the primitive datatype.
When we create a object to a wrapper class, it carries a primitive datatype within
it and hence the object can be sent to the server. The server can retrieve the
primitive datatype from the object and use it.
There is another reason why we need a wrapper classes. In Java, collection
classes are defined in java.util package which handle only objects, not the
primitives. Hence, if we want to use collection classes on primitives, we should
convert them into objects. Here, also we need the help of wrapper classes.

For example, if we create an object to Character wrapper class it contains a single


field char and it is possible to store character like A.

char
A
Character object

Number Class:
Number is an abstract class whose subclasses are Byte, Short, Integer, Long, Float,
and Double. So the methods of number class are commonly available in all these
subclasses.

Number Class Methods:


The number class includes following methods.
 byte byteValue(): This method converts the calling object into byte value.
The calling object can be an object of Byte, Short, Integer, Long, Float, and
Double class
 short shortValue(): This method converts the calling object into
short value.
 int intValue(): This method converts the calling object into int
value.
 long longValue():This method converts the calling object into long
value.
 float floatValue():This method converts the calling object into
float value.
 double doubleValue: This method converts the calling object into
double value.
All these methods are available in Byte, Short, Integer, Long, Float, and Double
classes

Character Class:
Character class wraps a value of the primitive data type. char in an object. If we
create Character class object, it contains a char type field. In this field, we can
store a primitive char value like A. Character class has only one constructor which
accepts primitive data type.
Character(char ch)
So, we can create Character class object and store A there, as

Character obj=new Character(‘A’);

Important Methods Of Character Class:


The character class includes the following important methods:
 char charValue(): This method is useful to convert Character class object
again into primitive char value and returns that value. For example, we can
use it as.
Character obj=new Character(‘A’);
char ch=obj.charValue();
Now .ch contains ‘A’.
 Int compareTo(Character obj): This method is useful to
compare two Character objects. It is called as:
int x=obj1.compareTo(obj2);
where, obj1 and obj2 are Character class objects
o If obj1==obj2, then this methods returns 0.
o If obj1<obj2, then it returns negative value.
o If obj1>obj2, then it returns positive value.
 String toString: This method converts Character object into String
object and returns that String object.
 static Character valueOf(char ch): This method converts a
single character ch into Character object and returns that object.
 static boolean isDigit(char ch): This method returns true if
ch is Digit(0 to 9). Otherwise returns false.
 static boolean isletter(char ch): This method returns true
if ch is a letter(A to Z or a to z)
 static boolean isUpperCase(char ch): This method returns
true if ch is an uppercase letter(A to Z).
 static boolean isLowerCase(char ch): This method returns
true if ch is a lowercase letter(a to z).
 static boolean isSpaceChar(char ch): This method returns
true if ch represents a space which is coming space bar.
 static boolean isWhitespace (char ch): This method
returns true if ch represents white space. White space is a space which is
comes from pressing tab, enter or backspace buttons.
 static boolean isLetterOrDigit(char ch): This method
returns true if ch is either letter or digit.
 static char toUpperCase(char ch): This method converts ch
into uppercase and returns uppercase letter.
 Static char toLowerCase(char ch): This method converts ch
into lowercase and returns that lower case letter.

Program: Write a program that accepts the character from the keyboard and
display its type.
//Accept a character from the keyboard and display what it
is
import java.io.*;
class CharTest
{
public static void main(String args[])throws
IOException
{
//to accept a char from keyboard
char ch:
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
while(true) //execute repeatedly
{
System .out.println(“Enter character:”);
ch= (char)br.read();
//test and display the type of character
System .out.println(“you entered:”);
if(Character.isDigit(ch))
System .out.println(“a digit”);
else if(Character.isUpperCase(ch))
System .out.println(“an uppercase letter”);
else if(Character.isLowerCase(ch))
System .out.println(“a lowercase letter”);
else if(Character.isSpaceChar(ch))
System .out.println(“a space bar character”);
else if(Character.isWhitespace(ch))
{
System .out.println(“a whitespace
character”);
return;
}
else System .out.println(“Sorry, I dont know
that”);
br.skip(2);//to skip \n code from br
}
}
}
Output:
C:\> javac CharTest.java
C:\> java CharTest
Enter a character: y
You entered a lowercase letter
Enter a character:
You entered a space bar character
Enter a character: 9
You entered a digit
Enter a character: [press Enter]
You entered a whitespace character
C:\>

Byte Class:
The byte class wraps a value of the primitive type byte in an object. The
Byte class object contains a byte type field, we can store a primitive byte
number. Byte number range from -128 to +127.
Constructors
Byte class has two constructors. The first one takes byte number as its parameter
and converts it into byte class object and the next one takes String type
parameter and converts that string into Byte class object.
o Byte(byte num)
So, we can create Byte object as: Byte obj=new Byte(120);
o Byte(String str)
This constructor suggests that we can create a Byte object by converting a string
that contains a byte number, as;
o Byte obj=new Byte(“120”);
From the above, Every wrapper class contains two contructors, the first one takes
the corresponding primitive data type and other takes a string parameter. Apart
from this, some wrapper classes have a third constructor also. But Character
class has only first type of constructor.

Important methods of bytes class


Byte class includes following important methods:
 int compareTo(Byte b)
This method is useful to compare the contents of two byte class objects. It is
called as:
int x= obj1.compareTo(obj2):
where obj1 and obj2 are Byte class objects.

If obj1==obj2, then this method returns 0


If obj1<obj2, then it returns negative value.
If obj1>obj2, then it returns positive value.
boolean equals(Object obj)
this method compares the Byte object with any other object obj1. If both have
same content, then it returns true otherwise false.
 static byte parseByte(String str): This method returns the
primitive byte number contained in the String str.
 String toString(): This method converts the Byte object into
String object and returns the String object
 static byte valueOf(String str): This method converts the
string str that contains some byte number into Byte class object and
returns that object
Short class:
Short class wraps a value of primitive data type ‘short’ in its object. Short class
object contains a short type field that stores a short number.
Constructors:
Short class has two constructors. The first one takes a short number as its
parameter and converts it into Short class and the text one takes a String type
parameter and converts that string into Short class object.
 Short(short num)
This constructor is useful to construct the Short class object by supplying a short
number to it, as:
short s=14007;
Short obj=new Short(s);

 Short (String str)


This constructor is useful to construct the Short class object by passing a string str
to it as:
String str=”14007”;
Short obj=new Short(str);

Important Methods of Short Class


The Short class includes following important methods:
 int compareTo(Short obj): This method compares the numeric value of
two Short class objects and returns 0, -ve value, or +ve value.
 boolean equals(Object obj): This method compares the Short object
with any other object obj. If both have the same content then it returns
true otherwise false.
 static short parseShort(String str): This method equivalent of the
string str.
 String toString(): This method returns a string form of the Short object.
 static Short valueOf (String str): This method converts a string str that
contains some short number into Short class object and returns that object.

Integer Class:
The Integer class wraps a value of the primitive type int in an object. The Integer
class object contains an int type field. In this field, we can store a primitive int
number.
Constructors:
Integer class has two constructors. The first one takes an int number as its
parameter and converts it into Integer class object and the next one takes a String
type parameter and converts that String into Integer class object.
 Integer(int num): This means Integer object can be created, as:
Integer obj=new Integer(123000); Here, we are converting a primitive int
value into Integer object. This is called ‘boxing’.
 Integer(String str): This constructor suggests that we can create an
Integer object by converting a string that contains an int number, as:
Integer obj=new Integer(“198663”);
Important Methods of Integer Class
The integer class includes following important methods:
 int compareTo(Integer obj): This method compares the numerical value
of two Integer class objects and returns 0, -ve value, or +ve value.
 boolean equals(Object obj): This method compares the Integer object
with any other object obj. If both have the same content, then it returns
true otherwise false.
 static int parseInt(String str): This method returns int equivalent of the
string str.
 String toString(): This method returns a string form of the Integer object.
 static Integer valueOf(String str): This method converts a string str that
contains some int number into Integer class object and returns that object.
 static String toBinaryString(int i): This method converts decimal
integer number i into binary number system and returns that binary
number as a string.
 static String toHexString(int i): This method converts decimal integer
number i into hexadecimal number system and returns that hexadecimal
number as a string.
 static String toOctalString(int i): This method converts decimal integer
number i into octal number system and returns that octal number as a
string.
 int intValue(): This method converts Integer object into primitive int type
value. This is called ‘unboxing’.

*Program: Write a java program to convert int into binary, hexadecimal and octal
format
// Convert int into binary, hexadecimal, and octal format
import java.io.*;
class Convert
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in);
System.out.print(“Enter an integer:”);
String str=br.readLine();
//convert string into int
int i=Integer.parseInt(str);
System.out.println(“In decimal:”+i);
//convert int into other systems
str=Integer.toBinaryString(i);
System.out.println(“In binary:”+str);
str=Integer.toHexString(i);
System.out.println(“In hexadecimal:”+str);
str=Integer.toOctalString(i);
System.out.println(“In octal:”+str);
}
}
Output:
C:\> javac Convert.java
C:\> java Convert
Enter an integer: 456
In decimal: 456
In binary: 111001000
In hexadecimal: 1c8
In octal:710

Long class:
The long class contains a primitive ‘long’ type data. The object of Long class
contains a field where we can store a long value
Constructors:
Long class has two constructors. The first one takes long number as its parameter
and converts it into Long class object and the next one takes a String type
parameter and converts that string into Long class object.
Long(long num): This means Long object can be created as Long obj=new
Long(12300044);
Long(String str): This constructor suggests that we can create Long object by
converting a string that contains a long number, as:
String str=”12300044”;
Long obj=new Long(str);

Important methods of Long class:


The Long class includes following important methods:
 int compareTo(Long obj): This method compares the numerical value of
two long class objects and returns 0, -ve value or +ve value.
 boolean equals(Object obj): This method compares the long object with
any other object obj. If both have same content, then it returns true or
otherwise false.
 static long parseLong(String str): This method returns long equivalent
of the string str.
 String toString(): This method converts Long object into String object and
returns the String object.
 static Long valueOf(String str): This method converts a string str that
contains some long number into Long object and returns that object.
Float class:
The float class wraps a value of the primitive type float in an object. The Float
class object contains a float type field that stores a primitive float number.
Constructors:
Float(float num):This means Float object can be created as :
float f=12.987f;
Float obj=new Float(f);
Float(double num): This constructor is useful to create a Float class object with
a double type value converted into float.
Float(String str): This constructor suggests that we can create a Float object by
converting a string that contains a float number
Important Methods of Float Class
The Float class includes following important methods:
 int compareTo(Float obj): This method compares the numerical value of
two Float class objects and returns 0, -ve value, or +ve value.
 boolean equals(Object obj): This method compares the Float object
with any other object obj. If both have same content then it returns true
otherwise false.
 static float parseFloat(String str): This method returns a string form of
the Float object.
 String toString(): This method returns a string form of the Float object.
 Static Float valueOf(String str): This method converts a string str that
contains some float number into Float object and returns that object.

Double class:
The double class wraps a value of the primitive tyoe double in an object. The
Double class object contains a double type field that stores a primitive double
number.
Constructors:
Double class has two constructors. The first one takes double number as its
parameter and converts it into Double class object and next one takes a String
type parameter and converts that string into Double class object.
 Double(double num): This means Integer object can be created as :
double d=12.1223;
Double obj=new Double(d);
 Double(String str): This constructor is useful to create a Double object by
converting a string that contains a double number, as:
String str=”12.1223”;
Double obj=new Double(str);

Important Methods of Double Class:


The Double class includes following important methods:
 int compareTo(Double obj): This method compares the numerical value
of two Double class objects and returns 0,-ve value, or +ve value.
 boolean equals(Object obj): This method compares the Double object
with any other object obj. If both have same content then it returns true
otherwise false.
 static double parseDouble(String str): This method returns double
equivalent of the string str.
 String toString(): This method returns a string form of the Double object.
 static Double valueOf(String str): This method converts a string str that
contains a double number into double class object and returns that object.
Boolean Class:
The Boolean class object contains a primitive ‘boolean’ type data. The object of
Boolean class contains a field where we can store a boolean value.
Constructors:
Boolean class has two constructors. The first one takes boolean number as its
parameter and converts that string into Boolean class object.
Boolean(boolean value): This means Boolean object can be created.
Boolean obj=new Boolean(true);
Boolean(String str): This constructor suggests that we can create Boolean object
by converting a string that contains a boolean value, as:
String str=”false”;
Boolean obj=new Boolean(str);

Important Methods of Boolean Class


The Boolean class includes following important methods:
 int compareTo(Boolean obj): This method compares the numeric value
of two Boolean class objects and returns 0, -ve value, or +ve value.
 boolean equals(Object obj): This method compares the Boolean object
with any other object obj. If both have same content then it returns true,
otherwise false.
 static boolean parseBoolean(String str): This method returns boolean
equivalent of the string str
 String to String(): This method converts Boolean object into a String
object and returns the String object.
 static Boolean valueOf(String str): This method converts a string str
that contains a boolean value into Boolean object and returns that object

We can observe that most of the methods are common in all the wrapper classes.
There is another class called Math in java.lang package that contains method to
perform mathematical operations.

Math Class:
The class Math contains methods for performing basic numeric operations, such
as the elementary exponential, logarithm, square root, and trigonometric
methods . Note all the methods of Math class are ‘static’ and hence we need not
create an object to Math class to call them.
Important Methods of Math Class
 static double sin(double arg): This method returns the sine value of the
arg. arg is given radians.
 static double cos(double arg): This method returns the cosine value of
the arg. arg is given radians.
 static double sqrt(double arg): This method returns the square root
value of arg.

THREADS
A Thread represents a separate path of execution of a group of statements. In a Java
program, if we write a group of statements, then these statements are executed by JVM
one by one. This execution is called a thread, because JVM uses a thread to execute
these statements. This means that in every Java program, there is always a thread
running internally. This thread is used by JVM to execute the program statements.

Process 2
t2
t3
Process 1 Process 1
t1
Process 3

OS
Program: Write a program to find thread used by JVM to execute the statements.
//to find currently running thread in this program
class Current
{
public static void main(String args[])
{
System.out.println(“Let us find current thread”);
Thread t=Thread.currentThread();
System.out.println(“Current thread=”+t);
System.out.println(“Its name=”+t.getName());
}
}
Output:
C:\> javac Current.java
C:\> java Current
Let us find current thread
Current thread=Thread[main,5,main]
Its name=main

In the preceding program, currentThread() is a static method in Thread class. So we


called it as Thread.currentThread(). Then this method gave on object t of Thread class.
When we displayed this object t, it displayed its content as:
Thread[main,5,main]
 Here, the first main indicates the name of the thread running the current code
 We get 5 which is a number representing the priority of the thread
 The next main indicates the thread group name to which this thread belongs.
Every thread will have a priority number associated with it. These priority numbers will
range from 1 to 10. 1 is the minimum priority, and 10 is the maximum priority of a
thread. If priority number of a thread is more, it is given preference while execution by
JVM. The default priority number of a thread is 5.
A thread represents execution of statements. The way the statements are
executed is of two types:
1. Single tasking
2. Multi tasking
Single tasking
A task means doing some calculation, processing, etc. Generally, a task involves
execution of a group of statements, for example execution a program. In ‘single tasking’
environment, only one task is given to the processor at a time.
Since now-a-days a processor can execute millions of instructions per second,
even if a student has written a program of 100 lines, the processor will not take a more
than a fraction of a second to complete its execution. We can understand that the
processor is sitting idle without any work for most of the time.

Processor

jobs
Time

Single tasking

In single tasking, only one task is given to the processor at a time. This means we are
wasting a lot of processor time and microprocessor has to sit idle without any job for a
long time. This is to be drawback in single tasking.
Multitasking
To use the processor’s time in an optimum way, we can give it several jobs at a time.
This is called multi tasking.

Processor

1.4 millisecond

1 2 3 4

Memory

Generally, we have only one processor in our computer systems. One processor has to
execute several tasks means that it has to execute them in a round robin method.
Strictly speaking, this is not multi tasking, since the processor is quickly executing the
tasks one by one, so quickly that we feel all the jobs are executed by the processor at a
time. Multi tasking cannot be a real phenomenon with single processor systems. If we
want to really achieve multi tasking, we need computers with multiple processors.

The main advantage of multi tasking is to use processor time in a better way. We are
engaging most of the processor time and it is sitting idle. In this way, we can complete
several tasks at a time, and thus achieve good performance.

Multi tasking is of two types:


1. Process-based multi tasking
2. Thread based multi tasking
Process-based multi tasking: In process based multi tasking several programs are
executed at a time, by the microprocessor.
Thread based multi tasking: In thread bases multi tasking, several parts of the program
are executed at a time, by the micro processor.

Task1

Thread 1 processor
Task2
Thread 2

Program

Each thread can be imagined as an individual process that can execute a separate set of
statements. We can imagine these threads as hands of the microprocessor. We have 2
hands, so we can do things at a time. Similarly, if a processor has 2 threads, it can do 2
tasks at a time. This is called Thread-based multi tasking
Achieving multi tasking with threads has one advantage. Since, the threads are light
weight processes, they use minimum resources of the system.

Uses of Threads
Threads can be used for multiple purposes. Some of the uses of threads are:
 Threads are mainly used in server-side programs to serve the needs of multiple
clients on a network or internet. On Internet, a server machine has to cater the
needs of thousands of clients at a time, thus they can handle several clients.
 Threads are also used to create games and animation. Animation means moving
the objects from one place to another. In many games, generally we have to
perform more than one task simultaneously. There threads will be invaluable
help.
Creating a Thread and Running It
We know that in every java program, there is a main thread available already. Apart
from this main thread, we can also create our own threads in a program. The following
steps should be used:
 Create a class that extends the thread class or implements Runnable interface.
Both the thread class and Runnable interface are found in java.lang package.
class Myclass extends Thread
or, class Myclass implements Runnable
 Now in this class, write a run() method as:
public void run()
{
statements;
}
By default, this run() method is recognized and executed by the thread.
 Create an object to Myclass, so that the run() method is available for the
execution.
Myclass obj=new Myclass();
 Now, create a thread and attach the thread to the object obj.
Thread t=new Thread(obj);
Or, Thread t=new thread(obj, “threadname”);
 Run the thread. For this purpose, we should use start() method of Thread class.
t.start();
Program: Write a program to create MyThread class with run() method and then attach
a thread to this MyThread class object.
//to create a thread a thread and run it
//let the class extends thread or implements Runnable
class MyThread extends Thread
{
//write a run() method inside this class
public void run()
{
//only this code is executed by the thread
for(int i=1; i<=100000; i++)
{
System.out.println(i);
}
}
}
//another class
class Demo1
{
public static void main(String args[])
{
//create an object to the MyThread class
MyThread obj=new MyThread();
//create a thread and attach it to the object of MyClass
Thread t=new Thread(obj);
//now run the thread on the object
t.start(); //now this thread execute the code inside run()
//method of my thread object
}
}
Output:
C:\> javac Demo1.java
C:\> java Demo1
1
2
3
4
5
:
:
Terminating the Thread
A thread will terminated automatically when it comes out of the method. To terminate
the thread on our own, we have to device our own logic. For this purpose, the following
steps can be used:
Create a boolean type variable and initialize it to false.
Boolean stop=false;
Let us assume that we want to terminate the thread when the user presses <Enter> key.
So, when the user presses that button, make the boolean type variable as true
Stop=true;
Check this variable in run() method and when it is true, make the thread return from the
run() method.
public void run()
{ if (stop==true) return;
}

Program: Write a java program showing how to terminate the thread by pressing the
enter button.
//to create a thread and run it and then stop it
import java.io.*;
class MyThread extends Thread
{
boolean stop=false;
public void run()
{
for(int i=1; i<=100000; i++)
{
System.out.println(i);
If(stop) return; // come out of the run()
}
}
}
class Demo1
{
public static void main(String args[]) throws Exception
{
MyThread obj=new MyThread();
Thread t=new Thread(obj);
t.start ();
//stop the thread when enter key is pressed
System.out.read(); // wait till enter key is pressed
obj.stop=true;
}
}
Output:
C:\> javac Demo1.java
C:\> java Demo1
1
2
3
4
5
6
:
:
Single tasking using a thread:
A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be
executed. We can create a thread and pass the 3 tasks one by one to the thread. For this
purpose, we can write all these tasks separately in separate method: task1, task2, task3.
Then these methods should be called from run() method, one by one. Remember, a
thread executes only the code inside the run() method. It can never executes other
methods unless they are called from run().
Program: Write a program showing execution of multiple tasks with a single thread
//single tasking using a thread
class MyThread implements Runnable
{
public void run()
{
// executes the tasks one by one calling the methods .
task 1();
task 2();
task 3();
}
void task 1
{
System.out.println(“This is task 1”);
}
void task 2
{
System.out.println(“This is task 2”);
}
void task 3
{
System.out.println(“This is task 3”);
}
class Single
{
public static void main(String args[])
{
//create an object to my thread class
MyThread obj=new MyThread
//create a thread t1 and attach it to that object
Thread t1=new Thread(obj);
//executes the thread t1 on that object’s run() method
t1.start()
}
}
Output:
C:\> javac Single.java
C:\> java Single
This is a task 1
This is a task 2
This is a task 3
In the above program, a single thread t1 is used to execute three tasks

Multi Tasking Using Threads


In multi tasking, several tasks are used at a time. For this purpose, we need more than
one thread. For example, to perform 2 tasks, we can take 2 threads and attach them to
the 2 tasks. Then those tasks are simultaneously executed by the three threads. Using
more than one thread is called ‘multi threading’.

Thread is basically lightweight sub-process, a smallest unit of processing.


Multiprocessing and multithreading both are used to achieve multitasking. But we use
multithreading than multiprocessing because threads are shared common memory
area. They don’t allocate separate memory so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Multithreading
1. It doesn’t block the user because threads are independent and you perform
multiple operations at same time.
2. You can perform many operations together so it saves time.
3. Threads are independent so it doesn’t affect other threads if exception occur in a
single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)
Process-based Multitasking (Multiprocessing)
o Each process have its own address in memory i.e. each process allocate separate
memory area.
o Process is heavy weight
o Cost of communication between process is high.
o Switching from one process to another require some time for saving and loading
registers, memory maps and updating lists etc.
Threads-based Multitasking (Multithreading)
o Threads share the same address space.
o Thread is a lightweight.
o Cost of communication between thread is low.

Difference between Multiprocessing and Multithreading


Multiprocessing means executing several programs at a time using more than one
processor. Multithreading means executing several parts of a program simultaneously
(Round robin processor time sharing algorithm)
Sno Multi processing Multi threading
1 OS controls switching JVM controls
2 switchingDifferent processes can use Threads all use the same language
different languages. (e.g.java)
3 Each process has its own JVM. All threads share a single JVM (running in
a single process)
4 Multi-processing refers to an Multi-threading refers to an application
application organized across with multiple threads running within a
multiple OS-level processes process
5 It refers to the ability of the It refers to the ability of the operating
operating system to execute system to execute multiple parts of a
multiple programs simultaneously. process simultaleously.
This process time is shared between
the programs.
6 Multi-processing is “heavy weight” Multi-threading is a more “light weight”
form of concurrency. form of concurrency.

Multitasking using threads program


Program: Write a program showing two threads working simultaneously upon two
objects.
//two threads performing two tasks at a time – Theatre example
class MyThread implements Runnable
{
// declare a string to represent the task
String str;
MyThread(String str)
{
this.str=str;
}
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println(str+”:”+i);
try
{
Thread.sleep(2000);
//cease thread execution for 2000 milliseconds
}
catch(InterruptedException i.e)
{
Ie.printStackTrace();
}
}// end of for
}// end of run()
}
class Theatre
{
public static void main(String args[])
{
// create two objects to represent two tasks
MyThread obj1=new MyThread(“Cut the ticket”);
MyThread obj2=new MyThread(“Show the seat”);
// create two threads and attach them to the objects
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
//start the threads
t1.start();
t2.start();
}
}
Output:
C:\> javac Theatre.java
C:\> java Theatre
Cut the ticket: 1
Show the seat: 1
Cut the ticket: 2
Show the seat: 2
Cut the ticket: 3
Show the seat: 3
:
Cut the ticket: 10
Show the seat: 10

Multiple Threads Acting On Single Object


We write an object to represent one task. If there is a different task, we take another
object. When two people(threads) perform a same task, then they need same object
(run() method) to be executed each time. Take the case of railway reservation. Every
day several want to reservation for a berth for them. The producer to reserve the berth
same for all the people. So, we need same object with same run() method to be
executed repeatedly for all the people (threads).
Program: write a program showing two threads acting upon a single object.
// Thread unsafe – Two threads acting on same object
class Reserve implements Runnable
{
// available berths are 1
int available=1;
int wanted;
//accept wanted berths at run time
Reserve(int i)
{
wanted=i;
}
Public void run()
{
//display available berths
System.out.println(“Available Berths=”+available);
//if available berths are more than wanted berths
if(available>=wanted)
{
//get the name of the passenger
String name=Thread.currentThread().getName();
//allot the berth to him
System.out.println(wanted +”Berths reserved for=”+name);
try
{
Thread.sleep(1500); // wait for printing the ticket
available=available-wanted;
//update the available number of berths
}
catch(InterruptedException ie)
{}
}
// if available berths are less. Display sorry
else System.out.println(“sorry, no berths”);
}
}
class Unsafe
{
public static void main(String args[])
{
//tell that one berth is needed
Reserve obj=new Reserve(1);
// attach first thread to the object
Thread t1=new Thread(obj);
// attach second thread to the same object
Thread t2=new Thread(obj);
//takes the threads names as a persons name
t1.start();
t1.start();
}
}
Output:
C:\> javac Unsafe.java
C:\> java Unsafe
Available Berths=1
Available Berths=1
1 berths reserve for first person
1 berths reserve for second person

Synchronizing Threads
When we start two or more threads with in a program, there may be situation when
multiple threads try to access the same resource and finally they can produce
unforeseen result due to concurrency issue. For example if multiple threads try to write
with a same file then they may corrupt the data because one of the threads can
override the data or while one thread is opening the same file at the same time another
thread might be closing the same file.

So, there is a need to synchronized the action of multiple threads and make sure that
only one thread can access the object at a given point in time. This is implemented using
a concept called monitors. Each object in java is associated with a monitor, which a
thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

Synchronizing in java is the capability to control the access of multiple threads to any
shared object. Java Synchronization is better option where we want to allow only thread
to access the shared object.

t1 t2 – wait till t1 comes out

enter the obj


mutex

Thread synchronization

There are two ways two synchronize the object.


Using synchronized block: Here, we can embed a group of statements of the object
(inside run() method) within a synchronized block, as shown here:
Synchronized (object)
{
statements;
}
Here object represents the object to be locked or synchronized. The statements inside
the synchronized block are all available to only one thread at a time. They are not
available to more than one thread simultaneously.
Using Synchronized keyword: We can synchronized an entire method by using
synchronized keyword. For example, if we want to synchronize the code of display()
method, then add the synchronized keyword before the method name as shown below.
Synchronized void display()
{
statements;
}
Synchronized block is useful to synchronize a block of statements. Synchronized
keyword is useful to synchronize the entire method.

*Program: write a java program to synchronize the threads acting on the same object.
The synchronized block in the program can be executed by only one thread at a time.
//thread synchronization – two threads acting on same object
Class Reserve implements Runnable
{
// available berths are 1
int available=1;
int wanted;
// accept wanted berths at run time
Reserve(int i)
{
wanted=i;
}
public void run()
{
synchronized(this) // synchronize the current object
{
// display the available berths
System.out.println(“Available Berths=”+available);
// if available berths are more than wanted berths
if(available >= wanted)
{
// get the name of the passenger
String name=Thread.currentThread().getName();
// allot a berth to him
System.out.println(wanted + “Berths reserved for” +name);
try
{
Thread.sleep(1500); // wait for printing a ticket
available= available – wanted;
// update the no of available berths
}
catch(InterruptedException of ie){}
}
// if available berths are less, display sorry
else System.out.println(“Sorry, no berths”);
} //end of synchronized block
}
}
class Safe
{
public static void main(String args[])
{
// tell that 1 berth is needed
Reserve obj=new Reserve(1);
// attach first thread to the object
Thread t1=new Thread(obj);
// attach second thread to the same object
Thread t2=new Thread(obj);
// takes thread names as person names
t1.setName(“First person”);
t2.setName(“Second person”);
// send the requests for berth
t1.start();
t2.start();
}
}
Output:
C:\> javac Safe.java
C:\> java Safe
Available Berths= 1
1 berths reserved for first person
Available Berths= 0
Sorry, no berths

In the above program, we used a synchronized block. Alternately, we can used the
synchronized keyword before the return type of the run() method as: public
Synchronized void run()

The following are the important methods of java.lang.Thread class


To create a thread, we can use the following forms:
Thread t1=new Thread(); //thread is created without any name
Thread t2=new Thread(obj); // here obj is target object of the thread
Thread t3=new Thread(obj, “thread-name”); //target object and target name are given

 To know the currently running the thread


Thread t= Thread.currentThread();
 To start a thread:
t.start();
 To stop execution of a thread for a specified time:
Thread.sleep(millseconds);
 To get name of a thread:
String name=t.getName();
 To set a new name to a thread:
t.setName(“new name”);
 To get a priority of a thread:
int priority_no=t.getPriority();
 To set priority of a thread:
t.setPriority(int priority_no)
 To test if a thread is still alive:
t.isAlive() returns true/false
 To wait till a thread dies:
t.join();

DEAD LOCK THREADS

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a


thread is waiting for an object lock, that is acquired by another thread and second
thread is waiting for an object lock that acquired by first thread. Since, both threads are
waiting to release the lock, the condition is called deadlock.

Thread 1 Thread 2

Dead lock is a situation of complete Lock, when no thread can complete its execution
because lack of resources. For example, Thread1 is holding a resource R1, and need
another resource R2 to finish execution, but R2 is locked by Thread2, which needs R1,
Which in turn is locked by Thread1. Hence none of them can finish and are stuck in a
deadlock.

When thread deadlock occurs, any future execution is stopped and the program will
come to a halt. Thread deadlock is a drawback in the program. The programmer should
take care to avoid any such deadlocks in his programs.

Book Ticket

train
150 miiliseconds

compartment 200 milliseconds


Cancel ticket

Thread deadlock

Program: Write a program depicting a situation in which a dead can occur.


// Thread Deadlock
class BookTicket extends Threads
{
// we are assuming train, compartment as objects
Object train, comp;
BookTicket(Object train, Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
// lock on train
Synchronized(train)
{
System.out.println(“BookTicket locked on train”);
try
{
Thread.sleep(150);
}
catch(InterruptedException e) { }
System.out.println(“BookTicket now waiting to lock on compartment…”);
Synchronized(comp)
{
System.out.println(“BookTicket locked on compartment”);
}
}
}
class CancelTicket extends Thread
{
// we are assuming train, compartment as objects
Object train,comp;
CancelTicket(Object train, Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
//lock on compartment
synchronized(comp)
{
System.out.println(“CancelTicket looked on compartment”);
try
{
Thread.sleep(200);
}
catch(InterruptedException e) { }
System.out.println(“CancelTicket now waiting to lock on train…”);
synchronized(train)
{
System.out.println(“CancelTicket locked on train”);
}
}
}
}
class DeadLock
{
public static void main(String args[])
{
// take train, compartment as objects of Object class
Object train=new Object();
Object compartment=new Object();
// create objects to BookTicket, CancelTicket classes
BookTicket obj1=new BookTicket (train,compartment)
CancelTicket obj2=new CancelTicket(train,compartment)
// attach 2 threads to these objects
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
// run the threads on the object
t1.start();
t2.start();
}
}
Output:
C:\> javac DeadLock.java
C:\> java DeadLock
BookTicket locked on train
CancelTicket looked on compartment
BookTicket now waiting to lock on compartment…
CancelTicket now waiting to lock on train…

Avoiding deadlocks in a program


There is no specific solution for the problem of deadlocks. It depends on the logic used
by programmer. The programmer should design his program in such a way, that it does
not form any deadlock.
To avoiding deadlocks in a program we have to chage previous program like below:
public void run()
{
//first lock on train like the BookTicket does
Synchronized(train)
{
System.out.println(“CancelTicket locked on train”);
try{
Thread.sleep(200);
}catch(InterruptedException e) { }
System.out.println(“CancelTicket now waiting to lock on compartment…..”);
synchronized(comp)
{
System.out.println(“CancelTicket locked on compartment…”);
synchronized(comp)
{
System.out.println(“CancelTicket locked on compartment”);
}
}
}
}
Now run the program again see the output:
BookTicket locked on train
BookTicket now waiting to lock on compartment
BookTicket locked on compartment
CancelTicket locked on train
CancelTicket now waiting to lock on train
CancelTicket locked on compartment

Life cycle of the Thread (Thread States)

A thread can be in one of the five states. According to sun, there only 4 states in thread
life cycle in java new, runnable, non-runnable and teriminated. There is no running
state.
But for better understating the threads, we are explaning it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable
5. Terminated
1) New: The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable: This is in the state when the thread is still alive, but is currently
not eligible to run.
5) Terminated: A thread is in terminated or dead state when its run() method exists.

New

start() sleep done, I/O


complete, lock available
resume, notify
Runnable

Non-Runnable
(Blocked)

Running

run() ,method sleep, block on I/O, wait


exists for lock, suspend,wait

Terminated

Thread Communication

In some cases, two or more threads should communicate with each other. For example,
a Consumer thread is waiting for a producer to produce the data (or some goods). When
the Producer thread completes production of data, then the Consumer thread should
take that data and use it. This mechanism is also called as inter thread communication
and cooperation.
Cooperation (inter thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed. It is implemented by following methods of Object class:
 obj.wait()
 obj.notify()
 obj.notify-All()

obj.wait(): This method makes a thread wait for the object(obj) till it receives a
notification from a notify() or notifyAll() methods.
Method Description
public final void wait()throws InterruptedException Waits until object is notified
public final void wait (long timeout) throws Waits for the specified amount of
InterruptedException time

obj.notify(): This method releases an object (obj) and sends a notification to a waiting
thread that the object is available.
Syntax: public final void notify()
obj.notifyAll(): This method is useful to send notifications to all waiting threads at once
that the object (obj) is available.
Syntax: public final void notifyAll()
It is recommended to use above methods inside a synchronized block.

Difference between wait() and sleep() methods


Both sleep() and wait() methods are used to suspend a thread execution for a specified
time. When sleep is executed inside a synchronized block, the object still under lock.
When wait() method is executed, it breaks the synchronized block, so that the object is
removed and it is available.
Generally, sleep() is used for making a thread to waiting for some time. But wait() is
used in connection with notify() or notifyAll() methods in thread communication.

Thread priorities
When the threads are created and started, a thread scheduler program in JVM will load
them into memory and execute them. This scheduler will allot more JVM time to those
threads which are having higher priorities. The priority numbers of a thread will change
from 1 to 10. The minimum priority (shown by Thread.MIN_PRIORITY) of a thread is 1,
and the maximum priority(Thread.MAX_PRIORITY) is 10. The normal priority of a thread
(Thread.NORM_PRIORITY) is 5.

When two tasks are assigned to two threads with different priorities, example 2 and 5,
then the thread with priority number 5 will be given more JVM time and hence it will
complete the task earlier than the thread with priority number 2.
*Program: Write a program to understand the thread priorities. The thread with higher
priority number will complete its execution first.
//thread priorities
class Myclass extends Thread
{
int count=0; // this counts numbers
public void run()
{
for(int i=1; i<=10000; i++)
count ++; // count numbers upto 10000
// display which thread has complete its counting and its priority
System.out.println(“Complete thread:”+Thread.currentThread().getName());
System.out.println(“Its priority:”+Thread.currentThread().getPriority());
}
}
class Prior
{
public static void main(String args[])
{
Myclass obj=new Myclass();
//create two threads
Thread t1=new Thread(obj. “One”);
Thread t2=new Thread(obj. “Two”);
// set priorities for them
t1.setPriority(2)
t2.setPriority(Thread.NORM_PRIORITY); // this means norm priority no 5
// start first t1 and then t2.
t1.start();
t2.start();
}
}
Output:
C:\> javac Prior.java
C:\> java Prior
Completed thread: Two
Its priority : 5
Completed thread: one
Its priority : 2
THREAD GROUP
A thread group represents several threads as a single group. The main advantage of
taking several threads as a group is that by using a single method, we will be able to
control all the threads in the group.
 To create a thread group, we should simply create an object to ThreadGroup
class as
ThreadGroup tg=new ThreadGroup(“groupname”);
Here, tg is the thread group object, and groupname is it’s name.

 To add thread to this group(tg):


Thread t1=new Thread(tg.targetobj.”targetobj”);
Here t1 thread is created and added to the thread group tg. This thread acts on the
targetobj, which is the target for the thread. The threadname represents the name of
the thread t1.
 To add another thread group tg1 to the tg.
ThreadGroup tg1=new ThreadGroup (tg. “groupname”);
Here, we are creating and adding the thread group tg1 to the thread group tg. The name
of the added thread group is represented by groupname.
 To know the parent of a thread or thread group, we can use getParent().
tg.getParent();
This method returns the ThreadGroup object which is the parent of tg.
 To know the parent thread group of a thread, we can use:
t.getThreadGroup();
This returns a ThreadGroup object which the thread t belongs.
 To know the number of threads actively running in a thread group.
tg.activeCount();
This methods returns an integer number that gives the number of threads in tg which
are currently running in the memory.
 To change the maximum priority of a thread group tg.
tg.setMaxPriority();
Normally, the maximum priority of a thread group will be 10. But this method can set it
as any other number between 1 and 10.
*Program: Write a java program for creating ThreadGroups.
// using thread groups
class TGroups
{
public static void main(String args[]) throws Exception
{
// we should understand that the following statements are executed by main thread
Reservation res= new Reservation();
Cancellation can=new Cancellation();
// create thread group with name
ThreadGroup tg=new ThreadGroup(“First Group”);
//create two threads and them to the first group
Thread t1=new Thread(tg, res, “First thread”);
Thread t2=new Thread(tg, res, “Second thread”);
// create another thread group tg1 as a child to tg
ThreadGroup tg1=new ThreadGroup(tg, “Second Group”);
//create 2 threads and add them to the second group
Thread t3=new Thread(tg1, can, “Third thread”);
Thread t4=new Thread(tg1, can, “Fourth thread”);
//find the parent group of tg1
System.out.println(“Parent group of tg1”+tg1.getParent());
// set maximum priority to tg1 as 7
tg1.setMaxPriority(7);
// know the thread group of t1 and t3
System.out.println(“Thread group of t1=”+t1.getThreadGroup());
System.out.println(“Thread group of t3=”+t3.getThreadGroup());
//start the threads
t1.start();
t2.start();
t3.start();
t4.start();
//find how many threads are actively running
System.out.println(“No of threads are active in tg=”+tg.activeCount());
}
}
Class Reservation extends Thread
{
public void run()
{
System.out.println(“I am Reservation thread”);
}
}
Class Cancellation extends Thread
{
public void run()
{
System.out.println(“I am Cancellation thread”);
}
}
Output:
C:\> javac TGroups.java
C:\> java TGroups
Parent of tg1=java.lang.ThreadGroup[name=First Group, maxpri=10]
Thread group of t1= java.lang.ThreadGroup[name=First Group, maxpri=10]
Thread group of t3= java.lang.ThreadGroup[name=Second Group, maxpri=7]
No of threads active in tg=4
I am Reservation thread
I am Reservation thread
I am Cancellation thread
I am Cancellation thread

Daemon Threads
Sometimes, a thread has to continuously execute without any interruption to provide
services to other threads. Such threads are called daemon threads. For example, oracle
exe is a program (a thread) that continuously executes in a computer. When a system is
switched on, it also starts running and terminate only when the system is off. Any other
threads like SQL+ can communicate with it to store or retrieve data.
 To make thread t as a daemon thread, we can setDaemon() method as:
t.setDaemon(true);
 To know if a thread is daemon thread or not, isDaemon() is useful.
Boolean x=t.isDaemon();
If isDaemon() returns true, then the thread t is a daemon thread, otherwise not
Points to remember for Daemon Thread in java
 It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description
1 public void setDaemon(boolean status) Is used to mark the current thread as
daemon thread or user thread
2 public boolean isDaemon() Is used to check that current is daemon

Applications of threads
In a network, a server has to render its service to several clients at a time. So, by using
threads at service side programs, we can make the threads serve several clients at a
time. In the following program, we are creating a server using 2 threads that can send
messages two clients at a time. First thread will contact first client, at the same time
second thread will contact second client. If third client comes, then again first thread
will provide service to it. Like this, 2 threads will contact the clients one by one, thus
they can serve several clients. Here, we are combining the java.net features with
threads.

Animates the things using threads

Another application of threads is animation, where an object, an image or some text is


moved from one place to another on the screen. Here is an example program to see a
moving banner using a thread. A logic is to exact the first character from a banner string
and add it at the end of the string. When the screen contents are refreshed, it appears
as if the entire string will move towards left. Now extract the left most character and
place it at the end of the banner string. Like this, repeat the same to get effect of a
moving banner.
Program: write a java program to animate the things using threads.
// moving banner using thread
import java.awt.*; // for GUI
class Banner extends Frame implements Runnable
{
//this is the banner string
String str=”DREAM TECH PUBLICATIONS”;
Banner()
{
setLayout(null); // don’t set layer manager
setBackground(Color.cyan);
setForeground(Color.red);
} // end of the constructor
public void paint(Graphics g)
{
// set front and display the banner string
Font f=new Font(“Courier, Font.BOLD, 40);
g.setFont(f)
g.drawString(str, 10,100);
}
public void run()
{
for(;;) { // move banner continuously
repaint(); // refresh the frame contents
try{
Thread.sleep(400): // give a gap of 400 milli between each movement
}catch(InterruptException ie){}
char ch=str.charAt(0); // extract first char from string
str=str.substring(1, str.length()); // add to str from second char till end
str=str+ch; // attach a first char at the end of str
}
}
public static void main(String args[])
{
Banner b=new Banner(); // b represents the frame
b.setSize(400,400);
b.setTiltle(“My banner”);
b.setVisible(true);
//create a thread and run it
Thread t=new Thread(b);
t.start();
}
}
Output:
C:\> javac Banner.java
C:\> java Banner

My banner

S DREAM TECH
PUBLICATIONS
Thread pools
A thread pool can be imagined as a group of threads which are ready to perform the
given tasks. Thus a thread pool may contain one more threads. These threads are some
times called as worked threads.

Difference between thread group and thread pool


Thread group Thread pool
A thread group is a class that contains one A thread pool is a concept that represent a
or more threads or other thread groups group of already created threads.
Every thread in the group can handle the The threads in the thread pool perform the
different task without coordinating with task with good coordination
other threads
The programmer should create a thread The fixed number of threads in the pool
per task will take care of the all the task.
Each thread will utilize system resources All the threads in thread pool are only
separately. Hence, there are a chances for limited resources which do not create high
high load of CPU and memory crashes. load on CPU or memory crashes.

In case of a thread pool the programmer creates a group of threads which executes the
task at a time. Let us take a thread pool with two threads. If there are 4 tasks, the 2
threads will execute the first two tasks. When first two tasks are completed,the two
threads will execute the remaining two tasks. Thus, they complete the given 4 tasks. In
this way, the threads in the thread pool are reused again and again

Advantages of thread pools


 Thread pools are useful to reduce overhead involved in creation of a creation of a
new thread every time a task is to be handled. Thus, they improve the response
time of the server
 Every thread pool will restricted the number of threads. Hence, the maximum
limit of number of threads allowed for the JVM will not be crossed.
 Thread pool eliminate problems related to over usage of memory
 Once the thread pool is created, the programmer need not manage the threads
in the thread pool. He will be freed to concentrate on the business logic.
Types of thread pools
The java.util.concurrent package provides an interface by the name of executor and a
sub interface ExecutorService. The methods of these interfaces are implemented in the
class executors. Using different methods, it is possible to create different types of thread
pools. There are five types of thread pools that we can create as described as below.
 Single thread executor: This is a thread pool that contains only one thread. When
several tasks are given, the thread will execute them one by one sequentially. The
method to create single thread executor is Executor.newSingleThreadExecutor().
 Cached thread pool: This is a thread pool with several threads. When tasks are
coming continuously, the threads will execute them simultaneously. The threads
which complete the task are kept in memory and reused for the new tasks. The
method to create this type of pool is Executors.newCachedThreadPool()
 Fixed thread pool: This is a thread pool with fixed number of threads. Each
thread will execute one task at a time. When task is completed, it will execute the
next waiting task.
 Scheduled thread pool: In this pool, there will be a group of threads. They are
aimed at executing the tasks in future, after a given time delay. We can use the
method Executors.newSheduledThreadPool() to create this type of thread pool.
 Single thread scheduled thread pool: This is a scheduled thread pool with only
one thread. It means there is only one thread to execute the task in future. The
method to use is Executors.newSheduledSingleThreadExecutor().

ABSTRACT WINDOW TOOLKIT

Abstract Window Toolkit (AWT) represents a class library to develop applications using GUI. The

java.awt package got classes and interfaces to develop GUI and let the users interact in a more friendly

way with the applications, some important classes of java.awt package.

Check box group


Object

Component Label

Button

Check box

Choice

List

Canvas
TextField
Scrollbar
TextArea
Text component

Container
Panel Applet

Window Frame

Components:

A component represents an object which is displayed pictorially on the screen. For example, we create

an object of Button class as:

Button b = new Button ( );

Now, b is the object of Button class. If we display this b on the screen, it displays a push button.

Therefore, the object b, on going to the screen is becoming a component called ‘Push button’. In the

same way, any component is a graphical representation of an object.

Window and Frame :

A window represents any imaginary rectangular area on the screen without any borders or title bar, A

frame represents a window with some title and borders.

Creating a Frame :

A frame becomes the basic component in AWT. The frame has to be created before any other

component. The reason is that all other components can be displayed in a frame. There are three ways

to create a frame, which are as follows.

 Create a Frame class object,

Frame f = new Frame ( );


 Create a Frame class object and pass its title also,

Frame f = new Frame (“My frame”);

 The third way is to create a subclass My Frames to the Frame class and

create an object to the subclass as:

Class My Frame extends Frame

My Frame f = new My Frame ( );

Since, My Frame is a subclass of Frame class, its object f contains a copy of Frame class and hence f

represents the frame.

Since, the size of our frame would be .’O’ px width and ‘O’ px height, it is not visible and hence we

should increase its size. so that it would be visible to us. This is done by set size ( ) method, as:

F, set size (400,350);

Here, the frame’s width is set to 400 px and height to 350 px. Then, we can display the frame, using set

visible ( ) method, as:

F, set visible (true);

Program 1: write a program to create a frame by creating an object to Frame class.

//Creating a frame – version 1

Import Java. awt.*;

Class MyFrame

Public static void main (string args [ ])

//Create a frame

Frame f = new Frame (“My AWT frame”);


//set the size of the frame

f. sets size (300,250);

//display the Frame

f. set visible (true);

Event Delegation Model :

When we create a component, generally the component is displayed on the screen but is not capable of

performing any actions. For example, we created a push button, which can be displayed but cannot

perform any action, even when someone clicks on it. This is called event. An event represents a specific

action done on a component. Clicking, double clicking, typing data inside the component, mouse over,

etc. are all examples of events. A listener is an interface which listens to an event coming from a

component. A listener will have some abstract methods which need to be implemented by the

programmer.

When an event is generated by the user on the component, the event is not handled by the component.

On the other hand, the component sends (delegates) that event to the listener attached to it. The

listener will not handle the event. It hands over (delegates) the event to an appropriate method. Finally,

the method is executed and the event is handled. This is called event delegation model’.

Method 1()

Component listener
Method 2()
This method

Method 3() handles event


event

component action part

 We should attach an appropriate listener to a component. This is done

using addxxxlistener ( ) method. Similarly, to remove a listener from a

component, we can use removexxxListener ( ) method.

 Implement the methods of the listener, especially the method which

handles the event.

 When an event is generated on the component, then the method in

step 2 will be executed and the event is handled.

 The advantage of event delegation model is the component and the

action parts can be developed in two separate environments. For

example, we can create the component in Java and the action logic can

be developed in Visual Basic.

 We can modify the code for creating the component without modifying

the code for action part of the component. Similarly, we can modify the

action part without modifying the code for the component. Thus, we

can modify one part without effecting any modification to other part.

This makes debugging and maintenance of code very easy.

Closing the Frame

Frame is also a component. We want to close the frame by clicking on its close button.
 We should attach a listener to the frame component. Remember, all

listeners are available in jave. awt. Event package. The most suitable

listener to the frame is window listener. It can be attached using

add window listener ( ) method as:

f. add window Listener (window Listener obj);

 Implement all the methods of the window Listener interface. The

following methods are found in window Listener interface:

public void windowActivated (windowEvent e)

public void window Closed (Window Event e)

public void window Closing (Window Event e)

public void window Deactivated (Window Event e)

public void window Deiconified (Window Event e)

public void window Iconified (Window Event e)

public void window Openec (Window Event e)

public void window Closing (Window Event e)

//close the application

System, exit (0);

Program 3: Write a program which first creates a frame and then closes it on clicking the close button.

// creating a frame and closing it.

Import java.awt.*;

Import java.awt.event.*;

Class MyFrame extends Frame


{

Public static void main(string args[ ])

// Create a frame with title

My Frame f = new My Frame ( );

// set title for the frame

f. set Title (“My AWT frame”);

// set the size of the frame

f. set Size (300,250);

// display the frame

f. set visible (true);

//close the frame

f.add window Listener (new My class( ) );

Class My class implements window Listeners

Public void window Activated (window Event e) { }

Public void window Closed (window Event e) { }

Public void window Closing (window Event e)

System. Exit (0);

Public void window Deactivated (window Event e) { }

Public void window Deiconified (window Event e) { }

Public void window Iconified (window Event e) { }


Public void window Opened (window Event e) { }

Drawing in the Frame :

Graphics class of java.awt package has the following methods which help to draw various shapes.

 Draw Line (int x1,int y1,int x 2,int y2)

This method is useful to draw a line connecting (x1,y1) and (x2,y2).

 Draw Rect (int x, int y, int w, int h)

This method draws outline of a rectangle. The left top corner of the rectangle starts at (x,y),the width is

w, and the height is h.

 drawRoundRect (int x,int y, int w,int h,int arcw, int arch): This method

draws the outline of a rectangle with rounded corners. The rectange’s

top left corner starts at (x,y), the width is w, and height is h. The

rectangle will have rounded corners. The rounding is specified by arcw

and arch. Arcw represents horizontal diameter of the arc at the corner

and arch represents vertical diameter of the arc at the corner.

 Draw Oval (int x, int y, int w,int h): This method draws a circle or

ellipse bounded in the region of a rectangle starting at (x,y),with width

w and height h.

To draw any of these shapes, we need paint ( ) method of component class, which refreshes the frame

contents automatically when a drawing is displayed. This method is useful whenever we want to display

some new drawing or text of images in the frame. The paint ( ) method is automatically called when a

frame is created and displayed.

Program 6: Write a program to draw a smiling face using the methods of Graphics class.

//Drawing a smiling face in a frame


Import java.awt.*;

Import java.awt.event.*;

Class Drawl extends Frame

Draw1 ( )

//close the frame

This.addwindow Listener(new window Adapter ( )

Public void window closing (window Event e)

Filling with Colors

To fill any shape with a desired color, first of all we should set a color using set color ( ) method. Then

any of the following methods will draw those respective shapes by filling with the color.

 fillRect (int x, int y, int w, int h): This method draws a rectangle and fills

it with the specified color.

 fill RoundRect (int x, int y,int w, int h, int arcw, int arch): This method

draws filled rectangle with rounded corners.

 filloval (int x, int Y, int w, int h): This method is useful to create an oval

(circle or ellipse ) which is filled with a specified color.

 fillArc(int x, int w, int h,int h int sangle, int aangle): This method draws

an arc and fills it with a spectified color.

 fillpolygon (int x [ ], int y [ ], int n ) : This method draws and fills a

polygon with a specified color.

Program 7: Write a program that allows you to fill the shapes with some colors.

// Drawing a smiling face in a frame with filled colors


Import java.awt.

Import java.awt.

Class Draw2 extends Frame

Draw 2 ( )

// close the frame

This.add windowListener (new windowAdapter ( )

Public void window Closing (Window Evnet e)

System.exit (0);

});

Public void paint (Graphics g)

//set blue color

g. set color (color, blue);

//display a rectangle to contain drawing

g. fill Rect (40,40,200,200);

// face

g. fill oval (90,70,80,80);

//set black color

g. set Color (color, black);


//eyes

g. fill oval (110,95,5,5);

g. fill oval (145,95,5,5);

//nose

g. draw Line (130,95,130,115);

//set red color

g. set color (Color, red);

Program 9: write a program to draw a home with moon in the background.

//My Home

Import java.awt.*;

Import java.awt.event.*;

Class Home extends Frame

Home ( )

This.addwindowListener (new window Adapter ( )

Public void window Closing (Window Event e)

System.exit (0);

});

Public void paint (Graphics g)

{
// store x, y coordinates in x [ ] and [ ]

Int x [ ] = {375,275,475};

Int y [ ] = {125,200,200};

Int n = 3; //no. of pairs

//set gray background for frame

This. Set Background (Color.gray);

// set yellow color for rectangle – house

g. set color (Color, yellow);

g. fill Rect (300,200,150,100);

// set blue color for another rectangle – door

g. set color (color.blue);

g. fill Rect (350,210,50,60);

//set dark a line – line below the door

g. drawLine (350,280,400,280);

// set dark gray for polygon – roof

g. set color (color .darkGray);

g. fill Polygon (x,y,n);

//set cyan color for oval – moon

g. set Color (color, cyan );

g. fill oval (100,100,60,60);

// set green for arcs – grass

g. set color (color.green);

g. fill Arc (50,250,150,100,0,180);

g. fill Arc (150,250,150,100,0,180);


g. fill Arc (150,250,150,100,0,180);

// draw a line – the bottom most line of drawing

g. draw Line (50,300,600,300);

// display some text

g. draw String (“My Happy Home “,275,350);

Public static void main (String args [ ])

// create the frame

Home h = new Home ( );

// set the size and title

h. set Size (500,400);

h. set Title (“My Home”);

//display the frame

h. set visible (true);

Displaying text in the frame

To display some text or strings in the frame, we can take the help of drawstring ( ) method of Graphics

class,as;

g. draw string (“Hellor”, x,y);


Here, the string “Hello” will be displayed starting from the coordinates (x,y).

If we want to set some color for the text, we can use set color ( ) method of Graphics class as:

g. set color (color.red);

there are two ways to set a color in AET. The first way is by directly mentioning the needed color name

from color class, as color.red, color. Yellow, color. cyan, etc.

The second way to mention any color is by combining the three primary colors: red, green and blue

while creating color class object as:

Color c = new color (r,g,b);

Here, r,g,b values can change from 0 to 255, 0 represents no color. 10 represents low intensity whereas

200 represents high intensity of color.

Color c = new color (255, 0, 0); //red color

Color c = new color (255,255,255); // white color

Color c = new color (0, 0, 0); // black color

Program 11: Write a program to display some text in the frame using drawstring ( ) method.

// Frame with background color and message

Import java. awt.

Import java.awt.event.

Class Message extends Frame

Message ( )

// close the frame when close button clicked

Add window Listener (new window Adapter ( ) {

Public void window closing (window Event we)

{
System .exit (0);

});

}// end of comstructor

Public void paint (Graphics g)

//set background color for frame

This. Set Background (new color (100,20,20);

//Set font for the text

Font f = new Font(“Arial”, Font. Bold+Font. ITALIC,30);

g. set color (color. Green);

//display the message

g. drawstring (“Hello, How are U? “, 100,100);

Public static void main(string args [ ] )

Message m = new Message ( );

m. set size (400,300);

m. set Title (“This is my text”);

m. set visible (true);

Displaying Images in the Frame

We can display images like.gif and.jpg files in the frame. For this purpose, we should follow these
steps:

 Load the image into image class object using get image ( ) method of
Toolkit class.
Image img = Toolkit. Get Default Toolkit ( ).get image (“diamonds. gif”);

Here, Toolkit. Get Default Toolkit ( ) method created a default Toolkit class object. Using this object, we
call get Image ( ) method and this method loads the image diamonds. Gif into img object.

Class Images extends Frame

//take a static type Image class object

Static Image img;

Images ( )

//load an image into Image object

Img=Too1kit.getDefaultToolkit().get Image(“diamonds.gif”);

//wait till the image is loaded into img object

//for this purpose, create MediaTracker (this);

//add image to MediaTracker

Track.addImage (img,0);

Try{

//let the JVM wait till the image is loaded completely track.wait ForID
(0);

}catch (Interrupted Exception ie){ }

//close the frame

Addwindow Listener (new window Adapter( )

Public void window closing (Window Event we)

System.exit (0);

});
}

Public void paint (Graphics g)

//display the image in the frame at 50,50 pixels

g.drawImage (img,50,50,nu11);

Public static void main (string args [ ])

//create the frame

Images I = new Images ( );

//set the size and title

i.set Size (500,400);

i.set Title (“My images”);

//display the same image in the title bar of frame

i.set Iconimage(img);

//display the frame

i.set visible (true);

Component Class Methods


A component is a graphical representation of an object on the screen. For example, push buttons, radio
buttons, menus, etc. are components. Even frame is also a component. There is component class
available in jave.awt package which contains the following methods.

 Font get Font ( ): This method returns the font of the component.
 Void set Font (Font f): This method sets a particular font f for the text
of the component.
 Color get Foreground ( ): This method gives the foregrouns color of the
component.
 Void set Foreground (color c): This method sets a foreground color c to
the component.
 Color get Background ( ): Gets the background color of the component.
 Void set Background (Color c): sets the background color c for the
component.
 String get Name ( ): Returns the name of the component.
 Void set Name (string name): Sets a new name for the component.
 int get Height ( ): Returns the height of the component in pixels as an
integer.
 int get Width ( ): Returns the width of the component in pixels as an
integer.
 Dimension get size ( ): Returns the size of the component as an object
of Dimension class. Dimension width and Dimension. Height will
provide the width and height of the component.
 int get x ( ): Returns the current x coordinate of the component’s
origin.
 int get x ( ): Returns the current y coordinate of the component’s
origin.
 Point get Location ( ): Gets the location of the component in the form
of a point specifying the component’s top- left corner.
 Void set Locaion (int x, int y): Moves the component to a new location
specified by *x,y).
 Void Set size (int width, int height): Resizes the component so that it
has new width and height as passed to set size ( ) method.
 Void set Visible (Boolean b): shows or hides the component depending
on the value of parameter b. set visible (true) will display the
component and set visible (false) hides the component.

Push Buttons

Button class is useful to create Push buttons. A Push buttons is useful to perform a particular action.

 To create a push button with a label, we can create an object to button


class as:
Button b = new Button ( ); //a button without any label is created.

Button b =new Button (“label”); //a button without any label is created.

 To get the label of the button, use get Label ( ):


String 1 = b. get Lable ( );

 To set the label of the button:


b. set Label (“label”);

Here, the “label” is set to the button b.

Listeners and Listener Methods :

For working with push buttons, Action Listener is more suitable. Similarly, for other component, other
listeners are also available. All listeners are available in java.awt.event package.
Component Listener Listener methods
Button Action Listener Public void action Performed(ActionEvent e)
Check Box Item Listener Public void item Statechanged(ItemEvent e)
Check Box Item Listener Public void item StateChanged(ItemEvent e)
Group
Text Field Action Listener Public void actionPerformed(Action Event e)
Focus Listener Public void focus Gained(Focus Event e)
Public void focus Lost (Focus Event e)
Text Area Action Listener Public void action Performed(ActionEvent e)
Focus Listener Public void focus Gained(Focus Event e)
Public void focus Lost (Focus Event e)
Choice Action Listener Public void action Performed(ActionEvent e)
Item Listener Public void item Statechanged(ItemEvent e)

Checks Boxes

A check box is a square shaped box which displays an option to the user. The user can select one or
more options from a group of check boxes.

 To create a check box, we can create an object to checkbox class as:


Checkbox cb = new Checkbox ( ); // create a check box without any label Checkbox cb = new
Checkbox (“label”); // with a label

Checkbox cb=new Checkbox(“label”, state); //if state is true, then the check

// box appears as if it is selected by default, else not selected.

 To get the state of a check box:

Boolean b = cb, get state ( );

 To set the state of a check box:

String s = cb. get Label ( );

Text Area

A text Area is similar to a text field, but it can accommodate several lines of text. For example, if the user

wants to type his address which contains several lines, he can use a text area.
 To create a Text Area:

Text Area ta = new Text Area ( ); // an empty text area

Text Area ta = new Text Area (rows, cols); // text area with some rows and // columns

Text Area ta = new Text Area (“string”); //text area with predefined string

 To retrieve the text from a Text Area:

String s = ta. Get Text ( );

 To set the text from a Text Area:

Ta. Set Text (“text”);

 To append the given text to the text area’s current text:

Ta. Append (“text”);

 To insert the specified text at the specified position in this text area:

Ta. Insert (“text”, position);

List Class

This class is useful to create a list box which is similar to choice menu. A list box presents the user with a

scrolling list of text items. The user can select one or more items from the list box.

 To add items to the list box, we can use add ( ) method, as:

1st .add (“item”);

 To get all the selected item from the list box:

String x [ ] = 1st.get Selected Items ( );

 To get a single selected item from the list box:

String x [ ] = 1st.get selected item ( ) ;

 To get the selected item’s position numbers:


Int x [ ] =1st.get Selected Indexes ( );

 To get a single selected item position number:

Int x = 1st.get Selected Index ( );

Program 20: Write a program to create a list box with of some languages from where the user can select

one or more items.

//List box demo

Import java.awt.*;

Import java.awt.event.*;

Class My list extends Frame implements Item Listener

//vars

int [ ] msg;

List 1st;

My list ( )

//set flow layout manager

Set Layout (new Flow Layout ( ));

//create an empty list box that displays 4 items initially

//and multiple selection is also enabled

1st = new List (4, true);

//add items to the list box

1st. add (“English”);

1st. add (“Hindi”);

1st. add (“Telugu”);

1st. add (“Sankrit”);


1st. add (“French”);

// add the list box to frame

Add(1st);

//add the listener to the list box

1st. add Item Listener (this);

//frame closing

Add window Listener (new window Adapter ( )

Public void window closing (window Event we)

System. Exit (0);

});

} //end of constructor

Public void item state changed (Item Event ie)

//call the paint ( ) method

Repaint ( );

Public void paint (Graphics g)

g. draw string (“selected languages : “,100,200);

//get the selected items position numbers intomsg[]

Msg = 1st, get selected Indexes( );


//know each selected item’s name and display

For (int I = 0; i<msg. length; i++)

String item = 1st.get Item(msg [i]);

g. drawstring (item, 100,220+1*20);

Public static void main (string args [ ] )

//create the frame

Mylist ml = new Mylist ( );

ml.set Title (“my list box”);

ml.set size (400,400);

ml.set visible (true);

Scrollbar Class

Scrollbar class is useful to create scrollbars that can be attached to a frame or text area. Scrollbar are

used to select continuous values between a specified minimum and maximum. Scrollbar can be

arranged vertically or horizontally.

 To create a scrollbar we can create an object to scrollbar class as:

Scrollbar sb = new Scrollbar (alignment, start, step,min,max);


Alignment: Scrollbar, VERTICAL, Scrollbar, HORIZONTAL

Start: starting value (Ex:0)

Step: step value (Ex: 30) // represents scrollbar length

Min: minimum value (Ex:0)

Max: maximum value (Ex:300)

 To know the location of a scrollbar, we can use get value ( ) method

that gives the position of the scrollbar in pixels as:

Int n = sb. Get valve ( );

 To update the scrollbar position to a new position, we can use set

value ( ) method, as:

sb. Set Value (int position);

 To get the maximum value of the scrollbar:

int x = sb. get Maximum ( );

 To get the minimum value of the scrollbar:

int x = sb. Get minimum ( );

 To get the alignment of the scrollbar:

int x = getorientation ( );

Program 21: write a program to create a vertical scrollbar with scroll button length 30px and with the

starting and ending positions ranging from 0 to 400 px.

// creating a vertical scrollbar

Import java.awt.*;

Import java.awt.event.*;
Class Myscroll extends Frame implements Adjustment Listener

//vars

String msg = ‘’ ‘’;

Scrollbar s1;

My scroll ( )

//do not set any layout

setlayout (nu11);

//create a vertical scrollbar

S1=new Scrollbar (scrollbar.VERTICAL, 0,30,0,400);

//add it to frame

Add (s1);

//add adjustment listener to scrollbar

S1. addAdjustment listener (this);

// frame closing

Add window Listener (new window Adapter ( )

Public void window closing (window Event we)

System. Exit (0);

});

}
Public void adjustmentvaluechanged (Adjustmetn Event ae)

Repaint ( ); // call paint ( )

Public void paint (Graphics g)

Display the position of scrollbar

g. drawstring (“SCROLLBAR POSITION: “. 20,150);

msg + = s1.get Value ( );

g.draw string (msg, 20,180);

msg= “ “;

Public static void main (String args [ ])

//create the frame

Myscroll m = new Myscroll ( );

Ms. Set Title (“My scroll bar”);

Ms. Set Size (400,400);

Ms. Set Visible (true);

You might also like