Programming in Java
Programming in Java
STUDY MATERIAL
SEMESTER: V
SYLLABUS
UNIT: I
UNIT: II
UNIT: III
UNIT: IV
UNIT: V
BOOK FOR STUDY Programming with Java, 4th Edition, E. Balagurusamy, Tata McGraw
Hill Pub. Ltd., New Delhi.
BOOKS FOR REFERENCE ―The Complete Reference‖ Java2, 3rd Edition, Patrick
Naughton, Herbert Schildt, Tata McGraw Hill Pub. Ltd., New Delhi.
REFERENCE WEBSITE:
Www.Wikipedia.Org
Www.Homeandlearn.Co.Uk
UNIT: I
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------
INTRODUCTION
Types of Applications
BYTE CODES
The java object frame work acts as the intermediary between the user programs and the
virtual machine which in turn acts as the intermediary between the operating system
and the java object framework.
FEATURES OF JAVA
API
Java environment includes a large number of development tools and hundreds of
classes and methods.
The development tools are part of the system known as Java Development Kit(JDK)
and the classes and methods are part of the Java Standard Library(JSL), also known as
the Application Programming Interface(API).
JAVA DEVELOPMENT KIT (JDK)
Java Development Kit comes with a collection of tools used for developing and
running java programs. They are
Applet viewer (for viewing java applets)
Javac (java compiler)
Java(java interpreter)
Javap(java dissembler)
Javab(for C header files)
Javadoc(for creating HTML document)
Jdb(java debugger)
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
division
System.out.println("b="+b );
System.out.println("a+b="+( a-b));
System.out.println("a*b="+( a*b));
System.out.println("a/b="+( a/b);
System.out.println("a%b="+( a%b));
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 15
}
When one of the operands is real and the other is an integer, the expression is
called a mixed-mode expression.
If either operand is of the real type, then the other operand is converted to real
and the real arithmetic is performed.
E.g.: 15/10.0=1.5
15/10=1
RELATIONAL OPERATORS
Compares two
ae-l relational operator ae-2 Operato Meaning
quantities depending on their relation.
r
Java supports six
< Is less than
relational operators.
<= Is less than or
equal to
A simple relational expression contains
> Is greater than
only one relational operator and is of the
>= Is greater than or
following form:
equal to
== Is equal to
ae-1 relational operator ae-2
!= is not equal to
Operator Meaning
&& Logical AND
A logical operator returns either TRUE or
|| Logical OR
FALSE values.
! Logical NOT
Truth Table
Logical operator && and || are used to check compound condition (ie for combining two
or more relations)
When an expression combines two or more relational expressions then it is called logical
expression or a compound relational expression
V variable
Exp expression
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
A=a % b a%=b
Eg:
Advantages:
It has 3 advantages
Easy to write.
Easy to read
Efficient code.
Eg. a[i++]
Sample Program:
class Incrementoperator
{
public static void main(String args[ ])
{
int m=10,n=20;
System.out. println("m=" +m);
System.out. println("n="+n);
S ystem.out. println("++m="+++m);
System.out.println("n++="+n++);
Systern.out. println("m="+m);
System .out. println("n="+n);
}
}
Output
m=10
++m=11
m=11
n=20
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 19
n++=21
n=21
CONDITIONAL OPERATORS
General Form
Exp1 ? exp2: exp3
Exp1, exp2, exp3 are expressions
The operator ?: works as follows
Eg a=10;
b=15
X= (a>b) ? a : b;
The output is X=15
BITWISE OPERATORS:
Operator Meaning
^ Bitwise exclusive OR
~ One’s complement
When a program breaks the sequential flow and jumps to another part of
the code, it is called branching.
When the branching is based on a particular condition, it is known as
conditional branching.
If branching takes place without any decision, it is known as
unconditional branching.
The following statements are known as control or decision making
statements.
If statement
Switch statement
Conditional operator statement
DECISION MAKING WITH IF STATEMENT
If statement is a powerful decision making statement and is used to control the flow of
execution of statements.
General form
if (test expression)
General form
if (test expression)
{
statement-block;
}
Statement-x;
THE ? : OPERATOR
If (x<0)
DISCUSS ABOUT THE ?: OPERATOR. (4MARKS) Flag=0;
Else
Flag=1;
It is a two-way decision making operator
Ex1: Can be
This operator is a combination of ? and : and takes three operands. written as
This operator is popularly known as the conditional operator.
Flag = (x<0) ? 0 : 1;
THE DO STATEMENT
In do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the test condition in the while statement is evaluated.
If the condition is true, the program continues to evaluate the body of the loop once
again.
The program continues to evaluate the body of the loop as long as the condition is
true.
When the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement.
(1) Initialization of the control variables is done first, using assignment statements such
as i=1 and count=0. The variable i and count are known as loop-control variables.
(2) The value of the control variables is tested using the test condition. The test
condition is a relational expression, such as i<10 that determines when the loop will
exit.
It the condition is true, the body of the loop is executed; otherwise the loop
is terminated and the execution continues with the statement that
immediately follows the loop.
General form
For (initialization; test condition;
increment)
{
Body of the loop
}
A FOR loop which is present inside of another FOR loop is called nesting of for
loop.
An arithmetic expression can be evaluated from left to right using the rules of
precedence of operators.
There are two distinct priority levels:
High */%
priority
Low priority + -
Loops perform a set of operations repeatedly until the control variable fails to satisfy
the test condition.
Java permits a jump from one statement to the end or beginning of a loop as well as a
jump out of a loop.
FORMAT: EXAMPLE
continue; For(…….)
While (test condition) {
{
……
……
If (condition) If (condition)
Continue; Continue;
……. …….
……. …….
} }
LABELLED LOOPS
Class SampleOne
{
Public Static void main (String args[])
{
System.Out.Println(“welcome to AVS
COLLEGE”);
}
}
Class declaration
Opening Brace
Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.
Every java application program must include the main() method. This the starting
point for the interpreter to begin the execution of the program.
A java application can have any number of classes but only one of them must include a
main method to initiate the execution.
Public : the keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
Static : which declares this method as one that belongs to the entire class and not a part
of any object of the class. The main methods must always be declared as static since
the interpreter uses this method before any object are created.
Void: the void states that the main method does not return any value.
Since java is a true object oriented language, every method must be part of an object.
The println method is a member of the Out object, which is a static data member of
System class.
More of java
Import java.lang.math;
The above statement instruct the interpreter to load the Math class from the package
lang.
JAVA FEATURES
Tool Description
javah( for C header files) Produces header files for use with native method.
JAVA TOKENS
Introduction
An array is a group of contiguous or related data items that share a common name.
A list of items can be given one variable name using only one subscript called single
subscripted variable or one dimensional array.
E.g. int value=new int [5] represent a set of five integer values.
Creating an array
Arrays must be declared and created in the computer memory before they are used.
Example
Int number[];Int[] number;
Float average[];Float[] average;
Creating memory locations
Initialization of Arrays
Arrayname [subscript]=value;
Eg: Number[0]=90;
Number[1]=100;
……….
Arrays starts with a subscript 0 and ends with a value one less than the size specified.
If size is not specified means compiler allocates enough space for all the elements
specified in the list
Array length
Two-dimensional array
Eg : int myarray[][];
Myarray=new int[3][4];
Or
{0,0,0}
{1,1,1}
VECTORS
Vector class is used to create a generic dynamic array known as vector that can hold
objects of any type and any number.
Created like
Advantage
A vector can be sued to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required.
In java strings are class objects and implemented using two classes; String and
StringBuffer.
General form Eg
String firstname;
String stringname; Firstname=new String(“anil”);
Stringname=new Or
String(“string”); String firstname=new String(“anil”);
String array
Item[0]=”soap”;
Item[1]=”biscuits”;
Item[2]=”powder”;
S1.indexOf(‘x’,’n’); Gives the position ‘x’ that occurs after nth position in
the string s1
StringBuffer class
StringBuffer class creates string of flexible length that can be modified in terms of both
length and content.
In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end.
Methods Task
Example program
class stringmanipulation
int p=i+1;
// modifying characters
Str.setcharAt(6,’-‘);
Unit: I
Section-B (4 Marks)
1. Explain Identifier?
2. Short notes on constant and examples?
3. Explain control statements?
4. Explain looping statements?
UNIT II
………………………………………………………………………………………………
Classes, Interfaces and Packages: Classes – Objects – Wrapper Classes – Packages and
Interfaces.
…………………………………………………………………………………………………
CLASSES AND OBJECTS
INTRODUCTION
CLASS: “A class is a way of binding the data and associated methods in a single
unit”
Any JAVA program if we want to develop then that should be developed with
respective class only i.e., without class there is no JAVA program.
Classes create objects and object uses methods to communicate between them.
Classes provide convenient method for packing together a group of logically related
data items and functions that work on them.
DEFINING A CLASS
A class is a user-defined data type with a template that serves to define its properties.
Anything in square bracket is optional.
Classname and superclassname are valid java identifier.
The keyword extends indicates that the properties of the superclassname class are
extended the classname class.
Data is encapsulated in a class by placing data fields inside the body of the class
definition.
These variables are called instance variables because they are created whenever an
object of the class is instantiated.
Instance variables are also know as member variables.
Example
Class Triangle
{
int length;
Int height;
}
The class triangle contains two integer type instance variable, length
and height.
CREATING OBJECT
OBJECT: In order to store the data for the data members of the class, we must create
an object.
Instance (instance is a mechanism of allocating sufficient amount of memory
space for data members of a class) of a class is known as an object.
Class variable is known as an object.
Grouped item (grouped item is a variable which allows us to store more than
one value) is known as an object.
Value form of a class is known as an object.
Blue print of a class is known as an object.
Real world entities are called as objects.
Eg2: Triangle tri1 = new Triangle ( ); tri1 and tri2 are the objects of
Triangle class
3) When the class id defined there is no 3) When an object is created we get the
memory space for data members of a memory space for data members of the
class. class.
Syntax:
Accessing variables
Accessing method
Objectname. Variablename
E.g.
Objectname.methodname(parameter Tri1.length=10;
-list); Tri1.getdata (10, 20);
Tri1.height=20;
CONSTRUCTORS
Class Volume
{
Int x,y,z;
Volume() // constructor
{
x=10;
Y=10;
Z=30
}
Public int calvolume()
{
int vol=x*y*z;
Return vol;
}
}
Class Demovolume()
{
Public static void main(String arg[])
{
Volume volobj=new Volume; // creating object
Int result=volobj.calvolume(); // calling method
System.out.println(“the volume is =”+result);
}
}
ADVANTAGES of constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
1. Constructor name must be similar to name of the class.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
1. Default/parameter less/no argument constructor and
2. Parameterized constructor.
1. DEFAULT CONSTRUCTOR
A default constructor is one which will not take any parameters.
Syntax:
E xample:
class <clsname>
{ class Test
clsname () //default constructor { {
Block of statements; int a, b;
Test ()
………………………………; {
System.out.println ("I AM FROM
PARAMETERIZED CONSTRUCTOR
A parameterized constructor is one which takes some parameters.
Syntax:
class <clsname>
{
…………………………;
…………………………;
<clsname> (list of parameters)
//parameterized constructor
{
Block of statements (s);
}
METHOD OVERLOADING
Class Volume
{
int area()
{
int val=10*20*30;
return val;
}
int area(int m, int n)
{
int val=m*n;
return val;
}
int area(int l, int m, int n)
{
int val=l*m*n;
return val;
}
float area(float m, float n)
{
float val=m*n;
return val;
}
float area(int l, float m, int n)
{
float val=l*m*n;
return val;
}
}
Class Demovolume()
{
Public static void main(String arg[])
{
Calculatearea calarea=new calculatearea();
Int result1, result2, result3;
Float result4, result5;
result1=calarea.area();
result2=calarea.area(10,20);
AVS & SAKTHI KAILASH result3=calarea.area(100,200,300);
GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 67
result4=calarea.area(10.2,20.2);
result5=calarea.area(10,20.2,10);
System.out.println(result1,result2,result3, result4,result5);
NESTING OF METHODS
A method can call other methods of the same class. This is known as nesting of
methods.
Example
Wrapper classes are basically used for converting the string data into fundamental data
type. Each and every wrapper class contains the following generalized parse methods.
Vectors cannot handle primitive data types like int, float, double and char.
This conversion is done by using the wrapper class contains in the java.lang package
float num1=Float.ValueOf(in.readLine());
int val=Integer.ParseInt(in.readLine());
INTERFACES:
Interface <interface
name>
Example
{ Interface is a keyword which is used for developing user
interface item
{
defined data
static types.
final int code = 1001;
Variable declaration;
void display();
Interface
}
name represent a JAVA valid variable name and
Method declaration;
it is treated as name of the interface.
} With respect to interface we cannot create an object
directly but we can create indirectly.
EXTENDING INTERFACE
Example
interface name1
{
AVS & SAKTHI KAILASHvoid
GROUP OF INSTITUTIONS
display(); DEPARTMENT : BCA Page 73
}
interface name2 extends name1
{
IMPLEMENTING INTERFACES
class mainpgm
{
interface interfaceA public static void main(String s[])
{ {
final int m=10; ClassA objA=new classA();
} objA.show();
class ClassA implements interfaceA }
{ }
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 74
void show()
{
System.out.println(m);
}
}
PACKAGE
INTRODUCTION
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name and
the class name.
Packages provide a way to "hide" classes thus preventing other programs or packages
from accessing clases that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".
Packages Contents
1. Using the fully qualified class name. (Using the package name containing the
class and then appending the class name by using the dot operator.)
E.g. java.awt.Color
Best and easiest one to access the class
Used only once, not possible to access other classes of the package.
2. Using the import statement, appear at the top of the file. Imported package
class can be accessed any where in the program
Or
import packagename.* ;
Double y = java.lang.Math.sqrt(x);
CREATING PACKAGES
First declare the name of the package using the package keyword followed by a
package name.
Steps:
package packagename;
Define the class that is to be put in the package and declare it public.
Create a subdirectory under the directory where the main source files are stored.
Example
ACCESSING A PACKAGE
USING A PACKAGE
Example 1
Section-A (2 Marks)
Section-B (4 Marks)
…………………………………………………………………………………………………
Inheritance: Inheritance Extending classes – Abstract and Final classes – Interfaces and
Inheritance
…………………………………………………………………………………………………
INTRODUCTION
Inheritance is the process of taking the features(data members + methods) from one
class to another class.
The class which is giving the features is known as base/parent class.
The class which is taking the features is known as derived/child/sub class.
Instance is known as sub classing or derivation of extendable classes or reusability.
ADVANTAGES OF INHERITACE:
Application development time is very less.
Redundancy (repetition) of the code is reducing. Hence we can get less memory cost
and consistent results.
Instrument cost towards the project is reduced.
We can achieve the slogan write one’s reuse/run anywhere of java.
TYEPS OF INHERITANCE
Based on taking the features from base class to the derived class, in JAVA we
have five types of inheritances. They are as follows.
1. Single inheritance
Single class is one in which there exists single base class and single derived class
3. Hierarchical inheritance
Hierarchical inheritance is one in which there exits single base class and n number of
derived classes.
4. Multiple inheritance
derived classes.
Multiple inheritances are one supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.
5. Hybrid inheritance
Hybrid inheritance = combination of any available inheritances types
In the combination , one of the combinations is multiple inheritances.
Hybrid inheritance also will not be supported by JAVA through the concept of
classes but it is supported through the concept of interfaces.
SINGLE INHERITANCE
When a single sub class extends the properties of a single super class, then it is known
as single level inheritance.
Example
class Room
int volume ()
{ {
return (Length*Breadth*Height);
int Length, Breadth;
}
Room (int x, int y) }
class inhert
{ {
public static void main (String args[])
Length=x; {
Room1 obj=new Room1(14,12,10);
Breadth=y;
int area1=obj.area ();
} int volume1=obj.volume();
System.out.println(“Area1 =”+area1);
int area () System.out.println(“Volume =”+volume1);
{ }
return (Length*Breadth);
}
}
class Room1 extends Room
Volume=6000
System.out.println(“Volume=”+(i*j*k));
}
}
HIERARCHAL INHERITANCE
When a finally of classes is created in hierarchal model then it is called as hierarchal
inheritance.
Example
class A
class mainclass
{ {
public static void main(String args [])
int a, b; {
A obja=new A();
void input() B objb=new B();
{ C objc=new C();
obja.input1();
a=10; objb.a=10;
objb.b=20;
b=20; objb.addtion();
objc.a=10;
System.out.println(“a=”+a+”b=”+b); objc.b=20;
objc.product();
}
}
} }
class B extends A
{
void addition ()
{
System.out.println(“a+b=”+(a+b));
}
}
class C extends A
{ void product ()
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 89
{
System.out.println(“a*b=”+(a*b));
}
}
ABSTRACT AND FINAL CLASSES
ABSTRACT CLASS
ABSTRACT METHODS {
When a method is defined as final than that method is not re- abstract void sum ();
defined in a subclass. };
When a final method is called, java compiler can copy the byte code for the subroutine
directly inline with the compiled code of the calling method, thus eliminating the
overhead of the method call.
2. Using final to prevent inheritance
When we want to prevent a class from being inherited, then the class can be declared
as final.
When a class is declared as final then it implicitly declared all of its methods as final.
It is illegal to declare a class a both abstract and final since an abstract class is in
complete by itself and relies upon its sub classes to provide complete implementations.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 92
FINAL VARIABLES AND METHODS
It prevents the subclasses form overriding the member of the superclass.
Final variables and methods are declared as final using the keyword final as a
modifier.
Making a method final ensures that the functionality defined in that method will never
be altered in any way.
The value of a final variable can never be changed.
Final classes
A class that cannot be sub-classed is called a final class.
It prevents a class being further sub-classed for security reasons.
Any attempt to inherit these classes will cause an error.
FINALIZER METHODS
Initializationà constructor method is used to initialize an object when it is declared.
This process is called initialization.
Finalizationàfinalizer method is just opposite to initialization, it automatically frees
up the memory resources used by the objects. This process is known as finalization.
METHOD OVERRIDING
A method defined in a super class is inherited by its sub class and is used by the objects
created by the sub class.
There may be occasions when we want an object to respond to the same method is called.
This is possible by defining a method in the sub class that has the same name, same
arguments and same return type as a method in the super class.
When the methods are called, the method defined in the sub class is invoked and executed
instead of the one in the super class. This is known as overriding.\
Example
class Super
{ int x; void display ()
Super (int x) {
System.out.println(“Super x=”+x);
{ System.out.println(“Sub y=”+y);
this.x; } }
class overridetest
} {
void display () public static void main (String args[])
{
{ Sub S1=new Sub (100, 200);
System.out.println(“x=”+x); S1.display ();
}
} }
}
class Sub extends Super
{ int y;
Sub (int x, int y)
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 94
super (x);
this.y=y;
}
}
METHODS WITH VARARGS
Varargs represents variable length arguments in methods.
It makes that java code simple and flexible.
General form
<access specifier> <static> void method-name (object …
arguments)
{
}
In the above syntax The method contains an argument called varargs in which
Object is the type of an argument
Ellipsis (…) is the key to varargs
Argument is the name of the variable.
For eg: Public void sample(String username, String password, String mail)
Can be written as Public void sample (String …var_name)
Here var_name is the variable name that specifies that we can pass any number of
String arguments to the sample method.
1. What is Inheritance?
2. What is Public Access?
3. Defining Interfaces?
4. What is Extending Interfaces?
Section-B (4 Marks)
UNIT: IV
----------------------------------------------------------------------------------------------------------------
Exception Handling: Error Handling and Exception Handling – Exception
Types and Hierarchy – Try Catch blocks – Use of Throw, Throws and Finally – Programmer
Defined Exceptions.
---------------------------------------------------------------------------------------------------------------
EXCEPTION HANDLING
INTRODUCTION
Compile time errors are those which are occurring because of poor
understanding of the language.
Run time errors are those which are occurring in a program when the user
inputs invalid data.
The run time errors must be always converted by the JAVA programmer into
user friendly messages by using the concept of exceptional handling.
COMPILE-TIME ERRORS
All syntax errors will be detected and displayed by the Java compiler and therefore
these errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
It is therefore necessary that we fix all the errors before we can successfully compile
ad run the program.
Most of the compile-time errors due too typing mistakes. Typographical errors are
hard to find.
We may have to check the code word by word, or even character by character.
The most common problems are:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 100
Missing semicolons
Missing brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables.
Incompatible types in assignments/initialization
Bad references to objects
Use of = in place of = = operator
RUN-TIME ERRORS
Sometimes, a program may compile successfully creating the .class file but may
not run properly.
Such programs may produce wrong results due to wrong logic or may terminate due
to errors such as stack overflow.
Most common run-time errors are:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 101
Dividing an integer by zero
Accessing an element that is out of bounds of an array
Trying to store a value into an array of an incompatible
class or type
Trying to cast an instance of a class to one of its subclasses.
Passing a parameter that is not in a valid range or value for
a method.
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference as a legitimate object reference
to access a method or a variable.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
Example
class Example
{
public static void main(String
args[])
{
int d=0;
int a = 42/d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs
a new exception object and then throws this exception. This causes the execution of
example to stop, because once an exception has been thrown, it must be caught by an
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 102
exception handler and dealt with immediately. In this example, we haven’t supplied any
exception handlers of our own, so the exception is caught by the default handler provided
by the Java run-time system.
Java exception is an object that describes an exceptional (that is error) condition that
has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. Either way, at some point, the
exception is caught and processed.
Exception can be generated by the Java run-time system, or they can be manually
generated by your code.
If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then display
an appropriate message for taking corrective actions. This is known as exception
handling.
In JAVA we have two types of exceptions they are custom defined exceptions
User Defined Exceptions.
Predefined Exceptions.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 103
Predefined exceptions are those which are developed by SUN micro system and
supplied as a part of JDK to deal with universal problems. Some of the universal
problems are divide by zero, invalid format of the number, invalid bounce of the
array
Predefined exceptions are divided into two types.
synchronous exceptions.
Asynchronous exceptions.
Asynchronous exceptions.
Asynchronous exceptions are those which are always deals with hardware
problems. In order to deal with asynchronous exceptions java.lang.Error class
is the super class for all
synchronous exceptions
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 104
Synchronous exceptions are one which always deals with programmatic errors.
In order to deal with synchronous exceptions we must predefine the class called
java.lang.exception
Synchronous exceptions are of two types
They are checked exceptions
i. A checked exception is one whichfound and interface not found.
ii. Unchecked exceptions are those which are always deals with
programmatic run time errors such as ArithmeticException,
NumberFormatException, ArrayIndexOutOfBoundsExcept An exception is an
object which occurs at run time which describes the nature of the message.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 105
The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken.
The mechanism suggests incorporation of a separate error handling code that performs
the following tasks:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 106
and number fails.
In order to handle he exceptions in java we must use the fallowing key words. They are
try,
catch, finally, throws and throw.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 107
try
{
Block of statements which are to be monitored by JVM at run time (or
problematic errors);
}
catch (Type_of_exception1 object1)
{
Block of statements which provides user friendly messages;
}
catch (Type_of_exception2 object2)
{
Block of statements which provides user friendly messages;
}
.
.
.
catch (Type_of_exception3 object3)
{
Block of statements which provides user friendly messages;
}
finally
{
Block of statements which releases the resources;
}
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 108
The basic concept of exception handling are throwing an exception and catching it.
try block
Exception object Creator
catch block
Java exception handling is managed via keywords: try, catch,throw, throws and
finally.
Program statements that you want to monitor for exceptions are contained within a try
block.
If an exception occurs within the try block, it is thrown. Your code can catch this
exception and handle it in some rational manner.
To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws
clause.
Any code that absolutely must be executed before a method returns is put in a finally
block.
Try block:
This is the block in which we write the block of statements which are to be
monitored by JVM atrun time i.e., try block must contain those statements which
causes problems at run time.
If any exception is taking place the control will be jumped automatically to
appropriate catch block.
If any exception is taking place in try block execution will be terminated and the rest
of the statements in try block will not be executed at all and the control will go to
catch block.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 109
For every try block we must have at least one catch block. It is highly recommended
to write ‘n’number of catch’s for ‘n’ number of problematic statements.
Catch block:
This is used for providing user friendly messages by catching system error messages.
In the catch we must declare an object of the appropriate execution class and it will
be internally referenced JVM whenever the appropriate situation taking place.
If we write ‘n’ number of catch’s as a part of JAVA program then only one catch
will be executing at any point.
After executing appropriate catch block even if we use return statement in the catch
block the control never goes to try block.
Finally block:
This is the block which is executing compulsory whether the exception is taking place
or not.
This block contains same statements which releases the resources which are obtained
in try
block (resources are opening files, opening databases, etc.).
Writing the finally block is optional.
Example
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 110
class Example OUT PUT
{ Division by zero
{
try
{
int d=0;
int a = 42/d;
}
catch( ArithmeticException e)
{
System.out.println(“Division by
zero”);
}
d=5;
System.out.println(“d=”+d);
}
}
class Multicatch
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 111
public static void main(String[] args)
{
try
{
int a=args.length;
System.out.println(“a=”+a);
int b= 42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by zero:”+e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index Out Of Bound:”+e);
}
System.out.println(“After try/catch block.”);
}
}
This program will cause division by zero exception if is started with no command-line
parameters, since a will equal zero.
It will survive the division if you provide a command-line argument, setting a to
something larger than zero.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 112
But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a
length of 1, yet the program attempts to assign a value to c[42].
THROWS
There may be times when we would like to throw our own exceptions. We can do this
by using the keyword throws as follows:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 113
class ExceptionDemo
{
static void compute( int a ) throws MyException
{
System.out.println(“Called compute(“+a+”)”);
if (a > 10 )throws new MyException(a);
System.out.println(“Normal Exit”);
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch(MyException e)
{
System.out.println(“Caught”+e);
}
}
}
Called compute(1)
Normal Exit
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 114
Called compute(20)
Caught MyException[20]
If a method is capable of causing an exception that it does not handle, it must specify
this behaviour so that callers of the method can guard themselves against the
exception.
You do this by including a throws clause in the method’s declaration.
FINALLY
Java supports another statement known as finally statement that can be used to handle
an exception that is not caught by any of the previous statement.
finally block can be used to handle any exception generated within a try block.
It may be added immediately after the try block or after the last catch block shown as
follows.
try try
{ {
--- ---
--- ---
} }
finally
catch( )
{ {
--- -----
} --- --
}
….
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 115
….
finally
{
---
---
}
Example
class FinallyDemo
Output
{ inside procA
procA’s finally
static void proA( )
{
try
{
System.out.println(“Inside ProcA”);
}
finally
{
System.out.println(“ProA’s finally”);
}
}
public static void main( String args[] )
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 116
procA( );
}
}
PROGRAMMER DEFINED EXCEPTIONS
User defined exceptions are those which are developed by JAVA programmer as a part
of
application development for dealing with specific problems such as negative salaries,
negative ages,
etc.
Guide lines for developing user defined exceptions:
Choose the appropriate package name.
Choose the appropriate user defined class.
Every user defined class which we have choose in step 2 must extends either
java.lang.Exception or java.lang.RunTimeException class.
Every user defined sub-class Exception must contain a parameterized
Constructor by taking string as a parameter.
Every user defined sub-class exception parameterized Constructor must called
parameterized Constructor of either java.lang.Exception or
java.lang.RunTimeException class by using super(string parameter always).
For example:
package na; // step1
public class Nage extends Exception // step2 & step3
{
public Nage (String s) // step4
{
super (s);// step5
}
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 117
};
NOTE: Main method should not throw any exception since the main method is called by
JVM and JVM cannot provide user friendly message.
QUESTION BANK
UNIT 4
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 118
8) Describe string buffer class?5 MARK
9) Explain the operators in java? 5 MARK
10) Explain multithreaded programming?10 MARK
UNIT: V
----------------------------------------------------------------------------------------------------------------
Applets and Graphics: Fundamentals of Applets – Graphics. AWT and Event Handling:
AWT components and Event Handlers – AWT Controls and Event Handling Types and 35
Examples – Swing- Introduction. Input and Output: Files – Streams. Multithreading and
Networking: Multiple Threads – Networking basics.
----------------------------------------------------------------------------------------------------------------
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 119
They are standalone applications and distributed applications.
A standalone application is one which runs in the context of local disk
and whose result is not sharable. Every standalone application runs from
command prompt and it contains main method along with
System.out.println statements.
A distributed application is one which runs in the context of browser or
World Wide Web and it can be accessed across the globe. Any
technology which runs in the browser will have ‘n’ number of life cycle
methods and it does not contain main methods and
System.out.printlnstatements.
In JAVA, SUN micro initially has developed a concept called applets which runs in
the context of browser. “An applet is a JAVA program which runs in the context of
browser or World Wide Web”.
In order to deal with applets we must import a package called java.applet.*. This
package contains only one class Applet whose fully qualified name is
java.applet.Applet. Since applets are running in the browser, the class Applet contains
the life cycle methods.Life cycle methods are also called as loop back methods.
FUNDAMENTALS OF APPLETS
Applets are small java program that are primarily used in internet computing. They can
be transferred over the internet from one computer to another and run using the applet
viewer or any web browser that support the java program.
An applet can perform arithmetic operations, play sounds, display graphics, accept user
input, create animation and play interactive games.
Java applications are generally run from a command-line prompt using JDK. Applets are
run on any browser supporting Java. For an applet to run it must be included in a web
page using HTML pages.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 120
When a browser loads a web page including an applet, the browser downloads the applet
from the web server and runs it on the web owner’s system. Java interpreter is not
required specifically for doing so it is already built-in the browser.
LOCAL APPLET
An applet developed locally and stored in a local system called as local applet.
They doesn’t require internet connection It searches the directories in the local system
and locates and loads specified applet.
REMOTE APPLET
It is stored on a remote computer which is connected to the net. If connected with the net,
we can download the remote applet onto our system. We can utilize it via the internet.
URL
Uniform Resource Locator. It specifies the applets address.
Applet code uses the service of two classes namely, Applet and Graphics from the Java
library.
The applet class is contained in the java. Applet package provides life and
behavior to the applet through its methods such as init(), start(), and paint().
The Applet class maintains the lifecycle of an applet.
The paint() method of the applet class actually displays the result of the applet
code on the screen.
APPLET LIFE CYCLE
Every java applet inherit a set a default behavior from the Applet class. As the result
applet is loaded, it undergoes a series of changes in its state as shown in the above figure
the applet states will be
Born or initialization state
Running state
Idle state
Dead or destroyed state
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 121
In java.applet.Applet we have four life cycle methods.
They are public void init (), public void start (), public void stop () and public void
destroy ()
1. Public void init ():
This is the method which is called by the browser only one time after loading the
applet.
In this method we write some block of statements which will perform one time
operations, such as, obtaining the resources like opening the files, obtaining the
database connection, initializing the parameters, etc.
It is achieved by calling init() method of the applet class.
Syntax:
Public void init()
{
……..
}
2. Public void start ():
After calling the init() method, the next method which is from second request to
sub-sequent requests the start method only will be called i.e., short method will be
called each and every time.
In this method we write the block of statement which provides business logic.
Syntax:
Public void start()
{
………
}
5. Run the applet: To run the applet we have two ways. They are using HTML
program and using applet viewer tool.
Using HTML program: In order to run the applet through HTML program we must use
the following tag.
Syntax:
<applet code =”.class file of the applet” height = height value width =
widthvalue>
</applet>
For example:
File name: MyApp.html
<HTML>
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 124
<HEAD>
<TITLE> My applet example </TITLE>
</HEAD>
<BODY>
<APPLET code="MyApp" height=100
width=150>
</APPLET>
</BODY>
</HTML>
Usingappletviewer:
Appletviewer is a tool supplied by SUN micro system to run the applet programs from
the command prompt (in the case of browser is not supporting).
For example:
appletviewer MyApp.java
When we use appletviewer to run the above applet, MyApp.java program must
contain the
following tag within the multi line comment.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 125
</applet>*/
EXAMPLE:
An applet program which displays “WELCOME TO AVS COLLEGE”
Program:
GRAPHICS
GRAPHICS
One of the most important features of Java is its ability to draw graphics .
Java’s graphics class includes methods for drawing many different types of shapes.
To draw a shape on the screen , we may call one of the methods available in the
graphics class.
The following are the most commonly used methods in graphics class.
Methods:
drawLine()
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 126
drawRect()
fillRect()
drawRoundRect()
fillRoundRect()
Ex:
Import java.awt.*;
Import java.applet.*;
/*<Applet code = “line.class” height=100 width=200>
</Applet>*/
Public class line extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRect(60,10,30,80);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,100,70,30,5,5);
}
}
Circles and Ellipses:
It is achieved by using
drawOval()
fillOval()
Ex:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 127
Import java.awt.*;
Import java.applet.*;
/*<Applet code = “cir.class” height=100
width=200>
</Applet>*/
Public class cir extends Applet
{
public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(color.Green);
g.fillOval(70,30,100,100);
}
Arcs:
It is achieved by using
drawArc()
drawOval()
Ex:
Import java.awt.*;
Import java.applet.*;
/*<Applet code = “larc.class” height=100
width=200>
</Applet>*/
Public class larc extends Applet
{
public void paint(Graphics g)
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 128
g.drawOval(40,40,120,150);
g.fillOval(68,81,10,10)
g.fillArc(60,125,80,40,180,180);
}
}
Polygons:
Syntax:
Void drawPolygon(int x[], int y[], int
numpoints)
AWT (abstract window
toolkit)
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 129
java.awt.* (contains various classes and interfaces for creating GUI components) and
java.awt.event.* (contains various classes and interfaces which will provide functionality to
GUI components).
Except Object class and Applet class all the classes in the above hierarchy chart are
belongs
to java.awt.* package.
A JAVA program which creates Window and Frame
import java.awt.*;
class myf extends Frame class FDemo
{ {
Myf () Public static void main
(String [] args)
{ {
setText (“AVS COLLEGE BCA”); Myf mo=new myf ();
setSize (100, 100); }
LABEL setBackground (Color, cyan); }:
CLASS: setForeground (Color, red);
setVisible (true);
}
};
Label is a class which is used for creating label as a part of windows application.
The component label comes under passive component.
Labels always improve the functionality and readability of active components.
Creating a label is nothing but creating an object of label.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 130
Label class API:
Data members:
public static final int LEFT (0)
public static final int CENTER (1)
public static final int RIGHT (2)
//The above three statements are called alignment parameters or modifiers.
Constructors:
Label ()
Label (String)
Label (String label name, int alignment modifier)
Instance methods:
public void setText (String);
public String getText ();
public void setAlignment (int);
public int getAlignment ();
BUTTON CLASS:
Button is an active component which is used to perform some operations such as
saving thedetails into the database, deleting the details from the database, etc.
Creating a button is nothing but creating an object of Button class.
Button API:
Constructors:
Button ();
Button (String);
Instance methods:
public void add ActionListener (ActionListener);
public void remove ActionListener (ActionListener);
CHOICE:
Choice is the GUI component which allows us to add ‘n’ number of items.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 131
This component allows selecting a single item at a time.
Creating a choice component is nothing but creating an object of Choice class.
Choice API:
Constructors:
choice ();
Instance methods:
public void add (String);
public void addItem (String);
public void add (int pos, String);
public void addItem (int pos, String);
public void remove (String);
public void remove (int);
public void removeAll ();
CHECKBOX:
Checkbox is basically used for maintaining checklist purpose checkbox is an
interactive component which contains a square symbol and a label.
Creating a checkbox is nothing but creating an object of checkbox class
Checkbox API:
Constructors:
checkbox ();
checkbox (String);
checkbox (String, boolean);
Instance methods:
public void setLabel (String);
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 132
public String getLabel ();
public void setState (boolean);
public boolean getState ();
public void addItemListener (ItemListener);
public void removeItemListener (ItemListener);
RADIO BUTTONS:
In java.awt we are not having a special class for radio buttons but we can create
radio
button from Checkbox class.
In java.awt we have a predefined class called CheckboxGroup through which we
can add all
the checkboxes to the object of CheckboxGroup class.
Steps for converting checkboxes into radio button:
1. Create objects of CheckboxGroup class.
For example:
CheckboxGroup cbg1=new CheckboxGroup ();
CheckboxGroup cbg2=new CheckboxGroup ();
CheckboxGroup object allows to select a single checkbox among ‘n’ number of
checkboxes.
2. Create ‘n’ number of objects of Checkbox class
For example:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 133
public void setCheckboxGroup (CheckboxGroup);
For example:
cb1.setCheckboxGroup (cbg1);
cb2.setCheckboxGroup (cbg2);
4. Register the events of checkbox with ItemListener by using the following method:
public void addItemListener (ItemListener);
NOTE: Instead of using a setCheckboxGroup method we can also used the following
Constructor which is present in Checkbox class.
LIST:
List is the GUI interactive component which allows to select either single or
multiple items at a time.
Creating List component is nothing but creating an object of List class.
List API:
Constructors:
List ();
List (int size);
List (int size, boolean mode);
Instance methods:
public void setSize (int size);
public int getSize ();
public void add (String);
public void addItem (String);
public void add (int, String);
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 135
Whenever we want to develop any windows applications one must deal with event
delegation model.
Event delegation model contains four properties.
They are: In order to process any active components, we must know either name or
caption or label or reference of the component (object).
Whenever we interact any active component, the corresponding active component will
have one predefined Event class, whose object will be created and that object contains
two details:
1. Name of the component.
2. Reference of the component.
The general form of every Event class is xxx event.
For example:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 136
In JAVA purely undefined methods are abstract methods present in interfaces.
Interfaces in awt are called listeners. Hence, every interactive component must have a
predefined listener whose general notation is xxx listener
For example:
SWINGS java.awt.event.ItemListener
TextField java.awt.event.TextListener
TextArea java.awt.event.TextListener
Scrollbar
java.awt.event.AdjustmentListener
INTRODUCTION
In the earlier days SUN micro system; we have a concept called awt.
AWTis used for creating GUI components.
All AWT components are written in ‘C’ language and those components appearance is
changing from one operating system to another operating system. Since, ‘C’ language is
the platform dependent language.
In later stages SUN micro system has developed a concept called swings.
Swings are used for developing GUI components and all swing components are developed
in java language.
Swing components never change their appearance from one operating system to another
operating system. Since, they have developed in platform independent language.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 137
AWT SWING
1. awt components are developed in ‘C’ 1. Swing components are developed in java
language. language.
2. All awt components are platform 2. All swing components are platform
dependent. independent.
3. All awt components are heavy weight 3. All swing components are light weight
components, since whose processing time components, since its processing time and
and main memory space is more. main memory space is less.
FOR EXAMPLE:
JButton JB=new JButton (“ok”);
All components of swings are treated as classes and they are belongs to a package
called javax.swing.*
In swings, we have two types of components. They are
auxiliary components and
logical components.
Auxiliary components are those which we can touch and feel. For example, mouse,
keyboard, etc.
Logical components are those which we can feel only.
Logical components are divided into two types. They are
passive or inactive components and
active or interactive components.]
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 138
HIERARCHY CHART IN SWINGS:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 139
INPUT AND OUTPUT
FILES
It is defined as the collection of records. Further the records are classified as a
collection of fields.
We can store and manage files which creates file, updates file. We can perform both
reading and writing operation on files.
The process of reading and writing objects are called as Object Serialization Java.io
package includes a class called File Class which provides support for creating files
and directories. It includes several constructors for instantiating the file objects.
Creation of Files:
A file name is a unique string of characters that helps identify a file on disk.
It consists of two parts:
(a) Primary Part:
(b) Extension Part
Ex:
Test.dat unit.doc stud.txt
File Initialization:
It can be done in two ways.
(a) Direct Method
(b) Indirect Method
(1) Direct Method:
Here we explicitly specify the name of the file.
Ex:
FileInputStream fis; //defining a file stream object
try
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 140
fis=new FileInputStream(“test.dat”)
………
}
Catch (IOException e)
……
(2) Indirect Method:
Here we can implicitly specify the file
Ex:
…..
File infile;
infile = new File(“test.dat”);
FileInputStream fis;
try
{
fis = new FileInputStream(infile);
…….
}
Catch( ….)
ByteStream Class:
It creates and manipulates streams and files for reading and writing bytes.It is
unidirectional in nature, that means it transmit the byte in only one direction.
1. InputStream:
It reads 8 bit bytes including a superclassIt includes a number of subclasses
for supporting various related functions.
It is an abstract class.No instance of the class is created.
Functions:
Reading bytes
Closing streams
Marking positions
Skipping ahead
Finding number of bytes
2. OutputStream:
It is derived from the base class output stream.
It is also an abstract class.
Functions:
Writing bytes
Closing streams
Flushing streams
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 143
EXAMPLE PROGRAM
import java.io.*;
class rwb
{
public static void main(String args[])
{
FileInputStream infile=null;
int b;
try
{
infile=new FileInputStream("in.Doc");
while((b=infile.read())!=-1)
{
System.out.print((char)b);
}
infile.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OTHER STREAMS:
1. Object Streams:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 144
We can perform input–output operations on objects.
The object streams are created using ObjectInputStream and
ObjectOutputStream
This process is called as object serialization
2. Piped Streams:
They provide the functionality for the threads to communicate and exchange the data
between them.
The objects used are PipedInputStream and PipedOutputStream.
3. Pushback Streams:
It is used to push a single byte or character back into the input stream so that it
can be reread.
This is used with parsers.
4. Filtered Streams:
It provides two abstract classes FilterInputStream and FilterOutputStream, which
create i/o streams for filtering io operations.
They are called as filters.
CREATING THREADS
----
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 146
}
The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method
called start( ).
1. By creating a thread class : Define a class that extends thread class and override its
run( ) method with the code required by the thread.
The approach to be used depends on what the class we are creating requires.
If it requires to extend another class, then we have no choice but to implement the
Runnable interface, since Java classes cannot have two superclasses.
We can make our class Runnable as a thread by extending the class java.lang.Thread.
This gives us access to all the thread methods directly. It includes the following steps:
2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 147
class MyThread extends Thread
{
……..
……..
}
Now we have a new type of thread MyThread.
To actually create and run on instance of the thread class, we must write the following
The second line calls the start( ) method causing the thread to move into the runnable
state.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 148
Then the Java runtime will schedule the thread to run by invoking its run( ) method.
Now, the thread is said to be in the running state.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 149
public static void main(String[] args)
{
new A( ).start( );
new B( ).start( );
}
}
Output
From thread A:i=1
From thread A:i=2
From thread B:i=1
From thread B:i=2
From thread A:i=3
Exit from A
From thread B:i=3
Exit from B
The main thread dies at the end of its main method. However, before it dies, it creates
and starts all the two threads A and B. Note that the output from the threads are not
specially sequential.
Stopping A thread
Whenever we want to stop a thread from running further, we may do so by calling its
stop( ) method, like:
AThread.stop( );
This statement causes the thread to move to the dead state. The stop( ) method may be
used when the premature death of a thread is desired.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 150
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either of the following thread methods:
The thread will return to the runnable state when the specified time is elapsed in the
case of sleep( ), the resume( ) method is invoked in the case of suspend( ) and the
notify( ) method is called in the case of wait( ).
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 151
STATE TRANSITION DIAGRAM OF A THREAD
NEWBORN STATE
When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the
following things with it:
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 152
SCHEDULING A NEW BORN THREAD
RUNNABLE STATE
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
If all threads have equal priority, then they are given time slots for execution in round
robin fashion, i.e., first-come, first-serve manner.
This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread of equal priority
before its turn comes, we can do so by using the yield( ) method.
RUNNING STATE
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquish control on its own or it is preempted by a higher
priority thread.
A running thread may relinquish its control in one of the following situations.
1 .It has been suspended using suspend( ) method. A suspended thread can be revived by
using the resume( ) method. This approach is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 153
Relinquishing control using suspend( ) method
2.
It
has been made to sleep. We can put a thread to sleep for a specified time period using the
method sleep( time) where time is in milliseconds. This means that the thread is out of queue
during this time period. The thread re-enters the runnable state as soon as this time period is
elapsed.
3.It has been told to wait until some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.
BLOCKED STATE
The thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy
certain requirements. A blocked thread is considered “ not runnable” but not dead and
therefore qualified to run again.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 154
DEAD STATE
Every thread has a life cycle.
A running thread ends its life when it has completed executing its run( ) method.
It is a natural death. However, we can kill it by sending the stop message to it at any
state thus causing premature death to it.
A thread can be killed as soon as it is born, or while it is running, or even when it is in
“ not runnable “ condition.
Example
class A extends Thread
{
public void run( )
{
for(int i=1; i< 3;i++)
{
if (i == 1 ) yield( );
System.out.println(“\n From thread A:I=”+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1 ;j<=5;j++)
{
System.out.println(“\n From thread B:j=”+j);
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 155
if (j==3 )
stop( );
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1; k<=3;k++)
{
System.out.println(“\t From thread c:k=”+k);
if (k === 1 )
try
{
sleep(1000);
}
catch( Exception e)
{
}
}
System.out.println(“Exit from C”);
}
}
class ThreadMethods
{
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 156
public static void main(String[] args)
{
A threadA =new threadA( );
B threadB =new threadB( );
C threadC =new threadC( );
System.out.println(“Start thread A”);
ThreadA.start( );
System.out.println(“Start thread B”);
ThreadB.start( );
System.out.println(“Start thread C”);
ThreadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
From Thread B:j=1
From Thread B:j=2
From Thread A:i=1
From Thread A:i=2
End of main thread
From Thread C:k=1
From Thread B:j=3
From Thread A:i=3
Exit from A
From Thread C:k=2
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 157
From Thread C:k=3
Exit from C
THREAD EXCEPTIONS
Note that the call to sleep( ) method is enclosed in a try block and followed by a catch
block. This is necessary because the sleep( ) method throws an exception, which
should be caught.
If we fail to catch the exception, program will not compile.
Java run system will throw IllegalThreadStateException whenever we attempt to
invoke a method that a thread cannot handle in the given state.
For example, a sleeping thread cannot deal with the resume( ) method because a
sleeping thread cannot receive any instructions. The same is true with the suspend( )
method when it is used on a blocked ( not runnable ) thread.
Whenever we call a thread method that is likely to throw an exception, we have to
supply an appropriate exception handler to catch it.
THREAD PRIORITY
In Java, each thread is assigned a priority, which affects the order in which it is
scheduled for running.
The threads of the same priority are given equal treatment by the Java scheduler and,
therefore they share the processor on a first-come,first-serve basis. Java permits us to
set the priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority( int number );
The number is an integer value to which the thread’s priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY = 10
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 158
The number may assume one of these constants or any value between 1 and 10. Note
that the default setting is NORM_PRIORITY.
By assigning priorities to threads, we can ensure that they are given the attention they
deserve. Whenever multiple threads are ready for execution, the Java system chooses
the highest priority thread and execute it.
Remember that the highest priority thread always preempts any lower priority threads.
Example
class A extends Thread
{
public void run( )
{
System.out.println(“Thread` A Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread A:i=”+i);
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
System.out.println(“Thread B Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread B:j=”+j);
System.out.println(“Exit from B”);
}
}
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 159
class C extends Thread
{
public void run( )
{
System.out.println(“Thread C Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread C:i=”+i);
System.out.println(“Exit from C”);
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
threadC.setPriority( Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority( )+1);
threadC.setPriority( Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 160
}
}
Output
Start thread A
Start thread B
Start thread C
Thread B Started
From thread B:j=1
From thread B:j=2
Thread C Started
From thread C:k=1
From thread C:k=2
From thread C:k=3
Exit from C
End of main thread
From thread B:j=3
Exit from B
Thread A Started
From thread A:i=1
From thread A:i=2
From thread A:i=3
Exit from A
SYNCHRONIZATION
In the above examples, we have seen threads that use their own data and methods
provided inside their run( ) method.
What happens when they try to use data and methods outside themselves. On such
occasions, they may compete for the same resources and may lead to serious problems.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 161
For example, one thread may try to send a record from a file while another is still
writing to the same file.
Depending on the situation, we may get strange results. Java enables us to overcome
this problem using a technique known as synchronization.
In case of Java, the keyword synchronized helps to solve such problems by keeping a
watch an such locations. For example, the method that will read information from a file
and the method that will update the same file may be declared as synchronized.
Example
synchronized void update( )
{
---- // code here is synchronized
----
}
When we declare a method synchronized, Java creates a “monitor” and hands it over to
the thread that calls the method first time.
As long as the thread holds the monitor, no other thread can enter the synchronized
section of code.
A monitor is like a key and the thread that holds the key can only open the lock.
It is also possible to mark a block of code as synchronized as shown below:
synchronized ( lock-object )
{
---- // code here is synchronized
----
}
Whenever a thread has completed its work by using synchronized method, it will hand
over the monitor to the next thread that is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain
control of a resource.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 162
Due to some reason, the condition on which the waiting threads rely on gain control
does not happen.
This result in what is known as deadlock. For example, assume that the thread A must
access method1 before it can release method2, but the threadB cannot release method1
until it gets hold on method2.
Because these are mutually exclusive conditions, a deadlock occurs. The code below
illustrate this:
ThreadA
synchronized method2( )
{
synchronized method1( )
{
}
}
ThreadB
synchronized method1( )
{
synchronized method2( )
{
}
}
IMPLEMENTING THE RUNNABLE INTERFACE
To create thread using the Runnable interface, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable” class as
the target of the thread.
4. Call the thread’s start( ) method to run the thread.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 163
If the direct reference to the thread threadX is not required, then we may use a shortcut
as shown below:
new Thread( new X( ) ).start( );
Example
class X implements Runnable
{
public void run( )
{
for(int i=1;i<3;i++)
System.out.println(“\t ThreadX:”+ i);
System.out.println(“End of thread X”);
}
}
class RunnableTest
{
public static void main(String[] args)
{
X runnable = new X( );
Thread threadX = new Thread( runnable );
threadX.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main Thread
ThreadX:1
ThreadX:2
End of ThreadX
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 164
NETWORKING BASICS
1. A client side programming is one which always makes a request to get the service
from the server side program.
2. A server side programming is one which receives client request, process the request
and gives response back to the client.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 165
In order to exchange the data between the client and server we must have a protocol. A
protocol is the set of rules which exchange the data between client and server
programs.
When we are developing any client and server application we must follow certain steps
at client client side and server side.
1. Connect to the server side program. To connect to the server the client side program must
3. After performing some operations at server side, the client side program must receive the
response from the server side.
1. Every server side program must run at certain port number (a port number is a logical
numerical ID at which logical execution of the program is taking place)
2. Every server must have a physical name to access the services or programs which are
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 166
on IP address (127.0.0.1 default)
4. Every server side program must read request data (request parameter).
Socket: In order to develop the program at client side we must use the class Socket.
Socket API:
Constructor:
Instance methods:
DISADVANTAGES OF NETWORKING:
2. We are able to get only language dependency (client side and server side we
must write only
java programs).
5. We are able to develop only intranet applications but not internet applications.
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 168
QUESTION BANK
UNIT 5
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 169
13) what are the steps for create applet ? 5 MARK
14) how to accessing interface variable?5 MARK
15) Explain the exception types with an example?10 MARK
AVS & SAKTHI KAILASH GROUP OF INSTITUTIONS DEPARTMENT : BCA Page 170