JAVA
JAVA
STUDY MATERIAL
3
PREFACE
Dear Students,
Introduction to Java is a powerful programming language which
with the advent of World Wide Web and a massive software package, being used
by various types of trade & industry. To take advantage of the full potential of
Java the user has to understand its features, their implications and how to
implement them in a World Wide Web scenario.
This E-Book has been designed especially keeping in mind the
learners and we have tried our-best to make this E-Book simple as possible, to make
it easy for the learner and also elaborate the point to be handful for anyone using
the computer.
If this E-Book helps anyone to learn and to use the computer
effectively, it will be of great success.
Introduction to Java
ABOUT JAVA
Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects on
Internet as easily as they can do in a local system. This enables multiple programmers at multiple
remote locations to collaborate and work together on a single project.
Java Environment
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
The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs. They include:
Appletviewer (for viewing Java applets)
Javac (Java compiler)
Java (Java interpreter)
Javap (Java disassembler)
Javah (for C header files)
Javadoc (for creating HTML documents)
Jdb (Java debugger)
To create a Java program, we need to create a source code file using a text editor. The source code is
then compiled using the Java compiler javac and executed using the Java interpreter java. The Java
debugger jdb is used to find errors, if any, in the source code. A compiled Java program can be
converted into a source code with the help of Java disassembler javap.
class hellojava
{
public static void main (String args [])
{
System.out.println (―Hello World‖);
}
}
Save file as hellojava.java
Compile by typing javac hellojava.java on the command line.
On successful compilation execute the program by typing java hellojava, on the
command line.
The program will display Hello World on the screen.
Every java application program has a main() method. It is the first function run when the program is
executed. The void keyword preceding main() indicates that it does not return any values. public
indicates that the method is global, static denotes that main() is a class method and can be called
without creating an object.
Byte code
Fig.1
The virtual machine code is not machine specific. The machine specific code (known as machine
code) is generated by the Java interpreter by acting as an intermediary between the virtual
machine and the real machine as shown in Fig.2.Remember that the interpreter is different for
different machines.
Real Machine
Operating System
Java Virtual Machine
Java Object Framework (API)
Compiler Interpreter
User Application Programs
User
Keywords
Keywords are essential part of a language definition. They implement specific features of
the language. Java language has reserved 60 words as keywords.
CONSTANTS:
Constants in Java refer to fixed values that do not change during the execution of a program. Java
supports several types of constants.
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus sign.
Valid examples of decimal integer constants are:
345 -768 0 45676
embedded spaces, commas, and non-digit characters are not permitted between digits. For example,
12 456 23,786 $2900
are illegal numbers.
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading 0.Some examples of octal integer are:
045 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They
may also include alphabets. A through F or a through f.A letter A through F represents the
numbers 10 through 15.Following are the examples of valid hex integers.
0X2 0X9F 0xbcd 0x
Real Constants
Numbers containing fractional parts are called real (or floating point) constants. Examples of real
constants are:
0.0067 -0.45 345.78 -.89
Single Character Constants
A single character constant contains a single character enclosed within a pair of single quote marks.
Examples of character constants are:
‗5‘ ‗X‘ ‗;‘ ‗‗
String Constants
A string constant is a sequence of characters enclosed between double quotes. Examples are:
―Hello World‖ ―3456‖ ―?…..!‖ ―5+3‖ ―X‖
DECLARATION OF VARIABLES
The declaration of variable tells the compiler what the variable name is. It specifies what type of data
the variable will hold. The place of declaration (in the program) decides the scope of the variable. A
variable must be declared before it is used in the program. The general form of declaration of a
variable is:
Type variable1, variable2, variableN;
Some valid declarations are:
int count;
float x, y;
char c1, c2, c3;
.INITIALIZATION OF VARIABLES
The process of giving initial values to variables is known as the initialization. The ones that are not
initialized are automatically set to zero.
The following are valid Java statements:
float x, y, z; //declares three float variables
int m=8, n=45; //declares and initializes two int variables
DATA TYPES
Data types specify the size and type of values that can be stored.
Primitive (Intrinsic)
Non-Primitive (Derived)
Non-numeric
Numeric Classes Arrays
Character
Boolean Interface
Integer
Floating-point
Integer Types:
Integer types can hold whole numbers such as 123,-96 and 5639.We can make integers long
by appending the letter L or l at the end of the number. Example: 123L or 123l
Integer
Byte
Short
Long
Int
Integer data types
Floating Point
Float Double
Type Size
Float 4 bytes
Double 8 bytes
CHARACTER TYPE:
In order to store character constants in memory, java provides a character data type called char. The
char type assumes a size of 2 bytes but, basically, it can hold only a single character. BOOLEAN
TYPE:
There are only two values that a Boolean type can take: true or false. Both these words have
been declared as keywords. Boolean type is denoted by the keyword Boolean.
Relational
Operator Meaning Value
expression
Is less
< 4.5<-10 FALSE
than
Is less
<= than or 4.5<=10 TRUE
equal to
Is
> greater 6>3 TRUE
than
Is
greater
>= -35>=0 FALSE
than or
equal to
Is equal
== 4+5==5+4 TRUE
to
Is not
!= 45!=9 TRUE
equal to
LOGICAL OPERATORS
Java has three logical operators.
Operator Meaning
&& Logical
AND
|| Logical
OR
! Logical
NOT
ASSIGNMENT OPERATORS
Assignment operators are used to assign the value of an expression to a variable.
Decision Constructs:
SIMPLE IF STATEMENT:
The ‗statement-block‘ may be a single statement or a group of statements. If the test expression
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
It should be remembered that when the condition is true both the statement-block and
the statement-x are executed in sequence
This is illustrated in fig.
Entry
True
test
expression
?
Statement-Block
False
Statement-x
Next statement
If the test expression is true, then the true-block statement (s) immediately following the if statement,
are executed; otherwise, the false-block statement(s) are executed. In either case, either
true –block or false-block will be executed, not both. This is illustrated in fig. In both the cases, the
control is transferred subsequently to the statement-x.
Entry
True-block False-block
statements statements
Statement-x
class ContinueBreak
{
public static void main(String args[])
{
LOOP1 : for (int i=1;i<100;i++)
{
System.out.println (― ―);
If ( i >= 10) break;
for(int j=1;j<100;j++)
{
System.out.print(― * ―);
If (j == i)
Continue LOOP1;
}
}
System.out.println (―Termination by BREAK‖);
}
}
While Loop
A while loop keeps executing the statement in its body (which may be a compound statement, with a
number of single statements inside curly braces) while a particular logical condition evaluates to true.
Here‘s what a while loop looks like in general:
while (condition)
statement
Note that if condition is not true, the body of the loop is not even executed once.
public class check6
{
public static void main (String args[])
{
int xyz = 10;
while (xyz > 0)
{
System.out.println (―Value = ―, xyz - -);
}
}
}
do-while loop
The do-while loop is just like a while loop, except that the test condition is evaluated at the end of
the loop, not at the beginning. Here‘s what the do-while loop looks like (bear in mind that the
statement can be a compound statement with a number of single statement inside curly braces):
do
statement
while (condition);
for loop
The java for loop is a good choice when you want to use a numeric index that you automatically
increment or decrement each time through the loop, such as when you‘re working with as array.
Here‘s what the for loop looks like in general (note that statement can be a compound statement,
including several single statement inside curly braces:
for (initialization_expression; end_condition; iteration_expression)
{
statement
}
An array is a set of continuous memory locations. Array can hold similar type of data only.
Like any other variables, array must be declared and created in the computer memory before they
are used. Creation of an array involves three steps:
Declare the array
Create memory locations
Put values into the memory locations.
Examples:
Int number[ ];
Float [ ] marks;
After declaring an array, we need to create it in the memory. Java allows us to create arrays using new
operator only, as shown below:
arrayname = new type [size];
Examples:
number = new int[5];
average = new float[10];
It is also possible to combine the two steps—declaration and creation – into one as shown below:
int number [ ] = new int [ 5 ];
Initialization of Arrays
The final step is to put values into array created.This process is known as initialization. This is done
using the array subscripts as shown below:
Arrayname [subscript] = value;
Example:
number [0] = 35;
number [1] = 40;
We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
Type arrayname [ ] = { list of values);
Example:
int number[ ] = { 35,40,20,57,12};
Array Length
In java all arrays store the allocated size in a variable named length.We can access the length of the
array a using a.length.
Example:
int aSize = a.length;
class NumberSorting
{
public static static void main(String args[])
{
int number[] = { 55,40,80,65,71};
int n = number.length;
System.out.print(―Given list : ―);
For (int I = 0; I < n ; i++)
{
System.out.print(― ― + number[i]);
}
System.out.println(―\n‖);
//Sorting begins
for(int i=0; i < n ; i ++)
{
for(int j = i + 1; j < n; j++)
{
if (number[i] < number[j])
{
//Interchange values
int temp = number[ i ];
number[i] = number[j];
number[j] = temp;
}
}
}
System.out.print(―Sorted list: ― );
for(int i=0; i<n; i++)
{
System.out.print(― ― + number[i]);
}
System.out.println(― ―);
}
}
Output:
Given list: 55 40 80 65 71
Sorted list: 80 71 65 55 40
class MulTable
{
final static int ROWS = 20;
final static int COLUMNS = 20;
public static void main(String args[ ])
{
int product [] [] = new int [ROWS] [COLUMNS];
int row, column;
System.out.println(―MULTIPLICATION TABLE‖);
System.out.println(― ―);
int i,j;
for(i = 10; i<ROWS; i++)
{
for(j=10; j<COLUMNS; j++)
{
product [i] [j] = i * j;
System.out.print(― ― + product[i] [j]);
}
System.out.println(― ―);
}
}
}
STRINGS
Strings represent a sequence of characters. The easiest way to represent a sequence of characters in
Java is by using a character array. Example:
char charArray[ ] = new char[4];
charArray[0] = ‗J‘;
charArray[1] = ‗a‘;
charArray[2] = ‗v‘;
charArray[3] = ‗a‘;
In java , strings are class objects and implemented using two classes, namely,String and StringBuffer.
A java string is an instantiated object of the String class.A java string is not a character array and is
not NULL terminated. Strings may be declared and created as follows:
String stringName;
StringName = new String (―string‖);
Example:
String firstName;
FirstName = new String(―Anil‖);
These two statements may be combined as follows:
String firstName = new String(―Anil‖);
There are two ways of creating a String in java. One way is by not using the new operator. Thus
, normally a String is created ,
String s = new String(―hello‖);
But a slightly shorter method can be used
String s = ―GoodBye‖;
Eg.
class abc
{
public static void main(String args[])
{
String pchs1 = ―hello‖;
String prts1 = ―hello‖;
if (pchs1 = = prts1)
{
System.out.println(―String are equals‖);
}
String pchs2 = new String(―hello‖);
String prts2 = new String(―hello‖);
if(pchs2 = = prts2)
{
System.out.println(―String are equals‖);
}
}
}
Chapter-3
Java is a full-fledge OOP language.The structure of Java is such that it enforce designing and
coding of application in an object oriented way .To developed a programe in an object priented way,
the program has to be n the form of a class. A simple example of creating a programe with only one
class is given below.
Class Test
The main method declares a local variable are and a Room type object room1 and
then assign values to the data members of Room class by using the getdata method.Finally,it
calculate the area and print the result.
class Room
float len;
float bre;
len = a;
bre = b;
}
class RoomArea
float area;
System.out.println(―Area =‖+area);
when create file with multiple classes make sure that your file name is same with the class
name that contain the main method.
Import Statement
To make use of classes within different packages, the import statement is use .Once imported,the
classes within the package can be used by the programe.All standard package of Java are
included within a package called java.By default,all programe import the java.lang
3. Classpath Variable
Whenever a class is created without nay package statement,it is implied that the class is included
in Java‘s default package.Incase of writing small programes it is not necessary for the package
name to be mentioned. The necessity for packages can be understood in real time application
environment.
Java compiler and the interpreter searches the class file in the path specifed in
CLASSPATH environmental variable. The current working directory is,by default,included in this
variable.hence is possible to compile and execute the programe from the existing directory.In case of
creating package,insure that the root directory of the package is included in the CLASSPATH variable.
Chapter-4
Exceptions
1. Introduction
An exception is an abnormal condition that arise in a code sequence at runtime.In other
word,an exception ia n run time error.In computer language that does not support exception
heandling,errors must be checked and handle manually-typically through the use os error
code,ans so on.
Class Exc{
Public static void main(String args[])
{
int d,a;
try{
d=0;
a=42/d;
System.out.println(―This will not be printed‖)
}catch(ArithmeticException e)
{
System.out.println(―Division by zero‖);
}
System.out.println(―After catch statement .‖);
}
This programe generate the following output:
Division by zero
After catch statement.
Throw
So far,you have only been catching exception that are thrown by the Jva run time
system.However,it is possible for your programe to throw an exception explicitly,using the
throw statement. The general form of throw is shown here .
Throw ThrowableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass of throwable
.Simple types,such as int or char,as well as non-Throwable classes,such as String and
Object,cannot be used as exception. There are two ways you can obtain a Throwable object:
using a parameter into a catch clause,or creating one with the new operator.
Here is the sample programe that creates and throws an exception.
The handler that catches the exception rethorws it to the outer handler.
Class ThrowDemo{
Static void demoproc(){
Try{
Throw new NullPointerException (―demp‖);
} catch(NullpointerException e){
System.out.println(―Caught inside demoproc.‖);
throw e;
}
}
public static void main(String args[]){
try{
demproc();
}catch(NullpointerException e){
System.out.println(―Recought :‖=e);
}
}
}
Throws
If a method is capable of causing an exception that is does not handle, it must specify
this behavior so that the caller of the method can guard themselves against that
exception. you do this by including a throws clause in that a method‘s declaration . A
throws clause lists the type of exception that a method might throw. This is necessary for
all exception,except those of type Error or RuntimeException ,or nay of their
subclasses.All other exception that a method can throw must be declare in the throws
clause. If they are not, a compile-time error result.
}
Here,exception-list is a comma-separated list of the exceptions that a method can throw.
class ThrowsDemo{
static void throwOne(){
System.out.println(―Inside throwOne ―);
Throw new IllegalAccessException(―demo‖);
}
public static void main(String args[]){
throwOne();
}
}
To make this example compile,you need to make two changes. First,you need to declare
that throwOne() throws IlligalAccessException.second, main() must define a try/catch
statement that catches this exception.
The correct example is shown here
Finally
Finaly create a block of code that will execute after a try/catch block has copplete and before
the code following the try/catch block . the finally block will execute whether or not an exception
is thrown. If an exception is thrown, the finally block will execute even if no catch statement
matches the exception. This can be use for closing file handle and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional. However,each try statement requires at least one
catch or a finally caluse.
Here is an example programe that shows three methods that exit in various ways, none
without executing their finally clause :
// demonstrate finally
class FinallyDemo{
try{
System.out.println(―inside procA‖); Throw
new RuntimeException(―demo‖);
} finally{
System.out.println(― procA‘s finally‖);
}
}
// Return from wirhin a try block‘
try{
System.out.println(―inside procB‖);
Return;
}finally{
System.out.println(―procB‘s finally‖);
}
}
// Execute a try block normally
static void main(String args[])
{
try{
procA()
}catch(Exception e){
System.out.println(―Exception caught‖);
}
procB();
procC();
}
}
Creating User Defined Exception
Example
OutOfRangeException(String str)
super(str);
else
{
System.out.println(―The number ―+ I + ―is in range ―);
}
}
public static void main(String args[])
{
try
{
UExcept ue=new UExcep();
Ue.v1(-300);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Chapter-5
Bird
Attributes:
Feathers
Lay eggs
Flying Nonflying
Bird Bird
Attributes: Attributes:
baseclass :
baseclass is a class from which another class inherits functionality. In Java , a baseclass is often
called a superclass.
derived class:
derived or sub class is a class that inherits from a base class.
abstract class:
abstract class is a class that can not be instantiated directly.Abstract classes exist so that
subclasses can inherit variables and methods from them.
Inheritance:
The mechanism of deriving a new class from an old one is called inheritance.The old class is known
as the base class or super class or parent class and the new one is called the subclass or derived
class or child class.The inheritance allows subclasses to inherit all the variables and methods of
their parent classes.Inheritance may take different forms:
Single inheritance (only one super class)
Multiple inheritance (several super classess)
Hierarchical inheritance(one super class,many subclasses)
Multilevel inheritance(Derived from a derived class)
Java does not directly implement multiple inheritance. However, this concept is implemented using
a secondary inheritance path in the form of interface.
A A B
B C
class Room
{
int length;
int breadth;
Room (int x, int y)
{
length = x;
breadth = y;
}
int area()
{
return (length * breadth);
}
}
class BedRoom extends Room // Inheriting Room
{
int height;
BedRoom(int x, int y, int z)
{
super(x,y); // pass value to superclass
height = z;
}
int volume()
{
return (length * breadth * height);
}
}
class InherTest
{
public static void main(String args[])
{
BedRoom room1 = new BedRoom(14,12,10);
int area1 = room1.area(); //superclass method
int volume1 = room1.volume(); // baseclass method
System.out.println(―Area1 = ― + area1);
System.out.println(―Volume1 = ― + volume1);
}
}
Access specifiers:
Protected: Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
Private: Use private if the field is not to be visible anywhere except in its own class.
Overriding methods:
A method defined in a super class is inherited by its subclass and is used by the objects created by
the subclass.Method inheritance enables us to define and use methods repeatedly in subclasses
without having to define the methods again in subclass.
However,there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called.That means, we should override the method
defined in the superclass.This is possible by defining a method in the subclass that has the same
name, same arguments and same return type as a method in the superclass.Then , when that method
is called , the method defined in the subclass is invoked and executed instead of the one in the
superclass.This is known as overriding.The following program illustrates the concept of
overriding.The method display() is overridden.
Illustration of method overriding
class Super
{
int x;
Super(int x)
{
this.x = x;
}
void display() // method defined
{
System.out.println(―Super x = ― + x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
Super(x);
this.y = y;
}
void display() //method defined again
{
System.out.println(―Super x = ‖ + x);
System.out.println(―Sub y = ― + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1 = new Sub(100,200);
s1.display();
}
}
Output:
Super x =100
Sub y = 200
Abstract methods and classes
By making a method final we ensure that the method is not redefined in a subclass.That is, the
method can never be subclassed.Java allows us to do something that is exactly opposite to this.That
is, we can indicate that a method must always be redefined in a subclass,thus making overriding
compulsory.This is done using the modifier keyword abstract in the method definition.Example:
abstract class Shape
{
……………
……………
abstract void draw();
……………
……………
}
When a class contains one or more abstract methods, it should also be declared abstract as shown in
the example above.
While using abstract classes, we must satisfy the following conditions:
We cannot use abstract classes to instantiate objects directly. For example,
Interfaces
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but
with a major difference.The difference is that interfaces define only abstract methods and final
fields.This means that interfaces do not specify any code to implement these methods and data fields
contain only constants.Therefore, it is the responsibility of the class that implements an interface to
define the code for implementation of these methods.
The syntax for defining an interface is very similar to that for defining a class . The general
form of an interface definition is:
interface InterfaceName
{
variables declaration;
methods declaration;
}
Here, interface is the keyword and InterfaceName is any valid Java variable (just like class names).
Variables are declared as follows:
void display();
}
Note that the code for the method is not included in the interface and the method declaration simply
ends with a semicolon.The class that implements this interface must define the code for the method.
Implementing Interfaces:
Interfaces are used as ―superclasses‖ whose properties are inherited by classes. It is therefore
necessary to create a class that inherites the given interface.This is done as follows:
class classname implements Interfacename
{
body of classname
}
Here the class classname ―implements‖ the interface interfacename.A more general form of
implementation may look like this:
Class classname extends superclass implements interface1,interface2,………..
{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
//InterfaceTest.java
interface Area //Interface defined
{
final static float pi = 3.14F;
float compute(float x, float y);
}
class Rectangle implements Area //Interface implemented
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Area //Another implementation
{
public float compute(float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area; //Interface object area = rect;
System.out.println(―Area of Rectangle = ― +
area.compute(10,20)); area = cir;
System.out.println(―Area of Circle = ― + area.compute(10,0));
}
}
Output:
Area of Rectangle = 200
Area of Circle = 314
Java does not support multiple inheritance.But in Java this concept can be implemented using
interfaces.
Output:
Roll No: 1234
Marks obtained
Part1 = 27.5
Part2 = 33
Sports Wt = 6
Total score = 66.5
Chapter: 6
Threads
A thread is similar to a program that has a single flow of control. It has a beginning, a body and an
end and executes commands sequentially.A thread is a single line of execution within a program. A
thread is created either by subclassing the Thread class or implementing the Runnable interface.
During the life of a thread, there are many states it can enter. They include:
Newborn state
Runnable state
Running state
Blocked state
Dead state
A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in fig.
start
stop
Active stop
Killed
Thread Dead Thread
Running Runnable
yield
Resume notify
stop
Suspend sleep wait
Idle Thread
(Not Runnable) Blocked
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:
Schedule it for running using start() method.
Kill it using stop() method.
If scheduled, it moves to the runnable state. If we attempt to use any other method at this stage,
an exception will be thrown.
Newborn
stop
start
Dead state
Runnable state
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.The thread that relinquishes control joins the queue at the end
and again waits for its turn.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.
yield
Running means that the processor has its time to the thread for its execution. The thread runs until
it relinquishes 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.
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.
suspend
resume
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
the queue during this time period.The thread re-enters the runnable state as soon as this
time period is elapsed.
sleep (t)
after t
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.
wait
notify
A 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 fully qualified to run again.
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 a premature death to it. A thread can be killed as soon it is born, or while it is running,
or even when it is in ―not runnable‖ (blocked) condition.
Creating Threads
File are the primary source and destinition for data withinmany programs. Although there a
primary source and destination for data within many programes. Although there are servere
restrictions on their use wirhin applets for security reasons. A directory in java is treated simply a File
with one additional property – a list of filename that can be examinited by the list() method.
Here, directoryPath is path name of the file. Filename is the name of the file ,dirObj is a File object
that specifies a directory, and uriObj is an URL object that describes a file .
CONCEPT OF STREAM
In file processing, input refers to the flow of data into a program and output means the flow of data
out of a programe. Input to a programe may come from the keyboard, the mouse,the memory, the
disk, a netwiork, or another programe. Similarly, output from a programmer may go to the screen,
the printer, the memory, the disk , the network, or another programe.
Java uses the concept of streams to represent the ordered sequence of data, a
common characteristic shared by all the input/output devices as stated above. A stream represents a
uniform,easy-to-use,object-oriented interface between the programe and the input/output devices.
Java stream are classified into two basic types, namely, input stream and output Stream .An
input stream extracts data from the source9file) and sends it to the programe.Similiarly, an output
stram takes data from the programe and sends(writes). ti the destination (file).
STREAM CLASSES
The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data . these classes may be categorized into two groups based on the data on
which they operate.
1. Byte stream classes that provide support for handling I/O operation on bytes.
2. Character stream classes that provide support for managing I/O operation on characters.
1. Reading bytes
2. Closing streams
3. Marking positions in streams
4. Skipping ahead in stream
5. Finding the number of bytes in stream
The OutputStream includes methods that are designed to perform the following tasks
1. Write Bytes
2. Closing stream
3. Flushing stream
READING/WRITING CHARACTER
As pointed earler, subclasses of Reader and Writer implement stream that can handle
character. The two subclasses used for handling character in the file are FileReader (for
reading character) and FileWrite (for writing character). The following programe uses these
two file stream classes to copy the contents of a file named ―input.dat‖ into a file called
―output.dat‖
In the earler programe we have used FileReader and FileWriter classes to read and
write 16-bit characters . However , most file system use only 8-bit bytes. As pointed out earler, Java
I/O system provides a number of classes that can handle 8-bit bytes. Two commonly used classes for
handling bytes are FileInputStream and FileOutputStream calasses . We can use them in place if
FileReader and FileWriter.
The following programe demonstrates how FileOutputStream class is used for writing bytes to a file.
The programe writes the name of some cities stored in abyte array to a new file named ―city.txt‖.
// Write buyes to a programe
import java.io.*;
calss WriteBytes
{
public static vopd main( String args[])
{
//Declare and initialize a byte array
byte cities[] = { ‗D‘,‘E‘,‘L‘,‘H‘,‘I‘,‘\n‘,‘M‘,‘A‘,‘D‘,
‘R‘,‘A‘,‘S‘,‘\n‘,‘L‘,‘O‘,‘N‘,D‘,‘O‘,‘N‘,‘\n‘};
// Create an output file stream
FileOutputStream outfile = null;
Try
{
//Connect the outfile stream to ―city.txt
―
CHAPTER-8
Applets
Applets are small Java programs that are primarily used in Internet computing. They can be
transported over the Internet from one computer to another and run using the Applet Viewer or any
Web browser that supports Java.An applet is intended not to be run on its own, but rather to be
embedded inside another application. Like any application program, applet can perform arithmetic
operations, display graphics, play sounds, accept user input, create animation and play interactive
games. A web page can now contain not only a simple text or a static image but also a Java applet
which, when run, can produce graphics, sounds and moving images.
For writing the Internet based applications we need Applet, which can be embedded on net.
Compiling an applet is exactly the same as compiling an application.By compiling the source
code of the applet we get the .class file of the applet.
Let us consider the HelloJava applet. This applet has been stored in a file called
HelloJava.java.Here are the steps required for compiling the HelloJava applet.
Move to the directory containing the source code and type the following command:
javac HelloJava.java
The compiled output file called HelloJava.class is placed in the same directory as the If any
error message is received, then we must check for errors, correct them and compile the
applet again.
Before we try to write applets, we must make sure that Java is installed properly and also ensure that
either the Java appletviewer or Java-enabled browser is available.The steps involved in developing
and testing an applet are:
Building an applet code(.java file)
Creating an executable applet(.class file)
Designing a web page using HTML tags.
Preparing <APPLET> tag.
Incorporating <APPLET> tag into the web page
Creating HTML file
Testing the applet code
The appletviewer is available as a part of the Java Development Kit that we have been using so far.We
can use it to run our applet as follows:
appletviewer HelloJava.html
Notice that the argument of the appletviewer is not the .java file or the .class file, but rather .html
file.
Every java applet inherits a set of default behaviours from the applet class. As a result, when an
applet is loaded , it undergoes a series of changes in its state as shown in fig . The applet states
include:
Born or initialization state
Running state
Idle state
Dead or destroyed state
start()
stop()
Idle Stopped
Running
start()
Display
paint ()
destroy ()
End
Destroyed Dead
Exit of Browser
An applet‘s state transition diagram
Initialization State
Applet enters the initioalization state when it is first loaded.This is achieved by calling the init()
method of Applet Class.The applet is born.At this stage, we may do the following , if required.
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
The initialization occurs only once in the applet‘s life cycle. To provide any of the
behaviours mentioned above, we must override the init() method:
Running State
Applet enters the running state when the system calls the start() method of Applet class.This occurs
automatically after the applet is initialized.Starting can also occur if the applet is already in ―stopped‖
(idle) state. For example, we may leave the web page containing the applet temporarily to another page
and return back to the page.This again starts the applet running. Note that, unlike init() method
, the start() method may be called more than once.We may override the start() method to create a
thread to control the applet.
An applet becomes idle when it is stopped from running. Stopping occurs automatically when we
leave the page containing the currently running applet.We can also do so by calling the stop()
Method explicitly. If we use a thread to run the applet , then we must use stop() method to
terminate the thread.We can achieve by overriding the stop() method:
public void stop()
{
……………….
………………..(Action)
……………….
}
Dead State
An applet is said to be dead when it is removed from memory.This occurs automatically by invoking
the destroy() method when we quit the browser.Like initialization, destroying stage occurs only once
in the applet‘s life cycle.If the applet has created any resources, like threads, we may override the
destroy() method to clean up these resources.
Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen.This happens immediately after the applet enters into the running state. The paint() method is
called to accomplish the task.Almost every applet will have a paint() method.Like other methods in
the life cycle, the default version of paint() method does absolutely nothing. We must therefore
override this method if we want anything to be displayed on the screen.
Applet HelloJavaParam
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{
String str;
public void init()
{
str = getParameter(―string‖); // Receiving parameter
value if (str == null)
str = ―Java‖;
str = ―Hello‖ + str; //Using the value
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<! Parameterized HTML file>
<HEAD>
<TITLE>Welcome to Java Applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE = HelloJavaParam.class
WIDTH = 400
HEIGHT = 200>
<PARAM NAME = ―string‖
VALUE = ―Applet ! ―>
</APPLET>
</BODY>
</HTML>
Save the file as HelloJavaParam.html and then run the applet using the appletviewer as follows:
appletviewer HelloJavaParam.html
CHAPTER-9
AWT Components
ABSTRACT WINDOW TOOLKIT (AWT)
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT
feature include:
A rich set of user interface components i.e. (Button, TextArea, ScrollBar etc);
A robust event-handling model;
Graphics and imaging tools, including shape, color and font classes;
Button Class
This class creates a labeled button. The application can cause some action to happen when
the button is pushed.
If an application wants to perform some action based on a button being pressed and released,
it should implement ActionListener and register the new listener to receive events from this button,
by calling the button‘s addActionListener method. The application can make use of the button‘s
action command as a messaging protocol.
Label Class
A Label object is a component for placing text in a container. A label displayes a single line of read-
only text. The text can be changed by the application, but a user cannot edit it directly.
A TextField object is a text component that allows for the editing of a single line of text.
For example, the following image depicts a frame with four text fields of varying widths. Two
of these text fields display the predefined text ―Hello‖.
I I tf2
tf1
tf3 Hello
tf4 Hello
Applet started
Checkbox Class
A check box is a graphical component that can be in either an ―on‖ (true) or ―off‖ (false) state.
Clicking on a check box changes its state from ―on‖ to ―off‖ or from ―off‖ to ―on‖.
The following code example creates a set of check boxes in a grid layout:
setLayout(new GridLayout(3,1));
add(new Checkbox(―one‖,null,true));
add(new Checkbox(―two‖));
add(new Checkbox(―three‖));
Choice Class
The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of
the menu.
The following code example produces a pop-up menu:
Choice ColorChooser = new Choice();
ColorChooser.add(―Green‖);
ColorChooser.add(―Red‖);
ColorChooser.add(―Blue‖);
List Class
The List component presents the user with a scrolling list of text items. The list can be set up so that
the user can choose either one item or multiple items.
Events :
In the delegation model, an event is an object that describes a state change in a
source.It can be generated as a consequence of a person interacting with the elements in a graphical
user interface. Some of the activities that cause events to the generated are passing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Frame
Frame encapsulates what is commonly though of as a ―window‖. It is subclass of Window an
has a title bar, menu bar, border, and resizing corner. If you create a Frame object within an applet, it
will obtain a warning message, such as ― Java Applet Window‖ to the user that an applet window has
been created. This message warns trhat the window they see was created by an applet and not by
software running on their computer. When a Frame window is created by a programe rather than an
applet , a normal window is created.
Frame()
Frame(String title)
The first form create a standard window that does not contain a title. The second form create
a window with the title specified by title . Notice that you can not specify the dimentions of the
window. Instead, you must set the size of the window after it has been created
While it is possible to simply create a window by creating an instance of b Frame, you will
seldom do so, because you will not able to to much it. For example, you will not be able to receive or
process events that occur within it or easily output information to it. Most of the time, you will create
a subclass of Frame . Doing so let‘s you override Frame‘s methods and event handling.
Several classes provide menu functionality in the AWT. These classes do not inherit from
Component,since many platforms place serve limits on menu capabilities.Instead, menu classes
inherit from the MenuComponent class. The AWT provides the folloeing MenuComponent subclasses
to support menus :
1. MenuItem: Each item in a menu is represented by a MenuItem object
2. CheckboxMenuItem: Each menu item that contain a checkbox is represented by a
CheckboxMeniItem object. CheckboxMenuItem is a subclass of Menutem.
3. Menu : Each menu is represented by a Menu object.Menu is implemented as a subclass of
MenuItem so that you can easily create a submenu by adding one to another.
4. MenuBar: Menu bars are implemented by the MenuBar class. A MenuBar represents the
platform-dependent notion of a group of menus attached to a window.
Chapter-12
Layouts
Layout Manager
The layout manager classes are a set of classes that implement the
java.awt.LayoutManager interface and help to position the component in a container. The
interface takes the task of laying out the child component in the container.This task is achieved
by resizing and moving the child container. This task is achieved by resizing and moving the child
components. The advantage of this type of machanism is that when the container is resize the
layout manager automatically update the interface.
1. FlowLayout
2. BorderLayout
3. Gridyout
4. CardLayout
FlowLayout
A flow layout arrange components in the left-to-right flow,much like lines of text in
a paragraph.Flow layout are typically used to arrange buttons in a panel.It will arrange buttons left
to right until no more buttons fit on the same line. Each line is centered.
For example, the following programe shows an applet using the flow layout manager
to position three buttons:
Import java.awt.*;
Import java.applet.Applet;
Public calss myButtons extends Applet{
Button button1,button2,button3;
Public void init(){
button1=new Button(―ok‖);
button2=new Button(―Open‖);
button3=new Botton(―close‖);
add(button1);
add(button2);
add(button3);
}
}
A flow layout lets each component assume its natural size;
GridLayout
The GridLayout class is a layout manager that lays out a container‘s components in a
rectangular grid. The container is divided into equal-sized rectangles, and one component is
placed in each rectangle
Example
Import java.awt.*;
Import java.applet.*;
Public calss GlayoutEx extends Frame
{
Button b1, b2, b3, b4, b5, b6;
Public GlayoutEx()
{
setLayout(new GridLayout93,5));
b1=new Button(―a1‖);
b2=new Button(―a2‖);
b3=new Button(―a3‖);
b4=new Button(―a4‖);
b5=new Button(―a5‖);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setSize(400,400);
setVisible(true);
}
public static void main(String srgs[])
{
GlayoutEx gex=new GlayoutEx();
}
}
BorderLayout
A border layout lays out a container, arranging and resizing its components to fit in
five regions: north, east, west, and center. Each region is identified by the corresponding
constant: NORTH, SOUTH, WEST, and CENTER. When adding a components to a container with a
border layout, ues one of these five constant.
Swing
Swing component facilitate efficient graphical user interface(GUI) development. These component
are a collection of lightweight visul components. Swing component contain a replacement for the
heavyweight AWT components as well as complex uesr-interface components such as trees and
tables.
The major difference between lightweight and heavyweight componenta is that lightweight
components can have transparent pixel while heavyweight components are always
opaque.Lightweight component can be non rectangular while heavyweight components are always
rectangular.
JPanel
Jpanle is a generic lightweight container.The primary purpose of the class is to provide a concrete
container for the JFC. The JPanel class is provided ti give a concrete container class.Being a
extansion of the Jcomponent class,Jpanle is a container and inherits the features contained in
that class
The following code illustrates the usages of JPanel
Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;
Import javax.swing.*;
Class panel extends Jframe{
Public panle(){
SetTitle(―Box 1‖);
Jpanle contentpane=(Jpane)getContentPane();
Contentpane.setLayout(new GridLayout());
JButton ok=new Jbutton(―OK‖);
Contentpane.add(ok);
Jbutton cancel=new Jbutton(―CANCEL‖);
Contentpane.add(cancel);
Myadapter myapp=new myadapter();
AddWindowListener(myapp);
}
private class myadapter extends WindowAdapter{
public void windowClosing(WindowEvent e){
system.exit(0);
}
}
public static void main(String args[]){
panle b= new panle();
b.setSize(400,400);
b.setVisible(true);
}
}
JFrame
This is an extension of the AWT Frame class. An instance of the Jframe class is a
heavyweight component. It creates a top-level class that con be positioned and resized
independently.
The JFrame can be created using the constructors mentioned below
Constructors Description
JFrame() Create a new JFrame that is initially invisible
JFrame(String title) Create a new JFrame,initially invisible with the
specified title
JApplet
The JApplet class is an extension of the AWT applet class. This class is the preferred entry
point when creating applet that contain JFC components. The structure of the JApplet calss is the
same as that of the JFrame class. It contains an instance of the JrootPane class as its Child.
Components are added to to ContentPane
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class JcomboBoxDemo extends JApplet
Implements ItemListener {
Jlabel ji;
ImageIcon france,germany,italy, japan
Public void init(){
Container contentPane = getContentPane();
ContentPane.setLayout(new FlowLayout());
JcomboBox jc = new JcomboBox();
Jc.addItem(―France‖);
Jc.addItem(―germany‖);
Jc.addItem(―Itally‖);
Jc.addItem(―Japan‖);
Jc.addItemListener(this);
ContentPane.add(jc);
// create label
jl = new Jlabel(new ImageIcon(―france.gif‖);
contentPane.add(jl);
}
public void itemStateCahnged(ItemEvent ie){
String s = (String)ie.getItem();
Jl.setIcon(new ImageIcon(s + ―.gif‖));
}
}
Jlist
A Jlist is functionally similar to JcomboBox menu in that it allows the user to select one or
more objects from alist of choices. A Jlist will generate events when its selection changes,or when
any of its items changes . The differences between a Jlist and JcomboBox menu are given below
1. Unlike JcomboBox,which displays only the single-selected item, the list can be made to
show any number of choices in the visible window.
2. The Jlist can be constructed to allow multiple selection.
ScrollPane
A scroll pane is a component that presents a rectangular areas in which a component may be
viewed. Horizontal and/or vertical scroll bars may be provided if necessary .Scroll panes are
implemented in swing by the JscrollPane class,which extends Jcomponent.Some of it constructor
are shown here:
JscrollPane(Component comp)
JscrollPane(int vsb,int hsp)
JscrollPane(Component comp,int vsb,int hsb)
Here comp is the component to be added to the scroll pane pane.vsb and hsb are int constants that
define when vertical and horizontal scroll bars for this scroll pane are shown.
CHAPTER-15
JMenuBar
This component typically appears at the top of a JFrame, JWindow and JInternalFrame. It cannot be
added directly to the frame. It can be added only through the JFrame, Jwindow and JinternalFrame‘s
root pane. A JMenuBar is a component that can be added to a container similar to any other
component. It contains a set of Jmenus, with each Jmenu represented as a string within the
JMenuBar. When the user clicks one of the text strings, the associated menu pops up under the text
string and displays its menu items.
The next step is to add the menu bar into the JFrame. Normally the menu bar will be placed under
the title bar of the JFrame or JInternalFrame. These components use their root pane to hold menu
bars. Components with JRootPanes typically have a convenient method called setJMenuBar. Using
this
method, menu bar can be added in to the JFrame.
MyFrame.setJMenuBar(mb);
JMenu
This component actually appears in two ways. When this component is added to a JMenuBar, it
appears as a text string. When the user clicks on that text string, the JMenu expands the ral menu
under its menu bar string, displaying all of its menu items.Only one menu can be selected at a time
in the menu bar.
JPopupMenu
JPopupMenu component is used to display an expanded form of menu. There are two ways in which
this component can be used. It can be used as part of a JMenu or used by itself as a menu that can
be displayed anywhere on the applet. A JPopupMenu looks like a rectangular window that contains
a list of items, which will be displayed when a menu is clicked. These menu items are normally any
component that implement the MenuElement interface. The standard menu items that are added to
the JPopupMenu are JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem.
JMenuItem
A menu item is essentially a button in a list. When the user selects the button, the action associated
with the menu item is performed. A JmenuItem contained in a JPopupmenu performs exactly that
function. This component typically appears as a text String possibly with an icon in a Jmenu or
JPopupmenu. Pressing a JmenuItem does not change its appearance as JButton does. One thing to
be noticed here is that when the user clicks and releases the mouse on a JmenuItem, the menu that
contains this item will disappear from the screen and the corresponding dialog box will be
displayed for that menu item.
JCheckBoxMenuItem
From the name of the component it is understood that this menu item will contain one of the
JComponents called JCheckbox as menu items. A JcheckBoxMenuItem will always either be selected
or deselected and its appearance shows its current state. When a JcheckBoxMenuItem is selected it
has a mark next to it. If it is not selected , there is not checkmark. This component can also have a
string or an icon. The properties of JcheckBoxMenuItem can also be change. This is one of the great
features, which makes it possible to control the components appearance.
JRadiioButtonMenuItem
JRadioButtonMenuItems belongs to a single ButtonGroup so that only one can be selected at any
point to time. A JradioButtonMenuItems has a string or an icon and display it current state, i.e,
whether it is selected or deselected, by placing a dot to the left of the text icon. The icon in the
menu items are only for decoration purposes. The icon will not change the current state when the
user select or deselects the JradioButtonMenuItem.
The following code illustrates the usage of Menus:
Import java.util.*;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Import javax.swing.event.*;
Public class Menus extends JPanel implements ActionListener, MenuListener
{
JTextField field;
Public Menus(JFrame frm)
{
JMenuBar bar=new JMenuBar();
JMenu menu=new JMenu(―Emp.Names‖);
JmenuItem tmp;
SetBackground(Color.lightGray);
SetLayout(new BorderLayout());
SetDoubleBuffered(true);
Menu.addMenuListener(this);
Tmp=new JmenuItem(―‖Robert‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Robert‖);
Menu.add(tmp);
Tmp=new JmennuItem(―Mohammed‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Mohammed‖);
Menu.add(tmp);
Tmp=new JMenuItem(―vinod‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―vinod‖);
Menu.add(tmp);
Tmp=new JMenuItem(―Quit‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Quit‖);
Menu.add(tmp);
Bar.add(menu);
Frm.setJMenubar(bar);
Field=new JtextField(10);
Field.addActionListener(this);
Field.setActionCommand(―Text Filed Activated‖);
Add(field,‖South‖);
}
public void actionPerformed(ActionEvent e)
{
Stribg cmd;
Cmd=e.getActionCommand();
Field.setText(―Action:‖+cmd);
If(cmd.equals(―Quit‖))
{
System.exit(0);
}
}
public void menuSelected(MenuEvent e)
{
field.setText(―Menu selected‖);
}
public void menuDeselected(MenuEvent e)
{
field.setText(―Menu deselected‖)
}
public void menuCanceled(MenuEvent e)
{
field.setText(―Menu canceled‖);
}
public Dimension getPreferredSize()
{
return new Dimension(200,100);
}
public static void main(String s[])
{
JFrame frame=new JFrame(―Menus‖);
Menus panel=new Menus(frame);
Frame.setForeground(Color.black);
Frame.setBackground(Color.lightGray);
Frame.addWindowLstener(new WindowCloser());
Frame.getContentPane().add(panel,‖center‖);
Frame.setSize(panle.getPreferredSize());
Frame.setVisible(true);
}
}
class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window win=e.getWindow();
Win.setVisible(false);
System.exit(0);
}
}