Unit 4-Java IN R&R
Unit 4-Java IN R&R
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.
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.
*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:
Square=9.0
Square=16.0
Square=25.0
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
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
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.
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:
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
Child’s height=6.0
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.
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.
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.
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.
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;
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.
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
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.
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.
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
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.
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);
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);
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
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.
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
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.
Thread synchronization
*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()
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
Thread deadlock
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
Non-Runnable
(Blocked)
Running
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.
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.
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.
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.
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
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
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
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
A window represents any imaginary rectangular area on the screen without any borders or title bar, A
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
The third way is to create a subclass My Frames to the Frame class and
Since, My Frame is a subclass of Frame class, its object f contains a copy of Frame class and hence f
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:
Here, the frame’s width is set to 400 px and height to 350 px. Then, we can display the frame, using set
Class MyFrame
//Create a frame
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
example, we can create the component in Java and the action logic can
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.
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
Program 3: Write a program which first creates a frame and then closes it on clicking the close button.
Import java.awt.*;
Import java.awt.event.*;
Graphics class of java.awt package has the following methods which help to draw various shapes.
This method draws outline of a rectangle. The left top corner of the rectangle starts at (x,y),the width is
drawRoundRect (int x,int y, int w,int h,int arcw, int arch): This method
top left corner starts at (x,y), the width is w, and height is h. The
and arch. Arcw represents horizontal diameter of the arc at the corner
Draw Oval (int x, int y, int w,int h): This method draws a circle or
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
Program 6: Write a program to draw a smiling face using the methods of Graphics class.
Import java.awt.event.*;
Draw1 ( )
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
fill RoundRect (int x, int y,int w, int h, int arcw, int arch): This method
filloval (int x, int Y, int w, int h): This method is useful to create an oval
fillArc(int x, int w, int h,int h int sangle, int aangle): This method draws
Program 7: Write a program that allows you to fill the shapes with some colors.
Import java.awt.
Draw 2 ( )
System.exit (0);
});
// face
//nose
//My Home
Import java.awt.*;
Import java.awt.event.*;
Home ( )
System.exit (0);
});
{
// store x, y coordinates in x [ ] and [ ]
Int x [ ] = {375,275,475};
Int y [ ] = {125,200,200};
g. drawLine (350,280,400,280);
To display some text or strings in the frame, we can take the help of drawstring ( ) method of Graphics
class,as;
If we want to set some color for the text, we can use set color ( ) method of Graphics class as:
there are two ways to set a color in AET. The first way is by directly mentioning the needed color name
The second way to mention any color is by combining the three primary colors: red, green and blue
Here, r,g,b values can change from 0 to 255, 0 represents no color. 10 represents low intensity whereas
Program 11: Write a program to display some text in the frame using drawstring ( ) method.
Import java.awt.event.
Message ( )
{
System .exit (0);
});
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.
Images ( )
Img=Too1kit.getDefaultToolkit().get Image(“diamonds.gif”);
Track.addImage (img,0);
Try{
//let the JVM wait till the image is loaded completely track.wait ForID
(0);
System.exit (0);
});
}
g.drawImage (img,50,50,nu11);
i.set Iconimage(img);
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.
Button b =new Button (“label”); //a button without any label is created.
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.
Checkbox cb=new Checkbox(“label”, state); //if state is true, then the check
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 (rows, cols); // text area with some rows and // columns
Text Area ta = new Text Area (“string”); //text area with predefined string
To insert the specified text at the specified position in this text area:
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:
Program 20: Write a program to create a list box with of some languages from where the user can select
Import java.awt.*;
Import java.awt.event.*;
//vars
int [ ] msg;
List 1st;
My list ( )
Add(1st);
//frame closing
});
} //end of constructor
Repaint ( );
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
int x = getorientation ( );
Program 21: write a program to create a vertical scrollbar with scroll button length 30px and with the
Import java.awt.*;
Import java.awt.event.*;
Class Myscroll extends Frame implements Adjustment Listener
//vars
Scrollbar s1;
My scroll ( )
setlayout (nu11);
//add it to frame
Add (s1);
// frame closing
});
}
Public void adjustmentvaluechanged (Adjustmetn Event ae)
msg= “ “;