0% found this document useful (0 votes)
4 views185 pages

Core_Java_New[1]

Java is a programming language developed by Sun Microsystems, initially created for smart consumer devices, and later adapted for internet applications. It is characterized by its object-oriented nature, portability, security features, and high performance, allowing programs to run on various platforms without modification. The Java Development Kit (JDK) provides the necessary tools for creating and running Java applications and applets.

Uploaded by

azsafrah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views185 pages

Core_Java_New[1]

Java is a programming language developed by Sun Microsystems, initially created for smart consumer devices, and later adapted for internet applications. It is characterized by its object-oriented nature, portability, security features, and high performance, allowing programs to run on various platforms without modification. The Java Development Kit (JDK) provides the necessary tools for creating and running Java applications and applets.

Uploaded by

azsafrah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 185

1.

Introduction To Java

1.1 History of Java

Java began life as programming language Oak

Java was developed at Sun Microsystem. The history of Java can be traced
back to a project called Green project in SUN. Patric Naughton, Bill Joy, James
Gosling, Mike Sheridan were some of the people working on the Green project.

The aim of this project was to develop software for smart consumer electronic
devices such a complex remote controls. At first developer tried using C++ to
develop the software but they faced a number of problems.

So James Gosling developed a new language, which he called Oak. A study


showed that there already was a programming language called Oak. So they
changed the name to Java.

In 1994, the Internet and the World Wide Web became popluar. The people at
Sun realized that Java was suitable to develop applications for the Internet.

They wanted fundamentally a new way of computing, based on the power of


networks and wanted the same software to run on different computers,
consumer gadgets and other devices

During that time Mosaic the First Graphical Browser was released, with
this people on different types of machines and operating systems started accessing
the applications available on the web.

Patrick Naughton and his colleague Jonathan Payne developed a browser in


Java called WebRunne

r, which they later renamed as Hot Java. Sun Formally released Java and hot
Java in 1995. Hot Java proved to the world that it was possible to develop complex
applications by using java.

Members of the Oak team realized that java would provide the required
cross-platform independence from the hardware network, and the operating
system. Very soon, Java became an integral part on the web.

1.2 The New Era of Java

Java is a programming language from Sun Microsystems,

But, Java is much more than just a Programming language.

Java is new programming language from Sun Microsystems with elements


from C, C++, and other languages, and with libraries highly tuned for the Internet
Environment.

Java is quickly recognizable to many programmers. The statements and


expressions are similar to those in many languages and, in most cases, identical to
those of C or C++.

1
1.3 Comparison of Java with C:

Although Java adds some new things, it is most distinctive for what is left out.

Compared with C is,

Java does not have:

▪ Memory address (pointer) arithmetic


▪ The goto statement
▪ Automatic type conversion
▪ Global functions variables
▪ Type definitions aliases (typedefs)
▪ Preprocessor

1.4 Compared with C++:

Java does not have:

▪ Templates
▪ Operator overloading
▪ Multiply inheritance
▪ Multiple APIs in java

1.5 The Java system has several pieces:

▪ Java Programming Language


▪ Software Libraries accompanying the system (API)
▪ Java Virtual Machine (Platform Independent)
▪ Java-Enabled Web Browser

1.6 Characteristics of Java

Java is High-Level Programming Language that is all of the following:

▪ Simple and Powerful


▪ Architecture-Neutral
▪ Object-Oriented
▪ Portable
▪ Distributed
▪ High-performance
▪ Interpreted
▪ Multithreaded
▪ Robust
▪ Dynamic
▪ Security

2
Java is....

Simple and Powerful

Java was designed to be easy for the professional programmer to learn and
use effectively Java makes itself by not having surprising features.

Since it exposes the inner working of a machine, the programmer can perform
his desired actions without fear. Unlike other programming systems that provide
dozens of complicated ways to perform a simple task,

Java provides a small number of clear ways to achieve a given task.

Anyone can master Java with a little bit of programming experience. If the
user already understands the basic concepts of object-oriented programming,
learning Java will be much easier.

Secure

Today everyone is worried about safety and security. People feel that
conducting commerce over the Internet is as safe as printing their credit card
number on the first page of a newspaper. Threatening of viruses and system hackers
also exists. To overcome all these fears Java has safety and security as its key
design principle.

Using Java Compatible Browser, anyone can safely download Java


applets without the fear of viral infection or malicious intent.
Java achieves this protection by confining a Java program to the Java
execution environment and by making it inaccessible to other parts of the computer.
We can download applets with confidence that no harm will be done and no
security will be breached.

Java enables the constructions of virus-free, tamper-free systems.

Portable

In Java, the same mechanism that gives security also helps in portability.
Many types of computers and operating systems are in use throughout the world and
are connected to the Internet. For downloading programs through different platforms
connected to the Internet, some portable, executable code is needed.
Java's answer to these problems is its well-designed architecture.

Object-oriented

Java was not designed to be source-code compatible with any other language.
Java team gave a clean, usable, realistic approach to objects. The object model in
Java is simple and easy to extend, while simple types, such as integers, are kept as
high-performance non-objects.

3
Robust

Most program in use today fail use of two reasons:

▪ Memory management
▪ Exceptional conditions.

Thus, the ability to create robust programs was given a high priority in the
design of Java. Java forces the user to find mistakes in the early stages of program
development. At the same time, Java frees the user from having to worry about
many of the most common causes of programming errors.

Java checks code at compilation time.

However, it also checks the code at run time.

Java virtually rectifies the problem of memory management by managing


memory allocation and automatic memory deallocation by providing garbage
collection for unused objects.

Java also handles exceptional conditions by providing object-oriented


exception handling. In a well-written Java program, all run-time errors can- and
should be managed by the program itself.

Multithread

Java was designed to meet the real-world requirements of creating


interactive, networked programs. To achieve this,

Java supports multithread programming, which allows the user to write


programs that perform many functions simultaneously.

The Java run-time system enables the user to construct smoothly running
interactive systems.

Architecture-Neutral

The Java designers worked hard in attaining their goal "write once: run
anywhere, anytime, forever" and as a result the Java Virtual Machine was
Developed.

Since Java is Architecture-neutral it generates bytecode that resembles


machine code, and are not specific to any processor(CPU).

Interpreted and High performance

Java enables the creation of cross-platform programs by compiling the code


into an intermediate representation called Java byte code.

This code can be interpreted on any system that has a Java Virtual Machine.
Most of the earlier cross-platform solutions are run at the expense of performance.
Other interpreted systems, such as BASIC, Tel and PERL, suffer from almost insoluble
performance deficits.

Java byte code was carefully designed so that it can be easily translated into
active machine code for very high performance by using a just-in-time compiler.

4
Distributed

Java is designed for the distributed environment of the Internet, because it


handles TCP/IP protocols. This allowed objects on two different computers to execute
procedures(programs) remotely.

Java has recently reweived these interfaces in a package called Remote


Method Invocation (RMI).

Dynamic

Java program carry with them extensive amounts of run-time information that
is used to verify and resolve accesses to objects at run time. Using this concept it is
possible to dynamically link code. Dynamic property of java adds strength to the
applet environment, in which small fragments of byte code may dynamically updated
on a running system.

1.7 The Java Platform

The Java Programming language is both compiled and interpreted. After


writing a Java program, you have to first compile it.

After compilation, the program is converted into a format called ByteCodes.


After bytecodes can be executed on any computer. So bytecodes are said to the
Platform independent.

The bytecodes are then interpreted by the Java Interpreter. The java
interpreter is called the Java Virtual Machine (JVM) or the Java Runtime Engine. The
JVM convers the bytecodes into the machine code that be understood by the specific
computer on which it is run.

M/C code
Java Program
Interpreter 01001 Computer

Compiler Byte Code

Running bytecode on a JVM is the reason that Java software is "Write Once Run
Anywhere". Java executables provide a single binary that runs on every processor.

For example, the same Java program can run on Windows NT. Solaris, or
Macintosh.

add.c compiler add.exe


add.cpp add.obj

add.java compiler add.class interpretor machine code

5
Java
Program

Compiler

Interpreter Interpreter Interpreter

Windows Solaris Lunix


s

1.8 The Java API

The Java API supports all kinds of programs with packages of software
components that provide a wide range of functionality.

The core API given us the following features.

The Essentials: Objects, Strings, Threads, Numbers, Input and Output, Data
structures, System properties, Data and Time, and so on.

Applets: The set of conventions used by Java applets.

Networking: URLs, TCP and UDP sockets, and IP addresses.

Internationalization: Help for the writing programs that can be localized for users
worldwide. Program can automatically adapt to specific locales and be displayed in
the appropriate language.

Security: Both low-level and high-level, including. Electronic Signatures,


Public/Private key management, Access control, and Certificates.

Software component: Known as Java Beans, can plug into existing component
architectures such as Microsoft's OLE/COM/Active-X architecture, OpenDoc, and
Netscape's Liver Connect.

Object Serialization: Allows lightweight persistence


and communication via Remote Method
Invocation (RMI).
Java Database Connectivity (JDBC): Provides uniform access to a wide range of
relational databases.

Java not only has a core API, but also standard extensions. The standard
extensions define APIs for 3D, Servers, Collaboration. Telephone, Speech,
Animation, and more.

6
Packages of the Java API

java. lang Core language classes


java. applet Applet classes
java. awt Graphics, window, and GUI classes
java. awt. data transfer Data transfer(eg. Cut & paste) classes
java. awt. event Event processing classes & interfaces
java. beans Java Beans component model API
java. io Various types of input/output classes
java. net Networking classes
java. rmi Remote method invocation classes
java. security Security classes
java. sql JDBC SQL API for database access
java. util Various useful data classes

1.9 Java Development Kit(JDK)

JDK is a collection of tools that are necessary to work with java Applet and
applications.

▪ javac - the compliser, checks for syntactical error and converts syntax free
java program into bytecode.
▪ java - the Interpreter, executes the bytecode
▪ appletviewer - used to test applets on machines which does not havejava
enabled web browser

1.10 Type of Java Programs?

Java is of two things:

▪ An Application Programming language


▪ A Applet (Platform Independent Programming)

1.10.1 Applications:

JAVA applications can read from and write to files on the local computers. Standalone
applications make use of the resources of just a single computer. It is stored on the
hard disk of the local computers.

1.10.2 Applets:

Applets are JAVA programs that are used to develop web pages.
Java applet are programs that require a Web Browser with a JVM to run.

7
Summary

JAVA is a fully object oriented programming Language developed by SUN


MicroSystems in1995.

Advantages of JAVA:

1. It is easy to learn.
2. Everything in JAVA is in the form of Classes and Objects.
3. It provides the features of Abstraction, Encapsulation, Polymorphism
and Inheritance.
4. JAVA programs can access data across a network.
5. The byte code can be executed on a variety of computers running on
different operating system(Platform independent).
6. Java does not allow a programmers to manipulate the memory of the system.
7. Java programs are faster when compared to programs written in other
interpreter-based languages.
8. It allows multiple parts of a program to run simultaneously.
9. There are two types of JAVA programs 1.Application 2.Applets

8
2. Java Programming and Fundamentals

2.1 Structure of a JAVA program:


class <Class_name>
{

public static void main(String args[])


{
statements;
}
}

Program:

/* this is a simple java program .


call this program as Example.java */

class Example

{
//program begins with a call to the main method

public static void main(String args[])


{
System.out.println(“Welcome to JAVA”);
}
}

2.2 Comments:

A comments describes or explains the operation of the program to anyone


who is reading the source code.

The compiler ignores the contents of the comment.

In java, Three Types of component statements can be included in the


programs.

They are:

(i) A Single Comment statement précised by all the text which follows the
//, which treated as a comment and ignored by the compiler.

(ii) A Multiline Comment enclosed within the two character sequence /*…*/

(iii) The third type called the Documentation Comment begins with a /**
and ends with a */. They are used to produce a HTML file that documents
the program.

Every program in Java is a class. So, the first line of any Java program is
always class followed by the name of the program. The name of the program can be
anything it should only begin with an alphabet and contain no spaces.

9
The next line contains four words public, static, void and main.
public: The method main can be accessed by any other class.
static: The method main is associated with the class where it is declared.
void : The method main does not return any value.
main: main is the name of the method which can execute at first.

The method name main is followed by (String args[]). This means that the
method main accepts an array of string from the command line.

Creating , Compiling and Running a JAVA Program:-

To create a JAVA program, open a text editor(notepad).

1. Type JAVA program.


2. Ensure that the JAVA program is saved with the same name as given in the
class name of a program. Eg: Example.java
3. Also ensure that the program is saved with the extension .java.
4. To compile a java program, type javac specifying the name of the source file
on the command line.

javac <filename>.java

Eg: javac Example.java


5. The javac compiler creates a class file that contains the byte code version of
the program.

Eg: Example.class
6. To run a java program, executes the interpreter specifying the name of the
class file on the command line.

java <file name>

Eg: java Example

2.3 Java Fundamentals

2.3.1 Java Keywords

There are 48 reserved keywords currently in the java language. These


keywords, combined with the syntax of the operators and separators, form the
definition of the java language. These keywords cannot be used as variable, class or
method.

abstract do implements short


boolean double Import static
break else Int super
byte extends Interface switch
case final Long this
catch finally New throw
char float Private try
class for Protected true
continue false Public void
default if Return while

10
2.3.2 Data Types

All variables in the java language must have a data type.

A variable's data type determines the values that the variable can contain and
the operations that can be performed on it.

For example: Integers can contain only integral values (both positive and negative).
You can perform operations, such as addition, on integer variables.

The java programming language has two major categories of data types:

▪ Primitive (Primary Data types)

▪ Reference (object)

A variable of primitive type contains a single value of the appropriate size


and format for its type: a number, a character, or boolean value.

For example: the value of an int is an integer, the value of a char is a 16-bit
Unicode character, and so on.

Arrays, classes, and Interface are Reference types. The value of a


reference type variable, in contrast to that of a primitive type, is a reference to the
actual value or set of values represented by the variable.

A Reference is called a Pointer or a Memory address in other languages.


A reference is like your friend's address. The address is not your friend, but it's a way
to reach your friend.

A reference type variable is not the array or object, but rather a way to reach
it.

Primitive Data Types

Keywords Description Size/Format

(Integers)
8-bit two's complement (1 byte)
byte Byte-length integer

short Short integer 16-bit two's complement (2 byte)

int Integer 32-bit two's complement (4 byte)

long Long integer 64-bit two's complement (8 byte)

(Real numbers)
Single-Precision
float 32-bit (4 byte)
floating point
Double-precision
double 64-bit (8 byte)
floating point
(Other types)

char A single character 16-bit Unicode character (2 byte)

boolean A Boolean value true or false

11
In other languages, the format and size of primitive data types may depend
on the platform on which the program is running. In contrast, the java language
specifies the size and format of its primitive data types. Hence, you don't have to
worry about system dependencies.

2.3.3 Identifiers : A name can be specify to memory location like variable,


constant, array name, class name, object etc.,

Rules for Constructing Identifier Names


(i) The Identifier name must start with an alphabet, underscore and
DollerSign and can contain only alphabets, number, underscore and
DollerSign($).
(ii) No space between Identifier name
(iii) Java Keywords cannot be used as Identifier names.
(iv) Java is a case-sensitivity, a Identifier name with upper case letters is
different from the same name with lower case letters.

Declaration of Variable and Constants:

Syntax
datatype <identifiername>;

Example: float radius; //(variable);

final float PI=3.14; //(constant)

Note : You can declare variables anywhere in the program.

In addition to the name and type that you explicitly given to a variable, a
variable also has scope.

Scope : is the life span of the variable it determines what sections of code
can use the variable. The location of the variable declaration, that is where the
declaration appears in relation to other code elements, determines its scope.

The MaxVariables program, show below, declares eight variable of different


types within its main method.

public class MaxVariable


{
public static void main(String arg[])
{
//integers
//assign maximum value for each data types

byte largestByte = Byte.MAX_VALUE;

short largestShort = Short.MAX_VALUE;

int largestInteger = Integer.MAX_VALUE;

long largestLong = Long.MAX_VALUE;

12
//real Numbers

float largestFloat = Float.MAX_VALUE;


double largestDouble = Double. MAX_VALUE;

//other primitive types

char aChar ='S';


boolean aBoolean = true;

//display them all

System.out.println("The largest byte value is "+


largestByte);

System.out.println("The largest short value is "+


largestShort);

System.out.println("The largest Integer value is "+


largestInteger);

System.out.println("The largest long value is "+


largestLong);

System.out.println("The largest float value is "+


largestFloat);

System.out.println("The largest double value is "+


largestDouble);

if(Character.isUpperCase(aChar))
{
System.out.println("The Character "+aChar +" is upper
case.");
}
else
{
System.out.println("The Character "+aChar +" is lower
case.");
}
System.out.println("The value of aBoolean is "+aBoolean);
}
}

By Convention:
Variable names begin with a lowercase letter and Class names begin
with an uppercase letter. If a variable name consists have more than one word,
such as isVisible, the word are joined together and each word after the first begins
with an uppercase letter. Constant in java are defined as Fully uppercase
eg: Math.PI

2.3.5 Literals or Constants:


Integer Literals → 15,-15,28 etc.
Floating point literals → 15.0,25.89,0.028 etc.
Character literals → ‘k’,’$’,’5’ etc.
String literals → ”World”,”128”,"#$%" etc.
Boolean literals → true, false

13
3. Operators in Java
An operator is a symbol that specifies an operation to be performed.
1. Arithmetic Operator
2. Relational Operator
3. Conditional Operator
4. Logical Operator
5. Assignment Operator
6. Increment/Decrement Operator
7. Comma Operator
8. Bitwise Operator etc.,

3.1 Arithmetic Operators

Java has five basic arithmetic operators. Each of these operators takes two
operands, one on either side of the operator.

Operator Meaning Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulo (Reminder Value) a%b

Implicit Type Casting: Converting from one datatype another datatype


There are few Implicit (Directly by Java) type conversion :

OPERAND1 OPERAND2 RESULT

int int int


int float float
float float float
float double double
double float double
int double double
double double double

Explicit Type Casting : Are convert by the java programmer


Eg: float x=float(int var1/int var2);
Operators as per precedence:

L-R Left to Right


() For grouping the variables
*, /, % Multiplication, division and modulo
+,- Addition and subtraction

14
Command Line Arguments (Keyboard Input) :

class Argument
{
public static void main(String args[])
{
int a,b,c;
float f;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[1]);
f=(float)((a+b)/c);//type cast to float
System.out.println(“Result =”+f);
}
}
To run this above program after complied

C:\>java Argument 5 2 2

OUTPUT : 3.5

A command line argument is the information that directly follows the


program’s name on the command line when it is executed. To access the command
line arguments inside a java program is quite easy. They are stored as strings, in
the String array, passed to main method.

a=Float.parseFloat(args[0]);
b=Float.parseFloat(args[1]);

c:\>java Argument 25.34 14.60

Program: To get input from Keyboard

import java.util.*;
class Scan
{
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int i = sc.nextInt();
System.out.println("Enter a number");
int j=sc.nextInt();
int k=i+j;
System.out.println(k);
}
}

15
3.2 Relational Operators

There are several expression for testing equality and magnitude. All these
expressions return a Boolean value.

Operator Meaning Example


== Equality a==b
!= Not Equal a!=b
< Less than a<b
> Greater than a>b
<= Less than or equal to a<=b
>= Greater than or equal to a>=b

3.3 Logical operators

Logical operators available are AND, OR, XOR and NOT.

A B A&&B A||B A ^B
True True True True False
True False False True True
False True False True True
False False False False False
NOT(!) True -> False False-> True

3.4 Conditional Operator

The Conditional Operator is otherwise known as Ternary Operator and is


considered to be an alternative to the if..else construct. It returns a value and the

Syntax:

<test> ? <ture> : <false>

where <test> is the condition to be tested. If the condition returns true than
statement give in <pass> will be executed. Otherwise, the statement gives in<fail>
will be executed.

Example: c=a>b?a:b
Check for simple expression with true or false

3.5 Assignment Operators

The assignment operators used in c and C++ are also used in java. A selectin
of assignment operators is given

Syntax:
1. Variable = Constant eg: a=10;
2. Variable1 = Variable2 eg: a=b;
3. Variable = Expression eg: a=a+b;

Pre Assignment Post Assignment


X+=Y X=X+Y
X-=Y X=X-Y
X*=Y X=X*Y
X/=Y X=X/Y

16
3.5 Increment and Decrement Operators

To increment or decrement a value by one, the ++operator are used


respectively. The increment and the decrement operatos can be prefixed or
postfixed. The different increment and decrement operators can be used as given
below.

PostIncrement Operator Meaning


a++ First “a” value is Assign and then
increment by one.

Example:
a=10;
b=a++;

Result is : a=11
b=10

PreIncrement Operator Meaning


++a First Increment “a” by 1, then assign the
value of “a” to b .

Example:
a=10;
b=++a;

Result is : a=11
b=11

PostDecrement Operator Meaning


a-- First “a” value is Assign and then decrement
by one

Example:
a=10;
b=a--;

Result is : a=9
b=10

PreDecrement Operator Meaning


--a First Decrement “a” by 1, then assign the
value to “a” .

Example:
a=10;
b=++a;

Result is : a=9
b=9

17
3.6 Bitwise Operators

The bitwise operators are inherited from C and C++. They are used to
perform operations on individual bits in integers. A list of the bitwise operators
available is given int table:

Operators Meaning
& Bitwise AND
| Bitwise Or
^ Bitwise XOR
<< LeftShift
>> RightShift
~ Bitwise complement
X&=Y AND assignment
X|=Y OR assignment
X^=Y XOR Assignment

Program :
class Bitwise
{
public static void main(String arg[])
{
int x=5;
int y=3;
System.out.println(x&y);
System.out.println(x|y);
System.out.println(x^y);
System.out.println(x>>2);
System.out.println(x<<2);
}
}
OUTPUT :
1
7
6
1
20

18
4. Control Statements
This Statement will alter the program sequence and it is used to make a decision

Type of Control Statements :

1. Simple if Statement
2. if…else
3. Nested if…else
4. else…if ladder or or Mutliple else if
5. (if…elseif..else)
6. Switch..case statement.
7. Loops

4.1 Simple if Statement

If statement, is used to check a condition and execute different statements


based on the outcome of the condition. In java, the general form of the statement is,

Syntax:
if (condition)
{
statement(s);
}
normal statement;

Explanation:
When the condition is true the statement(s) are executed and then control
is passed to the statement immediately after the if statement. If the condition is
false, control is passed directly to the statement following the if statement, ie.,
Normal statement will execute.

Program:

class IfDemo
{
public static void main(String arg[] )
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);

if(a>b)
{
big=a;
}

if(b>a)
{
big=b;
}
System.out.println(“Big= "+big);

19
OUTPUT :
10
20
Big=20

4.2 If..else statement

In an if statement, if the condition is false, control is passed to the statement


following the if statement. The if-else statement, allows you to explicitly specify one
or more statements to be executed when the condition is false. The general format
of the statement is,

Syntax:

if(condition)
{
true block statement(s)
}
else
{
false block statement(s);
}
statement-x;

Explanation:
Here, If the condition is true, the true block statement(s) are executed and
if the condition is false, the false block statement(s) are executed. Statement -x
will execute always after the if ..else block

Program:

class IfElseDemo
{
public static void main(String arg[] )
{
int a =100 ,b=20,big=0;

if(a>b)
{
big=a;
}

else
{
big=b;
}
System.out.println(“Big= "+big);

OUTPUT :
100
20
Big=100

20
4.3 Nested if statements
Sometimes, while writing programs, it becomes necessary to check a second
condition based on the result of the first. In such cases, the second if statement has
to be nested within the first if statement. Such statement are called Nested if
statement

Syntax:
if(condition1)
{
.............
.............
if(condition2)
{
............
............
}
else
{
..........
...........
}
}
else
{
..........
..........
}

Here, condition1 is evaluated first. If it is true, then condition2 is


evaluated otherwise control is passed to the last else statement and all the
statements in between are skipped. Similarly result of condition2 determines
whether condition3 is to be evaluated and which set of statements is to be
executed.

Program:

class NestedIfDemo
{
public static void main(String arg[] )
{
int a =67 ,b=89,c=45,big=0;

if(a>b)
{
if(a>c)
big=a;
else
big=c;
}
else
{
if(b>c)
big=b;
else
big=c;

21
}

System.out.println(“Big= "+big);
}
}

OUTPUT :
67
89
45
Big=89

4.4 Else if ladder or Mutliple else if


The conditions are evaluated from the top to bottom with more than two conditions.

Syntax:
if(condition1)
{
statement1
}
else if(condition2)
{
statement2
}
else if(condition3)
{
statement3
}
----------------------
----------------------

else
{
default statement
}
statement-x;

As soon as a true condition is found, the statement associated with it is


executed and the rest of the ladder is bypassed. If none of the conditions are true,
the final else is executed. That is, if all other conditional tests fail, the last else
statement is performed. If the final else is not present, no action takes place if all
other conditions are false.
Program:

22
class NestedIfDemo
{
public static void main(String arg[])
{
int m1=56,m2=45,m3=59,m4=50,m5=91;
double per=(double)0.0;
int tot= m1+m2+m3+m4+m5;
per=tot/5.0;
System.out.println("Total Marks = "+tot);

System.out.println("Percentage = "+per);

if(per>=75)
{
System.out.println("Distinction");
}
else if(per>=60)
{
System.out.println("First Class");
}
else if(per>=50)
{
System.out.println("Second Class");
}
else if(per>=40)
{
System.out.println("Third Class");
}
else
{
System.out.println("No Grade");
}

}
}
OUTPUT
Total Marks = 301
Percentage = 60.2
First Class

4.5 Switch Statement


Nested if statement are very useful but they can become complex and difficult
to debug as the number of if statements increases. An alternative is to use switch
statement. A switch statement is used to choose one option out of many, based
on the value of an expression.

Syntax:

switch(expression)
{
case constant1:
statement1
break;
case constant2:
statement2

23
break;
-------------
-------------
case constant n:
statement n
break;
default:
default statement
break;
}

In switch statement, expression is compared with each of the constants


constant1, constant2, constant3, and so on. When a match is found, the
statements following the case are executed. The break statement is used to break
out of the switch statement and pass control to the statement following the switch
statement.
Program :

class SwitchDemo
{
public static void main(String arg[])
{
int n = Integer.parseInt(arg[0]);

switch(n)
{
case 1:
System.out.println("The number is one");
break;
case 2:
System.out.println ("The number is two");
break;
case 3:
System.out.println ("The number is three");
break;
default:
System.out.println ("The number is not
between 1 and 3");
break;
}
System.out.println ("\nEnd of program");

}
}
OUTPUT
C:\> java SwitchDemo 2

The number is two

24
4.6 Loops in Java
Computers are best suited for applications where a sequence of steps has to be
repeated several times. The program construct that is used to repeat such a
sequence of steps is called as loop. Every loop consists of condition that determines
the number of times those statements are to be repeated. There are three different
loop statements in Java, they are

1. while Loop
2. do-while Loop
3. for Loop

4.6.1 While Loop

The while loop executes a set of code repeatedly until the condition returns false.

Syntax :

while(condition)
{
statement(s);
}

This loop is executed as long as the condition is true. When the condition
becomes false control is passed to the statement following the while statement.
Program:

class WhileDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int i=1,s=0;

while(i<=n)
{
s=s+i;
i++;
}
System.out.printlnf("Sum of n Number is “+s);
}
}

OUTPUT :
10
55

4.6.2 do-while loop


The do-while loop is very similar to the while loop. The difference is that in a
do-while loop, the condition is evaluated at the end of the loop. That means the
loops are executed atleast once even though if the condition false. The general
format of the statement is
Syntax:

25
do
{
statement(s);

}while(condition);

Program:

class DoWhileDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int i=1,f=0;
do
{
f=f*i;
i++;
} while(i<=n);
System.out.printlnf("Product of a given Number is “+s);
}
}

OUTPUT :
10
55

4.6.3 For loop


As the name indicates, the for statement is used to repeat one or more
statements for a specified number of times

Syntax :

for(initialization; condition; increment)


{
statement(s)
}

Initialization
Statement that assigns an initial value to the control variable. The control
variable is a variable that is used to keep track of the number of times the loop has
to be repeated. This statement is executed once at the beginning of the loop.

Condition
A condition that compares the control variable with a value to find out if the
loop has been repeated the required number of times. If the condition is true, the
loop is repeated again, If the condition is false, control is passed to statement after
the for loop. The test is performed at the start of every iteration.

26
Increment
A statement that increases (or decreases) the value of the control variable by
a specified number every time the loop is executed. This statement in executed at
the end of every iteration.
Program:

class ForDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int s=0;
if(n==0)
System.out.println(s);
else
for(int i= 1;i<=n;i++)
{
s=s+i;
}
System.out.printlnf("Sum of n Number is “+s);
}
}

OUTPUT :
10
55

4.7 Break and Continue

The break keyword halts the execution of the current loop and forces control
out to the loop. The term break refers to the act of breaking out of a block of code.
Inorder to refer to a block by name, java has a label construct that assigns a name to
every block.

Continue is similar to break, except that instead of halting the execution of


the loop, it starts the next iteration. The following example demonstrates the usage
of continue statement.

Example for Break and Continue Statement:


Program 1:

// Write a program to check whether the number is prime or not


class BreakDemo1
{
public static void main(String arg[])
{
int n= Integer.parseInt(arg[0]);

for(int i=2;i<n;i++)
{
if(n%i==0)
break;
else
continue;
}

27
if(i==n)
System.out.println("Given number is prime");
else
System.out.println ("Given number is not prime");
}

OUTPUT:
5
Given number is prime

Program 2:

//Break with label name

class BreakDemo2
{
public static void main(String arg[])
{
boolean t=true;
a: {
b: {
c: {
System.out.println("Before the break");
if(t)
{
break b;

}
System.out.println("This will not execute");
}
System.out.println("This will not execute");
}
System.out.println("this is after b");
}
}
}

OUTPUT :
Before the break
This is after b

Example for Continue Statement;

Program:

//example for continue statement.

class ContinueDemo
{
public static void main(String arg[])
{
for(int i=0; i<10; i++)
{
System.out.print(i+" ");

if(i % 2 == 0)
{
continue;
}
System.out.println();

28
}
}
}

OUTPUT:
0 1
2 3
4 5
6 7
8 9

4.8 Nested loop:

When one loop statement is embedded within the another loop, it is called as
a Nested Loop. In java, multiple for loops(and while loops are do-while loops) can
be nested within each other.

Program:

class Nest
{
public static void main(String arg[])
{
int n;
n=Integer.parseInt(arg[0]);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}

}
}

OUTPUT:

Java Nest 5

1
1 2
1 2 3
1 2 3 4
1 2 3 3 4 5

29
5. Arrays in Java :
An array is an object that stores a list of items continuesly of same data type. An
array is used to store data continuelsy in the memory of the computer.

There are Single Dimensional and Multi Dimensional arrays.

5.1 Single Dimension Array:

Declaration of Single Dimension Array:

5.1.1 Array Initialization:

Syntax : data-type array-name[] = {value1,value2,.....};

Eg: int a[]= {10,20,50,67,77}

5.1.2 Creating array with size

datatype array-name [] = new datatype[size];

Eg: int a[] = new int[5]; or int[] a = new int[5];

or

int a[];
-------------------;
-------------------;
a[]= new int[5];

new keyword creates an instance of the array

Program: Sum of array

import java.io.*;

class SingleArray
{
public static void main(String arg[])
{
DataInputStream in = new DataInputStream(System.in));
System.out.println("Enter array size ");
String str=in.readLine();

int size=Integer.parseInt(str);

int a[] = new int[size];


int sum=0;
for(int i=0;i<n;i++)
{
str=in.readLine();
a[i]=Integer.parseInt(str);
sum=sum+a[i];
}
System.out.println("sum of array ="+sum);
}
}

30
5.2 Two Dimension Array:

Two dimensional array is like a table of rows and columns.

Declaration of two dimenstion Array:

Syntax: datatype array_name[][] = new datatype[rowsize][col.size];

Eg: int a[][]= new int[3][3];

Program:

import java.io.*;

class Array
{
public static void main (String arg []) throws IOException
{
DataInputStream kb= new DataInputStream(System.in);

System.out.println("Enter row size ");


String str=kb.readLine();
int row=Integer.parseInt(str);

System.out.println("Enter column size ");


str=kb.readLine();
int col=Integer.parseInt(str);

int a[][]= new int [row][col];

int sum =0;


for (int i=0;i<row;i++)
{
for (int j=0;j<col;j++)
{
str=kb.readLine();
a[i][j]=Integer.parseInt(str);
}
}

for (int i=0;i<row;i++)


{
for (int j=0;j<col;j++)
{
System.out.print(a[i][j]+"\t");
if(i==j)
sum = sum +a[i][j];
}
System.out.println();
}
System.out.println("Sum of the diagonal " +sum);
}
}

Note: For println() and print() methods

println() cursor to next line.


print() same line.

31
6. Methods (Functions)
Functions are an integral and important part of Object programming
language. In object oriented programming languages, functions are called as
Methods

Methods are subprograms that can be developed and tested separately.

There are several advantages of Methods (block of codes) is:

1. The individual blocks will be easier to code, test and debug.


2. The same block can be reused in different parts of the programs.
3. Commonly used blocked can be collected together in a library so that they can
be used by any other program

You have already come across several such methods in earlier chapters. Some
examples are System.out.println(), readLine(), Integer.parseInt();

6.1 Method Declaration:

Syntax:

access-specifier static returntype methodName(argument list)


{
Local variable declaration;
Executable part;
return (expression);
}

6.2 Method Calling:

methodName(parameter list);

6.3 Type of Method Declarations:

1. Method with arguments and with return type


2. Method without arguments and with return type
3. Method with arguments and without return type
4. Method without arguments and without return type

Type 1:

Example for Method with arguments and with return type

Program for sum of two nos using function:

class Method1
{
public static int sum(int a, int b)
{
int c;
c=a+b;
return(c);
}

32
public static void main(String args[])
{
int k;
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
k=sum(x,y);
System.out.println(k);
int z=sum(k,x);
System.out.println(z);

}
}

Type 2:

Example for Method without arguments and with return type

class Method2
{
public static int biggest()
{
int a=10,b=20;
if(a>b)
return(a);
else
return(b);
}
public static void main(String args[])
{
int big;
big=biggest();
System.out.println("Biggest of two nos = "+big)
}
}

Type 3:

Example for Method with argument and without return type:

Write a Method for swapping of two numbers

class Method3
{
static void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
System.out.println("X = "+ x +"Y = "+ y);
}
public static void main(String args[])
{
int a=10, b=20;
swap(a,b) //calling of swap function
System.out.println("End of main function");
}
}

33
Type 4:

Example for Method without argument and with return type:

Write a Method for swapping of two numbers

class Method4
{
static void swap()
{
int a=10, b=10,t;
t=a;
a=b;
b=t;
System.out.println("A = "+ a +"B = "+ b);
}
public static void main(String args[])
{
swap() //calling of swap function
System.out.println("End of main function");
}
}

34
7. Object Oriented Programming (OOPs)
Object Oriented Programming paradigm is playing an increasingly significant
role in the design and implementation of software development. It simplifies the
development of large and complex software systems and helps in the production of
software’s,
Which is Modular, Easily understandable, Reusable, and Adaptable to
changes.
The object oriented approach centers around modeling the real world
problems in terms of objects.

7.1 OOP's Concept:

The object-oriented model is based on three important concepts namely


Encapsulation , Inheritance and Polymorphism .

Abstraction: is a feature that makes only the necessary details available to the
user.

Eg: Consider a TV. When you watch TV, you are not bothered about the inner details
of the parts. You ignore the various complex individual parts that forms the TV.

7.1.1 Encapsulation: is a mechanism that binds together code and the data where
code manipulates the data, and keep both safe from outside interference and
misuse.

Encapsualtion is a protective wall that prevents the code and data from beging
randomly accessed by other code defined outside the wall.

The concept of hiding the non-essential details from the user is called Encapsulation.

Eg: Consider an automobile. The information about the engine is hidden from the
user.

7.1.2 Inheritance: is a process of creating a New Class with the properties of an


Existing Class, along with the additional characteristics unique to the new class. The
new class obtains the properties of the exising class.

7.1.3 Polymorphism: is a feature that allows one Interface to be used for a general
class of action. More generally, the concept of polymorphism is often expressed
by the phrase "one interface, multiple methods". This means one common
name for a method with different parameters.

In Java , there are two types of polymorphism:

▪ Method Overloading
▪ Method Overridding

7.2 Class

A class is a prototype that defines the Data and Code common to all objects
of a particular kind.
A class defines the structure and behaviour of the objects. The elements of a
class are called members. Code and data are two important elements of a class.

35
The code that acts on the data is called method. The data defined by the calss is
called variables.

Class Class Arith

Data Data

Data1 int a

Data2 int b

Data3 int c

Methods Methods

Method1() sum()

Method2() sub()

Method3() mul()

Class grouping data and Methods

7.2.1 Class Declaration.

Syntax:

class <class name>


{
access speciefier

variables (instance variable)


+
functions (methods)
}

7.2.2 Declaring Instance Variable:

Syntax:

<access-specifier> <data-type> var1,var2....;

access – specifier – public


- private
- protected.

Example for Create a Simple Class Box

public class Box


{
public double width;
public double height;
public double depth;
}

36
7.3 Objects as Instance:

An object is an instance of class or copy of class or Real time entity of a


class.
It is a variable, which is used to access the instance variables and methods of
class

7.3.1 The new Operator

The new operator creates a single instance of a named class and returns a
reference to that object.

Syntax:
class-name Objectname=new class-name( );

Eg: Box mybox = new Box();

This statement combines the two steps just described. It can be rewritten like
this to show each step clearly.

Box mybox; //declare reference to object

mybox = new Box(); //allocate memory for a box object

Statement Effect

Box null
mybox; mybox
Width
mybox = new Box();
Height
mybox
Depth

Box object
Declaring an object of type
box

7.3.2 Dot Operator (is use to access instance variables and methods):

The dot notation is used to obtain the value of the instance variable. It has
two parts namely, the object on the left side of the dot and the variable on the right
side of the dot. Dot expression are evaluated from left to right.

Syntax:
<object Reference> . <variable name>
<objectReference> . <method name>

37
Program: Example for class using Instance variables only.

class Box
{
double width;
double height;
double depth; //instance variables
}

class BoxDemo
{
public static void main(String args[])
{
Box mybox =new Box( ); //instance of class
double vol; //local variable

//assign values to mybox’s instance variables


mybox.width =10;
mybox.height=20;
mybox.depth=15;

//compute volume of box


vol = mybox.width+mybox.height+mybox.depth;
System.out.println(“Volume is “+vol);

}
}

OUTPUT: 45

7.3.3 Assigning object as Reference Variables

Object reference variables act differently than you might expect when an
assignment takes places. For example, what do you think the following fragment
does?

Although b1 and b2 both refer to Width


the same object, they are not linked in
any other way, for example: a
b1 Height
subsequent assignment to b1 will simply
unhook b1 from the original object Depth
without affecting the object or affecting
b2. b2

For Example:

Box b1 = new Box();


Box b2 = b1;
// ……..
b1=null;

Here, b1 has been set to null, but b2 still points to the original object.

Note: when you assign one object reference variable to another object reference
variable you are not creating a copy of the object, you are only making a copy
of reference

38
7.4 Methods:
7.4.1 Introduction to Methods

Class usually consists of two things: Instance variable and Methods. The
topic of methods is a large one because java gives them so much power and
flexibility.

7.4.2 Declaring functions (methods);

Syntax:
<access specifier><return-type>method-name(argument list)
{
local declaration;
function body;
return statement;
}

7.5 Access Specifier:


Access control is the process of controlling visibility of a variable or method.
When a method or variable is visible to another class, its method can reference the
method or variable.

7.5.1 public:

The members, which are declared as a public, can be accessed by any method
in the outside of the class.

Program: Example for Class using public data member only

class Item
{
public int a,b,c;

class MethodDemo
{
public static void main(String args[])
{
Item t=new Item();
int k; //local variable
t.a=10;
t.b=20;
t.c=t.a+t.b;
System.out.println(t.c);
}
}

39
Program: Example for Public Methods and Public instance variables in a class:

class PublicVar
{
public int a,b,c;
public int sum(int x, int y)
{
int z;
z=x+y;
return(z);
}
}
class MethodVariable
{
public static void main(String args[])
{
PublicVar p=new PublicVar( );
p.a=20;
p.b=10;
p.c=p.sum(p.a,p.b);
System.out.println(p.c);
}
}

7.5.2 Private:

A Member Data or Methods can only be accessed by the methods of the same
class. The private instance variable is not accessible from the outside of the class.

Program :

class PrivateVar
{
private int a,b,c;
}
class PrivateDemo
{
public static void main(String args[])
{
PrivateVar p=new PrivateVar();
p.a=20;
p.b=10;
p.c=p.a+p.b;
System.out.println(p.c);
}
}

In this program, it gives Six Errors as the variables are declared as private in
the class PrivateVar and it cannot be accessed by the PrivateDemo class.

40
Program :

class Item
{
private int a,b,c;
public void sum( )
{
a=20;b=10;
c=a+b;
System.out.println ( c );
}
}

class PrivateAccess
{
public static void main(String args[])
{
Item t=new Item( );
t.sum( );
}
}

Program : Calling Private Method via public method

class Item
{
private int sum(int a, int b)
{
int c;
c=a+b;
return ( c );
}
public void arith(int x, int y)
{
int z;
z=sum(x,y);
System.out.println(z);
}
}
class PrivateAccess1
{
public static void main (String args[])
{
Item t=new Item( );
t.arith(20,10);
}
}

7.4.3 Protected

This specifier is a relationship between a class and its present and future
subclasses. The subclasses are closer to the parent class than any other class. This
level gives more protection and narrows visibility.

The protected access specifiers have been deal with Inheritance and packages
in java.

Note: In Java, default access specifies is NoAccessSpecifier, not a PUBLIC.

41
7.5 Static Keyword

The static modifier can be applied to variables, methods and even to a strange
kind of code that is not a part of a method. Static features are associated with a
class rather than being associated with an individual instance of a class

7.5.1 Static variable [To save memory]

To make a variable as static , the variable name should be preceded by the


keyword static.
To access the static variable, we can use class name instead of using its
object, means that there is only one variable, no matter how many instances of class
might exist at any particular moment.

There are two way to reference a static variable:

1. Via a reference to any instance(object) of the class


2. Via the classname.

Program :

class item
{
public static int a;//class variable
}
class staticVar
{
public static void main(String args[])
{
item t= new item();
item t1= new item();
t.a=10;
t1.a=20;
System.out.println(t.a);
System.out.println(t1.a);

}
}

7.6 Static Method (Class Methods) :

Class methods, like class variables, are available to instance of the class and
can be made available to other classes. Class method can be used anywhere
regardless of whether an instance of the class exist or not. Class method is defined
as given below

Syntax:

static <return type> <methodname>( type arg1, type arg2, …....)


{
<set of statements>
}

42
Methods declared as static have several restrictions:

▪ They can only call other static methods


▪ They must only access static data.
▪ They cannot refer to this or super in any way( the keyword super relate to
inheritance )

Example for Static method :

class UseStatic
{
static int a=3;
static int b;
static void meth(int x)
{
System.out.println (“ X = “ + x);
System.out.println (“ a = “ + a);
System.out.println (“ b = “ + b);
}
static //static block
{
System.out.println (“Static block initialized”);
b=a*4;
}

public static void main(String args[])


{
meth(42);
}
}

OUTPUT:
Static block initialised
X = 42
a=3
b = 12

As soon as the UseStatic class is loaded, all of the static statements are run.
First a is set to 3 , then the static block executes(printing a message), and finally, b
is initialized to a*4 or 12. the main() is called, which calls meth(), passing 42 to x.

The static keyword indicates that it is a class method and can be accessed
without creating an object. The class methods, unlike instance methods, are not
allowed to use instance variables, as these method do not operate on an object.

43
7.7 Method Overloading:

In a class more than one method can have same method name with different
arguments. All the methods distinct in three ways.

1. The number of arguments should be distinct.


2. Types of argument should be distinct.
3. Sequence of argument should be distinct.

Program:

class A
{
public int sum(int a,int b)
{
return(a+b);
}
public int sum(int a,int b,int c)
{
return(a+b+c);
}
public double sum(int a, double b)
{
return(a+b);
}
public double sum(double a, int b)
{
return(a+b);
}
}

class MethodOverDemo
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.sum(20.4,30));
System.out.println(obj.sum(10,20));
System.out.println(obj.sum(10,20,30));
}
}

44
7.8 Constructor:

A Constructor is a special kind method that determines how an object is


initialized when created.

Rules for constructing Constructor:-

1. Constructor name and class name must be equal.


2. Constructor should be in public
3. Constructor has no return type. But it may be have argument.
4. When we create an object of the class, constructor will be invoke
automatically.
5. Constructors can also be Overloaded.

When the keyword new is used to create an instance of class, java allocates
memory for the object, initializes the instance variable and calls the constructor
methods.

7.8.1 Default Constructor:

Every class in java by default has a default constructor that does not take
any argument and the body of it does not have any statements.

Program:

class Const
{
public Const()//default constructor
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println( c );
}
}
class ConstDemo
{
public static void main(String args[])
{
Const p=new Const();
}
}

7.8.2 Parameterised Constructor :


Program:

class ConstPara
{
ConstPara(int a,int b)//parameterised constructor
{
int c;
c=a+b;
System.out.println( c );
}
}
class ConstParaDemo
{

45
public static void main(String args[])
{
ConstPara p=new ConstPara(30,10);
}
}

7.8.3 Overloading Constructors

Constructors can also take varying numbers and types of parameters. This
enables creation of objects with the properties required.

Program :

/* Here, Box defines three constructors to initialize


the dimensions of a box various ways.
*/
class Box
{
double width;
double height;
double depth;

// constructor used when all dimensions specified

Box(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified

Box()
{
width = -1;
height = -1;
depth = -1;
}

// constructor used when cube is created

Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);

46
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

7.8.4 Using object as Parameters

So far we have only been using simple data types as parameters to methods.
However, it is both correct and common to pass object to methods. For example,
consider the following simple program

Program :

// Objects may be passed to methods.


class Test
{
int a, b;

Test(int i, int j)
{
a = i;
b = j;
}

// return true if o is equal to the invoking object

boolean equals(Test o)
{
System.out.println("o.a = "+ o.a + "a = " + a);
System.out.println("o.b = "+ o.b + "b = " + b);

if(o.a == a && o.b == b)


return true;
else
return false;
}
}

class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, 22);

47
System.out.println("ob1 == ob2: " + ob1.equals(ob2));

System.out.println("ob1 == ob3: " + ob1.equals(ob3));


}
}

7.8.6 Returning object:

A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen() method returns an object in
which the value of a is ten greater than it is in the invoking object.

Program :

// Returning an object.
class Test
{
int a;

Test(int i)
{
a = i;
}

Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}

class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;

ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}

48
8. Inheritance
It is a process of creating new class from an existing class. The existing class
is called as “Base class (or) super class”. The newly created class is called as
“subclass or derived class”.

Syntax to create sub-class:-

class <sub-class-name> extends <super-class-name>


{
instance variable;
+
methods();
}

Type of Inheritance:-

1) Single Inheritance.
2) MultiLevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance ( for Interface only)

8.1 Single Inheritance :

It is a process of creating one subclass from one base class.

Program:

class A
{
int x,y;
public int sum(int a,int b)
{
x=a;
y=b;
return(x+y);
}
}
class B extends A
{
public int mul(int a, int b)
{
x=a;
y=b;
return(x*y);
}
}
class Single
{
public static void main(String args[])
{
B obj=new B();
System.out.println(obj.sum(20,10));
System.out.println(obj.mul(20,10));
}
}
using object of derived (sub(class)) we can access all the properties of super class.

49
8.2 Multilevel Inheritance :

It is a process of creating a sub class from another subclass.

Program :
class A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class B extends A
{
public int diff(int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int mul(int a,int b)
{
return(a*b);
}
}
class D extends C
{
public int div(int a, int b)
{
return(a/b);
}
}
class Multilevel
{
public static void main(String args[])
{
D d= new D();
System.out.println(d.div(20,10));
System.out.println(d.sum(20,10));
System.out.println(d.diff(20,10));
System.out.println(d.mul(20,10));
}
}

8.3 When Constructors are called :

class A
{
A()
{
System.out.println("A is called ");
}
}
class B extends A
{
B()
{
System.out.println("B is called ");
}

50
}

class C extends B
{
C()
{
System.out.println("C is called ");
}
}
class CallCons
{
public static void main(String arg[])
{
C c = new C();
}
}

OUTPUT:
A is called
B is called
C is called

8.4 Super Keyword: Super keyword are used to access data and code of a
super class.

Sytax: super.variable
super.method();

class main
{
int i=12;
}
class sub extends main
{
int i=17;

void display()
{
System.out.println("I = "+i);
System.out.println("Super.i = "+super.i);
}
}
class Super
{
public static void main(String arg[])
{
sub s = new sub()
s.display();
}
}

51
Example 2:

class Super
{
int i;
}
class sub extends Super
{
int i;
sub(int x, int y)
{
i=x;
super.i=y;
}
void display()
{
System.out.println("I in subclass = "+i);
System.out.println("I in superclass = "+super.i);
}
}
class CallSuper
{
public static void main(String arg[])
{
sub s = new sub(10,20);
s.display();
}
}

8.5 Calling Super Constructor with super keyword:


Class Super_Cons
{
int i,j;
void input(int x, int y)
{
i=x;
j=y;
}
}

class sub extends Super_Cons


{
int k;
sub(int x, int y, int z)
{
k=z;
super.input(x,y);

}
void display()
{
System.out.println("I = "+i+"\nJ = "+j);
System.out.println("K = "+k);
}
}
class CallSuper
{
public static void main(String arg[])
{

52
sub s = new sub(10,20,30);
s.display();
}
}

8.6 Multiple Inheritance :

It is a process of creating a sub class from more than one super class. Java
does not support for multiple inheritance for class

We can create Multiple Inheritance using Interfaces in Java.

8.7 Method Overriding:

In a multilevel inheritance, when a method in a subclass has the same name


and type signature as a method in its super class, then the method in subclass is said
to override the method in the superclass.

class A
{
Public int arith(int a,int b)
{
return(a+b);
}

}
class B extends A
{
public int arith(int a,int b)
{
return(a-b);
}
}
class c extends B
{
public int arith(int a, int b)
{
return(a*b);
}
}
class D extends C
{
public int arith(int a,int b)
{
return(a/b);
}
}
class Overriding
{
public static void main(String args[])
{
A p1; //(#To create Object reference)
p1=new B();
System.out.println(p1.arith(20,10));

p1=new C();
System.out.println(p1.arith(20,10));
p1=new D();

53
System.out.println(p1.arith(20,10));
p1=new A();
System.out.println(p1.arith(20,10));

}
}

OUTPUT : 10 200 2 30

8.8 Abstract Class

There are situations in which we will want to define a super class that declares
the structure of a given abstraction without providing a complete implementation of
every altered.

You can require that certain method to be overwrite in the future

To declare an abstract method, the function declaration to be preceeded by


abstract keyword. Any class that contains one or more abstract methods must
also be declared as abstract class.

Note : Abstract Class Cannot be instantiate (create object.)

abstract class A
{
abstract public int arith(int a, int b);

public int sum(int a,int b)


{
return (a+b);
}
}

class B extends A
{
public int arith (int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int arith(int a,int b)
{
return(a*b);
}
}
class D extends C
{
public int arith(int a,int b)
{
return(a/b);
}
}
class AbstractDemo
{
public static void main(String args[])
{
A p;

54
p=new B();
System.out.println(p.arith(10,20));
p=new C();
System.out.println(p.arith(10,20));
p=new D();
System.out.println(p.arith(10,2));
}
}
OUTPUT:
10
200
2

8.9 Final Modifiers

8.9.1 Final variable

If we make a variable as final, the variable will become a constant. In this


case we can’t change the final value.

class FinalVar
{
public static void main(String args[])
{
final int a=10;
a=a+5;//error
System.out.println(a);
}
}
The above program will give a error message.

Error Message : cannot assign a value to final variable a

8.9.2 Final Method:

Final method is used to put a lock on the method to prevent any inheriting
class from changing its meaning. This is done for design reasons when you want to
make sure that a method’s behavior is retained during inheritance and cannot be
overwritten.

class A
{
public int arith(int a,int b)
{
return(a+b);
}
}
class B extends A
{
final public int arith(int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int arith(int a, int b)
{
return(a*b);

55
}
}
class D extends C
{
public int arith(int a, int b)
{
return(a/b);
}
}
class FinalMethod
{
public static void main(String args[])
{
A p;
p=new B();
System.out.println(p.arith(10,20));
p=new C();
System.out.println(p.arith(10,20));
p=new D();
System.out.println(p.arith(10,2));
System.out.println(P4.arith(20,10));
}
}

The above program gives 2 errors.

Class FinalMethod of arith(int,int) in class C cannot override arith(int,int) in class B


overridden method is final

8.9.3 Final Class:

If we make a class as final, we can’t create a sub class from final class.

final class A
{
public int arith(int a,int b)
{
return(a+b);
}
}

class B extends A
{
public int arith(int a, int b)
{
return(a+b);
}
}

Error : The above program shows one error as B extends A.

56
8.10 ‘this’ keyword

The this keyword is used inside any instance method to refer to the current
object. The value of this refers to the object on which the current method has been
called. The this keyword can be used where a reference to an object of the current
class type is required.

Methods declared with the keyword static (class methods) cannot use this.

Program :

class A
{
private int a=10,b=20,c;
public void read()
{
this.a=25;
this.b=45;
}
public void sum()
{
c=a+b;
System.out.println(c);
}
}
class ThisDemo
{
public static void main(String args[])
{
A P1= new A ( ) ;
A P2= new A ( );
P1.read( );
P1.sum( );
P2.sum( );
}
}
OUTPUT :
70
30

57
9. Interface:
An Interface is a collection of methods without implementation. An
interface can also include variable declaration.

Interfaces are a close cousin to classes and their declaration resembling class
declarations.

9.1 Defining an interface:

interface interface-name
{
variables+methods;
}

9.2 Implementing interfaces:

Once an interface has been defined, one or more classes can implement that
interfaces. To implement the interface, include the implements keyword in a class
definition and then create a method defined by the interface.

class class-name implements interface-name


{

Syntax for creating an object:

interface-name reference= new class-name( );

Program :

interface A
{
public int sum(int a, int b);
}
class B implements A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class InterfaceDemo1
{
public static void main(String args[])
{
B P=new B();
System.out.println(P.sum(20,10));
}
}

58
9.3 Multiple inheritance for creating Interface:

Note: If a class implements more than one interface, the interfaces are separated, in
this case we will get multiple inheritance.

Program:

interface A
{
public int sum(int a, int b);
}
interface B
{
public int mul(int a,int b);
}
interface C
{
public int diff(int a,int b);
}

class D implements A,B,C


{
public int sum(int a,int b)
{
return(a+b);
}
public int mul(int a, int b)
{
return(a*b);
}
public int diff(int a,int b)
{
return(a-b);
}
}
class InterfaceDemo2
{
public static void main (String args[])
{
D P=new D( );
System.out.println(P.sum(20,10));
System.out.println(P.mul(20,10));
System.out.println(P.diff(20,10));

}
}

9.4 Extending Interface

One interface can inherit the another interface by using the keyword extends.

The syntax is same as inheritance of class.

interface A
{
public int sum(int a,int b);
}
interface B extends A
{
public int mul(int a,int b);

59
}
interface C extends B
{
public int diff (int a , int b);
}
class D implements C
{
public int sum(int a,int b)
{
return (a+b);
}
public int mul(int a,int b)
{
return(a-b);
}
public int diff(int a,int b)
{
return(a-b);
}

}
class InterfaceDemo3
{
public static void main(String args[])
{
D P=new D( );

System.out.println(P.sum(20,10));
System.out.println(P.mul(20,10));
System.out.println(P.diff(20,10));
}
}

we can use interface to import shared constants into multiple constant by


simple declaring an interface that contains variables which are initialize to the
required value.

interface A
{
public int a=10;
public int b=20;
public int sum(int a, int b);
}
class B implements A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class InterfaceDemo4
{
public static void main(String args[])
{
A P=new B();
System.out.println(P.sum(P.a,P.b));
}
}

60
61
10. Exception Handling
10.1 Introduction:

An exception is an event that occurs during the execution of a program that


disturbs the normal flow of instructions
Exceptions are erroneous events like Division by Zero, Opening a File that
Does Not Exist etc.
A Java exception is an object describes an exceptional condition that has
occurred in a piece of code. Error handling becomes necessarily when you develop
applications that need to cause of unexpected situations.

Advantages:
1. Separating Error Handling code from “Regular” code
2. Propagating Errors up the Call Stack
3. Grouping Error types and Error Differentiation

Class Hierarchy:

Object

Throwable

Error Exception

IOException RuntimeException

10.2 Types of exceptions:

10.2.1 Arithmetic Exception:

This exception is generated by Division by Zero Error.

class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42/d;
System.out.println(a);
System.out.println("End of program");
}
}
When a java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception. This cause the
excution of above program to stop, because once an exception has been throwns, it
must be caught by an exception handler and dealt with immediately.

In the example, we haven't supplied any exception handlers of our own, so


the exception is caught by the default handler by the java-runtime system.

62
Any exception that is caught by your program will ultimately processed by the
default handler. Hence default handler display a string describig the exception,

Java.lang.ArithmeticExcepiton : / by zero

Using try and catch

Althoug the default exception handler provided by the java run-time system is
useful for debugging, you will usually want to handle an exception yourself. Doing so
provides two benefits.

▪ First, it allows you fix the error.


▪ Second, it prevent the program from automatically terminating

To guard against the handle a run-time error, simply enclose the code that you want
to monitor inside a try block. Immediately following the try block, include a catch
clause that specifies the exception type that you wish to catch.

Program:

class ArithException
{
public static void main(String args[])
{
int a,b,c;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
System.out.println( c );
}
catch(ArithmeticException e)
{

System.out.println(“Exception error as zero divide


error”);
c=0;
}
System.out.println("End of program");
}
}

OUTPUT :
C:\> Java ArithException 100 0
Zero divide error.

63
Program:

import java.util.*;
class HandleError
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();

for(int i=0; i<10; i++)


{
try
{
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}

10.2.2 ArrayIndexOutOf BoundsException:

It is generated when array index is invalid.

class ArrayException
{
public static void main(String arg[])
{
try
{
int a[]=new int[5];
a[0]=25;
a[1]=30;
a[2]=14;
a[3]=15;
a[4]=100;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
System.out.println(a[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“You cannot access the value of
a[5]” + e);
}
}
}

64
c:\> java ArrayException

OUTPUT :
25
30
14
15
100
We cannot access the value of a[5].

10.2.3 NegativeArraySize Exception:

It is generated when array size is negative.

class NegativeException
{
public static void main(String args[])
{
try
{
int a[]=new int [-5]
a[0]=26;
a[1]=14;
a[2]=15;
a[3]=40;
a[4]=100;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
}
catch(NegativeArraySizeException e)
{
System.out.println(“Array size should be positive
integer”);
}
}
}

c:\> java NegativeException

OUTPUT:
Array size should be a positive(+ve) no.(number)

10.2.4 NumberFormat Exception:

This exception is generated when the string passed is not a number.

class NumberException
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);

65
c=a/b;
System.out.println(c);
}
catch(NumberFormatException e)
{
System.out.println(“Argument should contain only
numeric values”);
}
}
}
OUTPUT :
Java NumberException 100 er

10.2.5 FileNotFoundException :

It is generated when a requested file is not found


.
10.2.6 SQLException :

It is generated when error occurs during a database access.

10.2.7 UnKnownHostException :

It is generated when the host cannot be located.

10.4 Multiple Catch block:

More than one exception should be raised by a single piece of code. To


handle this type of situation, you can specify two or more catch blocks, each catch as
different types of exception. When an exception is thrown, each catch statement is
expected in order to print the messages. If the exception does not find a matching
catch block, it is passed to the default handles.

class MultiCatch
{
public static void main(String args[])
{
int f=0;
try
{

int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println("Result = "+c);
}
catch(ArithmeticException e)
{
System.out.println("Zero divide error");
f=1;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Enter minimum two
arguements");
f=1;
}
catch(NumberFormatException e)
{

66
System.out.println("Cannot convert string to
integer");
f=1;
}
if(f==0)
System.out.println("Your Transcation is
completed ");
else
System.out.println("Your Transcation is not
completed ");
}
}

Note: Instead of having multiple catch block, we can use single catch block by
specifying simply Exception.

class SimpleException
{
try
{
}
catch (Exception e)
{
System.out.println(“Error”);
}
}
10.5 Throw:

It is possible to throw an exception explicitly using throw statement.

Syntax:

throw new Exception-name(String);

class ThrowDemo
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(b==0)
throw new ArithmeticException();
else
{
c=a/b;
System.out.println( c );
}
}
catch(ArithmeticException e)
{
System.out.println(“zero divide error”);
System.out.println("Result ="+c);
}
}

67
10.6 Throws:

If a method is capable of causing an exception that it does not handle, it must


specify this behavior so that callers of the method can guard themselves
against the exception. You do this by including a throws clauses in the method’s
`declaration.

Syntax:

type method_name(parameter-list) throws exception-list


{
//body of method
}

Program 1: (without throws )

class WithoutThrows
{
public static void div(int a,int b)
{

int c;
c=a/b;
System.out.println( c );
}
public static void main(String args[])
{
div(20,0);
}
}

Program : 2 (with throws Exception)

class WithThrows
{
public static void div(int a,int b)
throws ArithmeticException
{
int c;
c=a/b;
System.out.println("sum ="+c );
}
public static void main(String args[])
{
try
{
div(20,0);

}
catch(ArithmeticException e)
{
System.out.println("Error "+e);
}
}
}

68
10.7 Finally:

When an exception is generated in program, control will be goto catch block


and it will stop the process sometimes it may be necessary to the program to stop
certain activities before termination. Finally creates a block of code that will be
executed after a try or catch block has completed.

class FinallyDemo
{
public static void main(String args[])
{
int a=0,b=0,c=0;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;

}
catch(ArithmeticException e)
{
c=0;
System.out.println(“Error”+e);
}
finally
{

System.out.println( c );
}
}

10.8 Creating User-Defined Exception:

Customized exceptions are necessary to handle abnormal conditions of applications


created by the user. The advantage of creating such an exception class is that,
according to situation defined by the user an exception can be thrown.

Steps to create user defined exception.

1. Create a subclass of Exception.


2. Inside the subclass define the constructor.
3. From the main program throw the above exception.

Program:

import java.lang.*;

class CheckDivisor extends Exception


{
CheckDivisor ()
{
System.out.println("MY CheckDivisor Error is caught ");
}
}
class MyExceptionDemo
{
public static void main(String args[])
{
try

69
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(b== 0)
throw new CheckDivisor();
else
{
c=a/b;
System.out.println( c);
}
}
catch(CheckDivisor e)
{
System.out.println(“Error”+e);
}
}
}

70
11. Packages:
One of the biggest assets of JAVA is a rich library set is available. These libraries
include several pre-return methods and classes that can be used by everybody.
These libraries include classes and methods for IO operations, Mathematical
operations, Networking, Image processing and many more activities.
Depending on their functions, the classes in these libraries are grouped together &
called as packages.

11.1 The import statement:

You can use java packages in a program by using import Keyword.

1. import <package name>.*;


2. import <package name>.class name;
In the above syntax the name of a package is followed either by an
asterisk or the name of class name in a package.

The * at the end of the import statement indicates that all the classes of a given
package have to be imported. The second statement indicates that only the specified
class from the given package as to be imported. You can therefore import a
particular class or all the classes of a package using the import statement.

11.2 Types of packages:

java.lang (default package, java can automatically import to the program)


java.util – Linkedlist,Stack, Vector, Date, etc.,
java.io – Basic IO operations and File handling
java.net – Network Programming.
java.applet – Creating Web Pages
java.awt – Label ,Button, Checkbox, Listbox, Menus…
java.sql – Connecting to database like Oracle,MS-SQL,MS-Access

i. java.lang:

The java.lang package is one of the most important packages in Java. It provides
a no. of classes and interfaces that are fundamental to java programming.

The java.lang package provides classes and interfaces that implement


fundamental java objects. It is the only package in java automatically imported.

java.lang includes following classes:

Boolean Long String


Byte Math StringBuffer
Character Number System
Class Object Thread
ClassLoader Package ThreadGroup
Compiler Process ThreadLocal
Double Runtime Throwable
Float RuntimePermission Void
InheritableThreadLocal SecurityManager
Integer Short

71
Java.lang defines the following interfaces:

▪ Cloneable
▪ Comparable
▪ Runnable

11.3 Wrapper Classes (Contains all Static Methods, ie we can access


via class name).

11.3.1 The Byte class:

1. parseByte(String str):-

Returns the byte equivalent to the no. contained in the string.

11.3.2 The Integer class

a. parseInt (string str):

It returns the integer equivalent of a number contained in the String.

Program :

class IntegerClass
{
public static void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.println( c );
}
}

OUTPUT:
10
20
30
b. toBinaryString(int num):

It returns a String that contains a binary equivalent of num.

Program:

class BinrayDemo
{
public static void main(String args[])
{
int num;
num = Integer.parseInt(args[0]);
System.out.println(Integer.toBinaryString(num));
}
}

OUTPUT: c:\> java BinaryDemo 23

10111

72
c. toHexString(int num):

It returns a String that contains a Hexa equivalent of num.

System.out.println(Integer.toHexString(num));

OUTPUT: 30
1e

d. ToOctalString (int num):-

It returns a String that contains a Octal equivalent of num.

System.out.println(Integer.toOctalString(num));

Ouput 30
36

11.3.3 The Long class:

long l = Long.parseLong(String str):

It returns a long equivalent of the number contained in the string.

Note:

The Long Class also we can use to Binary String, toHexString, toOctalString
functions.

11.3.4 The Float class:

float f=Float.parseFloat(String s);

It returns a float value of the given String.

Program:

class FloatClass
{
public static void main(String args[])
{
float a,b,c;
a=Float.parseFloat(args[0]);
b=Float.parseFloat(args[1]);
c=a+b;
System.out.println( c );
}
}

OUTPUT :
16.3
30.5

73
11.3.5 The Double class:

double=Double.parseDouble(String s);

It returns a double value of the given String.

11.4 Math class:


The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root, and trigonometric functions.

java.lang.Object
java.lang.Math
public final class Math extends Object

Method in Math class (all Static methods)

a) Sqrt( ) :

It returns the square root of given no.

class SqrtDemo
{
public static void main(String args[])
{
double a,b;
a=Double.parseDouble(args[0]);
b=Math.sqrt(a);
System.out.println(b);
}
}

OUTPUT:
64
8.0

b) abs():

It returns the absolute value of given no.

OUTPUT
-23
23

c) ceil():

It returns the smallest integer to that is greater or equal to n.

OUTPUT
23.123
24

74
d) floor():

It returns the largest integer no. that are lesser than or equal to n.

Ouput
23.123
23

e) max(x,y):

It returns the maximum of x & y.

class MaxDemo
{
public static void main(String args[])
{
double a,b,c;
a=Double.parseDouble(String args[0])
b=Double.parseDouble(String args[1])
c=Math.max(a,b);
System.out.println( c );
}
}

OUTPUT:
10 20
20

f) min(x,y):

It returns the minimum of x,y.

g) exp(x):

It returns the exponential value of a given number.


X=0 e0=1
ex=1+x/1!+x2/2!..

h) log(x):
It returns the natural logarithm of given no.

i) sin(n):
It returns the sine of the angle specified by n in radians.

j) cos(n):
It returns the cos of the angle specified by n in radian.

k) tan(n):
It returns the tangent of the angle specified by n in radians.

75
Program:

class SinDemo
{
public static void main(String args[])
{
double a,b;
a=Double.parseDouble(args[0]);
a=a*3.14/180;
b=Math.sin(a);
System.out.println(b);
}
}

Degree to Radian:
Radian to degree 180/ 
/180

1. asin( n)→It returns the sine inverse value.


2. acos(n)→It returns the cosine inverse value.
3. atan(n)→It returns the tan inverse value.

b=Math.asin(a);
b=b*/180 

toRadians( ):

It converts degree to radian.

class RadianDemo
{
public static void main(String args[])
{
double a,b
a=Double.parseDouble(args[0]);
a=Math.toRadians(a);
b=Math.sin(a);
System.out.println(n);
}
}

toDegrees( ):

It converts radian to degree.

76
11.5 Character Class:

1. isDigit(ch):

It is used to check whether the given Number is Number or not.

Program:

class DigitDemo
{
public static void main(String args[])
{
char ch=’a’;
System.out.println(Character.isDigit(ch));
}
}
OUTPUT: false

2. isLetter(ch) : check the character is Letter or not. (A..Z), (a..z)


3. isLetterOrDigit(ch) : checks both Letter and characters.
4. isLowerCase(ch) : check whether the character is lower
5. isUpperCase(ch) : check whether the character is uppercase.
6. isSpaceChar(ch) : check whether the character is space.
7. toLowerCase(ch) : To convert into lowercase.
8. toUpperCase(ch) : It converts Lowercase into uppercase letter.

77
12. String Class

12.1 Introduction :

A combination of characters is a string. Strings are instances of the class String.


They are real objects, and hence enable combination, testing and modification.

When a String literal is used in the program, java automatically creates instances of
the String class. String are unusual in this respect.

Program:

class StringDemo
{
public static void main(String args[])
{
String str=new String("World computers");
//or
String str1=”World computer centre”;
System.out.println(str);
System.out.println(str1);
}
}

12.2 length( ): It returns a length of a string.

class StringLength
{
public static void main(String args[])
{
String str = ”World computer centre”;
System.out.println(str.length( ));
}
}

OUTPUT: 21.

12.3 indexOf(char):

This is method is used to search a String for a particular character & returns first
occurance of the character in the string. It returns –1 if the character is not found in
the string. It seen case sensitive.

{
String str= ”World Computer Centre”;
System.out.println (str.indexOf(‘o’));
}

OUPUT: 7.

78
12.4 lastIndexOf( char):

It returns the index of the last occurrence of the char in the string. It returns –1 if
the character is not found in the string.

12.5 indexOf(String str):

The method searches for a string in the current object and returns the index value of
the first characters.

{
String str=”World Computer Centre”;
System.out.println(str.indexOf(“put”));
}
OUPUT: 9

12.6 charAt ( index )

This method returns the character at the index

{
String str = “World computer centre “
System.out.println(str.charAt(3));
}

OUTPUT : a

12.7 equals():

To check whether the 2 Strings are equal or not.

class EqualDemo
{
public static void main(String args[])
{
String str1=”World computer”;
String str2=”World computer”;
System.out.println(str1.equals(str2));
}
}

OUTPUT : True. (according to Boolean expression).

This method compare the strings with current object. It returns true if they are
equal and false if they are not equal.

12.8 equalsIgnoreCase()

This method is very similar to equals method, but as the name suggest, it ignores
the cases of the characters.

12.9 startsWith(startstring)

This method checks the current object starts with the same sequence of characters
as the string and returns true if it

79
class Startwith
{
public static void main(String args[])
{
String str = “World computer”;
System.out.println(str.startsWith(“World”));
}
}
OUPUT : true.

12.10 endsWith(endstring )

It returns true if the current object ends with given string.

12.11 substring(i)

This method extracts a substring containing all the characters from the current object
starting from index ‘i’ till the end.
{
String str=”World computer”;
System.out.println(str.substring(7));
}
OUTPUT : computer

12.12 substring(i,j)

This method extracts a Substring starting from the index position ‘i’ up till the index
position j (Not including the upper in the jth position)

System.out.println(str.substring(7,10));

OUTPUT: omp

12.13 toLowerCase():

This method is used to change a string in uppercase to lowercase.

{
String str=”WORLD COMPUTER CETNRE”;
System.out.println(str.toLowerCase());
}

12.14 toUpperCase( ):

This method is used to change a String in lower to uppercase.

System.out.println(str.toUpperCase());

12.15 replace(ch1,ch2)

This method is used to replace all occurance of ch1, with another character ch2 in the
current object.

{
System.out.println(“World Computer Centre”);
System.out.println(Str.replace(‘a’,’e’));
}
OUTPUT : peler computer center

80
class Str
{
public static void main(String args[])
{
String str=new String("World computer");
//or
String str1="World computer";
System.out.println(str);
System.out.println(str1);
System.out.println("Length = "+str.length( ));
System.out.println ("Index Of o ="+str.indexOf('o'));
System.out.println("Index of put = "+str.indexOf("put"));
System.out.println("char at pos. 3 ="+str.charAt(3));
System.out.println("Str = str1 ="+str.equals(str1));
System.out.println("ignore Str = str1 ="+str.equalsIgnoreCase(str1));
System.out.println("Strat at World ="+str.startsWith("World"));
System.out.println("sub string of 7 = "+str.substring(7));
System.out.println("sub string of 7 to 10 = "+str.substring(7,10));
System.out.println("Lower Case = "+str.toLowerCase());
System.out.println("Upper case = "+str.toUpperCase());
System.out.println("Replace a to e = "+str.replace('a','e'));
System.out.println(str);
}
}

81
12.2 StringBuffer Class:
The original String remains unchanged during all the string manipulations performed
on it.

This is because, in Java, object of the String class, once created cannot be changed
(immutable).

In java StringBuffer class , the changes will affect the original string.

Program:

class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer(“World computer”);
System.out.println(str);
}
}
OUTPUT : World computer

12.2.1 length( )

This method returns the no. of characters in the buffer.

{
StringBuffer str=new StringBuffer(“World computer centre”);
System.out.println(str.length( ))
}

OUTPUT : 21

12.2.2 charAt(i)

It returns the character at the index i.


System.out.println(str.charAt(2))

0OUTPUT : World

12.2.3 append(char)

The method is used to add a character ‘ch’ to the String buffer.


{
StringBuffer str=new StringBuffer(“World computer”);
System.out.println(str.append(‘s’));
System.out.println(str);
}
OUTPUT : World computers

12.2.4 append(String str)

This method is used to add a string.

82
System.out.println(str.append("centre"));
System.out.println(str);
}
OUTPUT : World computers centre

12.2.5 insert(i,ch)

This method is used to insert a character ‘ch’ at the index position ‘i’.
{
StringBuffer str;
System.out.println(str.insert(7,’r’));
}

OUTPUT : World cromputer

12.2.6 insert (i,str):-

This method insert a string str at the index position i.

OUTPUT : World computer centre.

12.2.7 reverse( )

It reverse the given String World


System.out.println(str.reverse( ));

OUTPUT : ralap

12.2.8 setCharAt(i,ch)

The method replaces the char at index position ‘i’ in the String buffer with the

char ‘ch’.
{
StringBuffer Str=new StringBuffer(“World computer”);
Str.setCharAt(7,’r’);
System.out.println(str);
}

OUTPUT : World crmputer

83
class StrBuff
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("World computer");
System.out.println(str);
System.out.println("Length = "+str.length( ));
System.out.println("Char at 2 is "+str.charAt(2));
System.out.println("Append s = "+str.append('s'));
System.out.println("Append Centre "+str.append(" centre"));
System.out.println("Insert r to 7th position =

"+str.insert(7,'r'));
System.out.println("Reverse "+str.reverse( ));
str.setCharAt(7,'z');
System.out.println("Set r to 7th poisition = "+str);
}
}

84
13. Java.util.package :

Collections Framework

A Collection is an object that groups multiple elements into a single unit. Collection
are used to store, retrieve and manipulate data, and to transmit data from one
method to another. It is at the top of the collections hierarchy (Base class)

A Collection framework is a unified architecture for representing and manipulating


Collections.

Collection frameworks are composing of three things. They are

Interface - Interface are abstract data types representing Collections


Implementations - Implementations are the actual execution of the interfaces.
Algorithms - Algorithm are methods that perform computations on
object that implements the interfaces.

Advantages of Collection Framework:

▪ Reduces programming effort by providing useful data structure and algorithms


▪ Increase program speed and quality since the implementation of each
interface are interchangeable
▪ Allows interoperability among unrelated API
▪ Extending or adapting a collection easy
▪ The Collection interface is at the top of the hierarchy. It enables us to work
with groups of objects.
▪ Encourage software reuse since the interface and algorithm are reusable

Implementation (or classes are the actual data objects used to store the collections

The important standard Collection Classes are :

1. AbstractCollection,
2. AbstractList,
3. AbstractSequentialList, Collection
4. ArrayList.
5. Arrays
6. LinkedList,
7. Stack,
8. Vector,
9. Date, Set List
10.AbstractSet,
11.HashSet,
12.Hashtable SortedSet
13.TreeSet etc.,

Algorithms are static methods within the Collection class. These method include
methods for sorting, searching, shuffling, data manipulations etc.

The legacy classes are Dictionary, HaseTable, Properties, Stack and Vector. The
legacy interface is the Enumeration Interface.

85
13.1 Util Interface

13.1.1 The List Interface

The List interface extends the Collection interface and declares the behavior of a
collection that stores a sequence of elements. Elements can be inserted or accessed
by their position in the list, using a zero-based index. A list may contain duplicate
elements

13.1.2 The Set Interface

The Set interface extends the Collection interface and declares the behavior of a
collection that dose not allow duplicate elements. Therefore, the add ( ) method
returns false if an attempt is made to add duplicate elements to a set

13.1.3 The SortSet Interface

The extension of the Set interface is the SortedSet Interface. It declares the
behavior of a set sorted in ascending order.

A NullPointerException is thrown if an attempt is made to use a null object and


null is not allowed in set.

13.2 Collection Classes

13.2.1 ArrayList Class

The ArrayList Class extends AbstractList and implements the List Interface.
ArrayList supports dynamic arrays that can grow as needed.
In java standard array are a fixed length is cannot be grown or shrink. That means
static array, know in advance how may elements are array will hold.
In essence, an ArrayList is a variable-length array of object references. ie, ArrayList
can dynamically increase or decrease in size. Array lists are created with an initial
size. When the size is exceeded, the collection is automatically enlarged. When object
are removed, the array may be shrunk.

ArrayList has the constructors shown here

1. ArrayList()
2. ArrayList(Collect c)
3. ArrayList(int capacity)

Syntax to create an Array List :

ArrayList obj=new ArrayList ( );

1. add(obj):
Insert obj into the invoking list at the end.
2. add(index,obj):
Insert obj into the invoking array list at the index passed in index.
3. remove(obj):
Removes one instance of obj from the invoking collection.
4. remove (index):
Remove a obj particular index.
5. size( ):
Returns the no. of elements of an array list.

86
Program:

// Demonstrate ArrayList.
import java.util.*;

class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();

System.out.println("Initial size of al: " +


al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");

System.out.println("Size of al after additions: " +


al.size());

// display the array list


System.out.println("Contents of al: " + al);

// Remove elements from the array list


al.remove("F");
al.remove(2);

System.out.println("Size of al after deletions: " +


al.size());
System.out.println("Contents of al: " + al);
}
}

Note: toArray () is use to obtaining a Array from an ArrayList

// Convert an ArrayList into an array.


import java.util.*;

class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList al = new ArrayList();

// Add elements to the array list


al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));

System.out.println("Contents of al: " + al);

// get array
Object ia[] = al.toArray();
int sum = 0;

87
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();

System.out.println("Sum is: " + sum);


}
}

13.2.2 LinkedList Class

The LinkedList class extends AbstractSquentialList and implements the List


Interface. It provides a Linked-list data structure.

The Constructors are

1. LinkedList()
2. LinkedList(Collection c)

This class is used to create linked list data structure.

1. add(obj):
Insert obj into the invoking linked list at the end.

2. add(index, obj):
Insert obj into invoking linked list at the index passed in index.

3. addFirst(obj):
Insert obj into the invoking linked list at the first end.

4. addLast(obj):
Insert obj into the invoking linked list at the last end.

5. remove(obj):
Removes the given element from the linked list.

6. removeFirst( ):
Removes the first element from the linked list.

7. removeLast( ):
Removes the Last element from the linked list.

8. getFirst( ):
Returns the 1st element of the linked list.

9. getLast( ):
Returns the Last element of the linked list.

10. size( ):
Returns the no. of elements of the linked list.

88
Program:

import java.util.LinkedList;
class LikedListDemo2
{
public static void main(String args[])
{
LinkedList l1=new LinkedList();
l1.add(“A”);
l1.add(“B”);
l1.add(“C”);
System.out.println(l1);
l1.add(1,”D”);
System.out.println(l1);
l1.addFirst(“E”);
System.out.println(l1);
l1.addLast(“F”);
System.out.println(l1);
l1.remove(“B”);
system.out.println(l1);
l1.removeFirst( );
System.out.println(l1);
l1.removeLast( );
System.out.println(l1);
System.out.println(l1.getFirst( ));
System.out.println(l1.getLast( ));
System.out.println(l1.size( ));
}
}

OUTPUT:

[A,B,C]
[A,D,B,C]
[E,A,D,B,C]
[E,A,D,B,C,F]
[E,A,D,C,F]
[A,D,E,F]
[A,D,C]
A
C
3.

Program:

// Demonstrate LinkedList.
import java.util.*;

class LinkedListDemo2 {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();

// add elements to the linked list


ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");

89
ll.addFirst("A");

ll.add(1, "A2");

System.out.println("Original contents of ll: " + ll);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);

System.out.println("Contents of ll after deletion: "


+ ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();

System.out.println("ll after deleting first and last: "


+ ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");

System.out.println("ll after change: " + ll);


}
}

13.2.3 The HashSet Class:

HashSet class extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage. As most readers likely know, a hash
table stores information by using a mechanism called hashing. In hashing, the
information content of key is used to determine a unique value, called its hash
code.

The hash code is then used as the index at which the data associated with the key is
stored. The transformation of the key into its hash code is performed automatically,
you never see the hash code itself. Also, your code can't directly index the hash
table.

The Constructors are

1. HashSet()
2. HashSet(Collection c)
3. HashSet(int capacity)
4. HashSet(int capacity, float fillRatio)

The basic operations are

1. add()
2. contains(obj)
3. remove()
4. size()

90
Program:

// Demonstrate HashSet.
import java.util.*;

class HashSetDemo
{
public static void main(String args[])
{
// create a hash set
HashSet hs = new HashSet();

// add elements to the hash set


hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.remove("A");
System.out.println(hs);
System.out.println(hs.contains("D"));
System.out.println(hs.size());

}
}

13.2.4 TreeSet Class

TreeSet provides an implementation of the Set Interface that uses a tree for
storage. Object are stored in sorted, ascending order. Access and retrieval times are
quite fast. Which makes TreeSet an excellent choice when storing large amount of
sorted information that must be found quickly.

The Constructors are

1. TreeSet()
2. TreeSet(Collection c)
3. TreeSet(Comparator comp)
4. TreeSet(SortedSet as)

1. add(obj): Insert obj into the list.

2. remove (obj ): Removes the given object from the list.


R
import java.util.*;
class TreeSetDemo1
{
public static void main(String args[]) E Z
{
TreeSet t1=new TreeSet( );
t1.add(“R”);
t1.add(“E”); D
t1.add(“D”); K
t1.add(“K”);
t1.add(“P”);
t1.add(“Z”);
P
System.out.println(t1);
t1.remove(“D”);

91
System.out.println(t1);
}
}

OUTPUT: Prints in the form of

[D,E,K,P,R,Z]
[E,K,P,R,Z]

Program:

// Demonstrate TreeSet.
import java.util.*;

class TreeSetDemo2
{
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet();

// Add elements to the tree set


ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");

System.out.println(ts);
}
}

13.3 Iterator Interface:

Iterator enables you to cycle through a collection, for example, you might want to
display each element. By far, the easiest way to do this is to employ an Iterator,
obtaining or removing elements. ListIterator extends Iterator to allow bi-
directional traversal of a list, and the modification of elements.

Methods of Iterator

Methods Description
Boolean hasNext() Returns true if there are more elements, otherwise
returns false
Object next() Returns the next element. Throws
NoSuchElementException if there is not a next
element.
void remove() Removes the current element. Throws
IllegalStateException if an attempt is made to call
remove() that is not preceded by a call to next().

Method of ListIterator

Methods Description
void add(Object obj) Inserts obj into the list in front of the element tha
twill be returned by the next call to next()
Boolean hasNext() Returns true if there is a next element. Otherwise,

92
return false.
Boolean Return the index of the previous element. If ther is
hasPerviousIndex() not a previous element, return –1
Void set(Object obj) Assigns obj to the current element. This is the
element last returned by a call to either next() or
previous()
Program:

// Demonstrate iterators.
import java.util.*;

class IteratorDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");

// use iterator to display contents of al


System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// modify objects being iterated


ListIterator litr = al.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}

System.out.print("Modified contents of al: ");


itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// now, display the list backwards


System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}

93
System.out.println();
}
}

13.4 Arrays Class:

Java 2 added a new class to java.util. called Arrays. This class provides various
methods that are useful when working with arrays. Although these methods
technically aren’t part of the collection framework, they help bridge the gap between
collections and arrays.

1. sort( ):

This method sorts an array. So that it is arranged in ascending order.

Program:

import java.util.*;
class BinaryArray
{
public static void main(String args[])
{
int a[]={90,25,10,30,15,60,95,100};
int i;
Arrays.sort(a);
for(i=0;i<a.length;i++)
{
System.out.println(a[i]+ “, “);
}
}
}
OUTPUT : 10,15,15,25,30,60,90,95,100

BinarySearch( ):-

This method used a binary search to find a specified value. This method must be
applied to sorted arrays.

Syntax:

Arrays.binarySearch(array,value);

import.java.util.*;
class ArraySort
{
public static void main(String args[])
{
int a[]={90,100,75,60,10,95,25,80};
int i ;
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a,75));
}
}
OUTPUT 3.

3. equals( ): Equals method returns true if 2 arrays are equals otherwise it returns
false.

94
Program:

import java.util.*;
class ArrayEquals
{
public static void main(String args[])
{
int a[]={90,100,75,60};
int b[]={90,100,75,60};
System.out.println(Arrays.equals(a,b));
}
}

OUTPUT: True.

13.5 The Legacy Classes and Interfaces

The original version of java.util did not included the collection framework. In
general, the legacy classes are supported because a large base of code exists that
uses them, including code still used by the java 2 API

The Legacy Classes dvefined by java.util are shown here:

▪ Dictionary
▪ HashTable
▪ Properties
▪ Stack
▪ Vector

There is one legacy interface called Enumeration.

The Enumeration interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects. This legacy interface
has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code.

Enumeration specifies the following two methods:

1. Boolean hasMoreElements()
2. Object nextElement()

Methods Description
Boolean hasMoreElements() Returns true if there are more elements,
otherwise returns false
Object nextElement() Returns the next object in the enumeration as
generic object reference

13.5.1 Vector Class

Vector implements a dynamic array, it is similar to ArrayList, but with two


differences. Vector is synchronized, and it contains many legacy methods that are
not part of the collections framework.

The Vector Constructors are:

1. Vector() - initial size of 10


2. Vector(int size) - specified size

95
3. Vector(int size, int incr) - specified size with specified increment
4. Vector(Collection c) - contains the elements of collection c

Program

// Demonstrate various Vector operations.


import java.util.*;

class VectorDemo
{
public static void main(String args[])
{

// initial size is 3, increment is 2


Vector v = new Vector(3, 2);

System.out.println("Initial size: " + v.size());


System.out.println("Initial capacity: " +
v.capacity());

v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));

System.out.println("Capacity after four additions: " +


v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));

System.out.println("Current capacity: " +


v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));

System.out.println("Current capacity: " +


v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));

System.out.println("First element: " +


(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());

if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration vEnum = v.elements();

System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();

96
/*for (Enumeration e = v.elements() ; e.hasMoreElements() ;)
{
System.out.println(e.nextElement());

}*/

}
}
13.5.2 HashTable Class:

It is used to create hash table. The hash table contains two columns. The 1 st column
is the index and the 2nd is value.

1. put( ): It is used insert the values into the hash table.

2. get( ): It returns the value corresponds to the given index value.

Program:

import java.util.*;
class HashTableDemo
{
public static void main (String args[])
{
Hashtable h=new Hashtable( );
h.put(“100”,”kumar”);
h.put(“101”,”Rangan”);
h.put(“102”,”Ram”);
h.put(“103”,”Sri”);
System.out.println(h.get(“102”));
System.out.println(h);
}
}

OUTPUT:
Ram
{103 Sri 102 Ram 101=Rangan 100=kumar}

13.5.3 Stack class

Stack is a subclass of Vector that implements a standard last-in, first-out stack.


Stack only defines the constructor, which create an empty stack. Stack includes all
the methods defined by Vector, and adds several of its own given below.

Methods Description
boolean empty() Return true if the stack is empty, and return
false if the stack contains elements
Object peek() Returns the elements on the top of the stack,
but does not remove it
Object pop() Returns the element on the top of the stack,
removing it in the process.
Object push(Object element) Pushes element onto the stack. Element is also
returned
int search(Object element) Search for element in the stack. If found, its
offset from the top of the stack is returned.
Otherwise, -1 is returned.

97
Program:

// Demonstrate the Stack class.


import java.util.*;

class StackDemo
{
static void showpush(Stack st, int a)
{
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st)


{
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[])


{
Stack st = new Stack();

System.out.println("stack: " + st);


showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try
{
showpop(st);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
}

13.6 StringTokenizer Class

StringTokenizer class provides the first step in this parsing process, prasing is the
division of text into a set of discrete part, or tokens, which in a certain sequence an
convey a semantic meaning.
StringTokenizer implements the Enumeration interface.

The StringTokenizer constructors are:

1. StringTokenizer(String str)
2. StringTokenizer(String str, String delimiters)
3. StringTokenizer(String str, String delimiters, Boolean delimAsToken)

98
Methods Description
int coutTokens() Using the current set of delimiters, the method
determines the number of token left to be parsed
and returns the result.
boolean hasMoreElement() Return true if one or more tokens remain in the
string and returns false if there are none.
boolean hasMoreToken() Returns true if one or more tokens remain in the
string and return false if here are none.
Object nextElement() Returns the next tokens as an Object
String nextToken() Returns the next token as String
String nextToken(String Returns the next token as String and sets the
delimiters) delimiters string to that specified by delimiters

Program:

// Demonstrate StringTokenizer.
import java.util.StringTokenizer;

class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Naughton and Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=1999";

public static void main(String args[])


{
StringTokenizer st = new StringTokenizer(in, "=;");

while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}

13.7 Date Class

The Date class encapsulates the current date and time. Date class is original version
of Java1.0. When Java1.1 was released, many of the functions carried out by the
original Date class were move into the Calendar and DateFormat classes, so many
of the Date methods are deprecated.

Date supports the following constructors:

1. Date()
2. Date(Long millisecond)

99
Methods Description
boolean after(Date date) Returns true if the invoking Date object
contains a date that is later then the one
specified by date. Otherwise, it returns false.
boolean before(Date date) Returns true if the invoking Date object
contains a date that is earlier then the one
specified by date. Otherwise, it returns false
int compareTo(Date date) Compares the value of the invoking object with
(or) that of date. Return 0 if the values are equal.
int compareTo(Object obj) Returns a negative value if the invoking
objects is earlier than date. Return positive
value if the invoking object is later than date

Program:

// Show date and time using only Date methods.


import java.util.Date;

class DateDemo
{
public static void main(String args[])
{
// Instantiate a Date object
Date date = new Date();

// display time and date using toString()


System.out.println(date);

Date dob= new Date(87,06,21);


Date doj = new Date(86,06,21);

if(doj.after(dob))
System.out.println("Entry dates are correct ");
else
System.out.println("Pls. Enter Doj date after dob date ");
}
}

100
14. IO package :
The java.io.package provides Classes and Interfaces that supports for input and
output Operations.

14.1 DataInputStream Class:

By using this class we can read values from keyboard.

import java.io.*;
class DataInputDemo
{
public static void main(String args[])throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
String str;
int n1,n2,n3;
System.out.print(“Enter the first no:”);
str=ds.readLine( );
n1=Integer.parseInt(str);
System.out.println(“Enter the second no:”);
str=ds.readLine( );
n2=Integer.parseInt(str);
n3=n1+n2;
System.out.println(n3);
}
}
OUTPUT :
Enter the first no : 100
Enter the Second no: 200
300.

readLine() method is in DataInputStream class.

14.2 File class:

It is used to obtain or manipulate the information associated with a disc file, such as
a permission, directory path and so no.

Syntax to create Fileobject:-

File obj=new File(“directory path/file name”);

1. getName( ):-
It returns the name of the file.
2. getParent( ):-
It returns the name of the parent directory.
3. exists( ):-
It returns true if the File exist, False if it does not the exist.
4. isFile( ):-
It returns true if it is a file And false if it is a directory.
5. isDirectory( ):-
It returns true if called on a directory. And false if called on a file.

101
6. canRead( ):-
This method is used to check whether the file s readable or not. If it is
readable then returns true otherwise it returns false.

7. canWrite( ):-
The method is used to check whether the file is writable or not.

8. isHidden( ):-
It returns true if the invoking file is hidden. Otherwise it returns false.

cd World- To hide the file


c:\>attrib +h <filename>
dir
9. length( ):-
The method returns the size of the file.

Program:

import java.io.*;
class FileDemo
{
static void P(String s)
{
System.out.println(s);
}
public static void main(String arg[])
{
File f1= new File("/subhjava/FileList.java");
P("File name : " + f1.getName());
P("Path : "+f1.getPath());
P("Abs Path : "+f1.getAbsolutePath());
P("Parent : "+f1.getParent());
P(f1.exists() ? "Exists " : "does not Exist ");
P(f1.canWrite () ? "is writeable " : "is not writeable");
P(f1.canRead () ? "is readable " :" is not readable");
P("is " + (f1.isDirectory() ? "directory ": "Not a
directory "));
P("is " + (f1.isHidden() ? "Hidden ": "Not Hidden"));
P(f1.isFile() ? "Normal file " : "might be a named pipe");
P(f1.isAbsolute () ? "is obsolute " : " is not absolute ");
P("File last modified : "+f1.lastModified());
P("file size : "+f1.length() + "Bytes");
}
}

10. renameTo( ):-


This method is used to rename a specified file.

import java.io.*;
class FileRename
{
public static void main(String args[])
{
File f1=new File(“c:/World/kumar”);
File f2=new File(“c:/World/prakash”);
f1.renameTo(f2);
}

102
}

11. list ( ):-


It returns all the files and directories of the invoking object.

import java.io.*;
class FileList
{
public static void main(String args[])
{
int i;
File f=new File(“e:/newjava”);
String str[]=f.list();
for(i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}

It returns but it is not display.


Str[0]=hello
Str[1]=World
Str[2]=rangan
Str[3]=kumar.
Str.length=4.(Here).
Java Hello|more

12. mkdir( ):-


The method is used to create directory.

import java.io.*;
class MakeDirectory
{
public static void main(String args[])
{
File f1=new File(“c:\India”);
f1.mkdir();
}
}

13. delete( ):
It is used to delete the file (given).

import java.io.*;
class FileDelete
{
public static void main(String args[])
{
File f1=new File(“c:/India”);
f1.delete( );
}
}

103
14.3 Streams

Java program perform I/O through streams. A stream is an abstraction that


either produces or consumes information. A stream is linked to a physical device by
the java I/O systems.
All streams behave in the same manner, even if the actual physical devices to
which they are linked differ.
Ie., an input stream can get from many different kinds of input devices like:
hard disk, a keyboard, or a network socket. And, also for output stream.

14.3.1 Tyes of Streams in Java :

• Byte Streams provide a convenient means for handling input and output of
bytes.
Bytes streams are used, for handling input and output of bytes

• Character Streams provide a convenient means for handling input and


output of Characters.
They use Unicode and, therefore, can be internationalized.

Note: Character streams were added in java1.1.


One other point: at the lowest level, all I/O is still byte-Oriented.

14.4 I/O Streams:

Java's stream-based I/O is built upon four abstract Classes:

The Byte Steam Class:

▪ InputStream
▪ OutputSream

The two most method important are read() and write(), which read and write bytes
of data.

The Character Stream Classes

▪ Reader
▪ Writer

The two most method important are read() and write(), which read and write
Characters of data.

14.4.1 The Byte Stream Clasess:

InputStream Abstract class that describes stream input


OutputStream Abstract class that describes stream output
BufferedInputStream Buffered input Stream
BufferedOutStream Buffered output Stream
DataInputStream An input stream that contains methods for
reading the java standard data types
DataOutputStream An output stream that contains methods for
writing the java standard data types
FileInputStream Input Stream that reads from a file
FileOutputStream Output Stream that writes to a file

104
14.4.2 The Character Stream I/O classes

Reader Abstract class that describes character stream input


Writer Abstract class that describes character stream output
BufferedReader Buffered input character Stream
BufferedWriter Buffered output character Stream
FileReader Input Stream that reads from a file
FileWriter Output Stream that reads to a file
InputStreamReader Input stream that translates bytes to characters
OutputStreamReader Output stream that translates bytes to characters
LineNumberReader Input Stream that counts lines
PrintWriter Output Stream that contains print() and println()
StringReader Input stream that reads from a string
StringWriter Output stream that writes to a string

Program: Read a Content from a File

import java.io.*;
class FileOpen
{
public static void main(String arg[]) throws IOException
{
FileInputStream fr = new FileInputStream(arg[0]);

int s;
while((s=fr.read())!=-1)
{
System.out.print((char)s);
}
fr.close();
}
}

Program : Write a Content to a File

import java.io.*;
class FileWrite
{
public static void main(String args[]) throws IOException
{
InputStreamReader kb=new InputStreamReader(System.in));

BufferedReader br=new BufferedReader (kb);


FileOutputStream fw=new FileOutputStream(args[0]);
char s;
while((s=(char)br.read()) !='*')
{
fw.write((int) s);
}
fw.close();
}
}

105
Program: Copying File From one to another

import java.io.*;
class FileCopy {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;

try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}

// open output file


try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}

// Copy File
try {
/* do {
i = fin.read();
if(i != -1)
fout.write(i);
} while(i != -1);*/
while((i=fin.read())!=-1)
fout.write(i);

} catch(IOException e) {
System.out.println("File Error");
}

fin.close();
fout.close();
}
}

106
15. User Defined Packages:
15.1 Packages

Package allows us to combine groups of classes and interfaces and also it controls
the accessibility of class inside a specific package.

Package allow us to organize class and interfaces into units

Package provide protection to classes, variables and methods in larger way than on a
class-by-class basis.

Package can be used to identify classes and interfaces

Step 1: create a directory


mkdir World
cd World
c:\WORLD>Edit

Inside the directory create classes and compile all the classes

e.g. javac Airth.java.

//package<directoryname>
package World;
public class Arith
{
public static int sum(int a,int b)
{
return(a+b);
}
public static int diff(int a,int b)
{
return(a-b);
}
public static int mul(int a,int b)
{
return(a*b);
}
public static int div(int a,int b)
{
return (a/b);
}
}

Creating another class :

package World;
public class General
{
public int fact(int n)
{
int i, f=1;
for(i=1;i<=n;i++)
{
f=f*i;

107
}
return(f);
}
public int power(int x,int y)
{
int i,p=1;
for(i=1;i<=p;i++)
{
p=p*x;
}
return(p);
}

15.2 Accessing User defined package World:

import World.*;
class AccessWorld
{
public static void main(String args[])
{
General g= new General();
System.out.println(Arith.mul(20,10));
System.out.println(g.fact(5));
}
}
OUTPUT :
200
120

15. 3 Scope of Access Specifiers

Class Member Access


Private No modifier Protected Public
Same class Yes Yes Yes Yes
Same package sub No Yes Yes Yes
class
Same package No Yes Yes Yes
non-subclass
Different Package No No Yes Yes
Subclass
Different Package No No No Yes
Non-subclass

108
16. Thread
16.1 Introduction

Unlike most other computer languages, java provides built-in support for
multithreaded programming. A multithreaded program conatins two or more parts
that can run concurrently

Each part of such a program is called a Thread, the each thread defines a
separate path of execution. Thus, multithreading is specialized form of multitasking.
However, there are two distinct types of multitasking: process-based and
thread-based.

A process-based multitasking is the feature that allow your computer to turn


two or more programs concurrently.

For example: process-based multitasking enables you to run the java


compiler at the same time that your are using a text editor(notepad)

A thread-based multitasking environment, the thread is the smallest unit of


dispatchable code. This means that a single program can perform two or more tasks
simultaneously.
For example: a text editor can format text at the same time that it is
printing, these two actions are performed by two separate thread.

Processes are heavyweight task, where as thread are lightweight task

A thread is similar to a sequential program. Like sequential program,a thread


also has a beginning , and an end. However a thread is not a program on its own.
But runs within a program. Every program has at least one thread that is called
primary thread. You can create more thread when necessary.

These are two types of threaded applications.

1. Single threaded applications


2. Multi threaded applications.

16.2 Single Threaded Application :

A process ie made up of only one thread is said to be single threaded. A single


threaded application can perform only one task at a time. You have to wait for one
task to be implemented before another can start.

16.3 Multi Threaded Applications :

A process having more than one thread is said to be multi threaded. A multi
threaded program is one in which these are two parts of same program that can run
concurrently.

16.4 Creating Thread Applications :

These are two ways to create thread application.

1. By extending the Thread class.


2. By implementing the Runnable interface.

109
1. By extending the Thread class :

Step 1: Create a class that extends Thread class.


Step 2: Implement the run method that contains logic of thread.
Step 3: Create a object for newly created thread and then call the start method
which calls the run method.
The Thread class defines several methods that help manage threads.

Method Meaning

getName Obtain a thread's name


getPriority Obtain a thread's priority
isAlive Determine if a thread is still running
join Wait for a thread to terminate
sleep Suspend a thread for a period of time to run
start Entry point for the thread
run Start a thread by calling its run method.

Program:

class Mythread extends Thread


{
public void run( )
{
try
{
System.out.println(“welcome to World”);
Thread.sleep(2000);
System.out.println(“Welcome to Java”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class ThreadDemo
{
public static void main(String args[])
{
// create obj for thread
Mythread t1= new Mythread();
t1. start( );
}
}
OUTPUT :
welcome to World
(after 2000 mili.sec)
welcome to java.

2. By Implementing Runnable Interface:

1. Create a class from runnable interface.


2. Implement the run method that contains the logic of the thread.
3. Once the thread is created it can be started by the creating an instance
and then calling start method.

110
class World implements Runnable
{
public void run( )
{
try
{
System.out.println(“Welcome to java”);
Thread.sleep(3000);
System.out.println(“Welcome to World”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class RunnableDemo
{
public static void main(String args[])
{
Thread t1 = new World( );
t1.start();
}
}

16.5 Creating Multi-threaded applications:

class First extends Thread


{
public void run( )
{
try
{
System.out.println(”Executing First thread”);
Thread.sleep(1000);
System.out.println(“End of First thread”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class Second extends Thread
{
public void run( )
{
try
{
System.out.println(“Executing second thread”);
Thread.sleep(5000);
System.out.println(“End of second thread”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}

111
class Third extends Thread
{
public void run( )
{
try
{
System.out.println(“Executing third thread”);
Thread.sleep(2000);
System.out.println(“End of third thread”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class MultiThread
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
t1.start( );
t2.start( );
t3.start( );
}
}
OUTPUT :
Executing First thread
Executing Second thread
Executing Third thread
End of first thread
End of third thread
End of second thread

16.6 Join( ) method:

The join method makes caller wait till the current thread finishes execution. In this
case it waits until the first thread finishes, before starting the second thread.

class JoinDemo
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
try
{
t1.start( );
t1.join( );
t2.start( );
t2.join( );
t3.start( );
t3.join( );
}

catch(Exception e)

112
{
System.out.println(“Error”);
}
}
}

OUTPUT :
Executing first thread
End of first thread
Executing second thread
End of second thread
Executing Third thread
End of third Thread

16.7 isAlive( ):

It is used to determine whether a thread has finished. The isAlive method returns
true if it is still running otherwise it returns false.

class AliveDemo
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
try
{
t1.start( );
if(t1.isAlive())
System.out.println("First Thread is running");
t1.join( );
if(t1.isAlive())
System.out.println(t1.isAlive( ));
else
System.out.println("First Thread finished");
t2.start( );

t3.start( );

}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
OUTPUT:
Executing first thread
true
End of first thread
False
Executing second thread
End of second thread
Executing third thread
End of third thread

113
16.8 Synchronization:

When two or more threads need access to a shared resources, they need some way
to ensure that the resource will be used by only one thread at a time. The process by
which this is called synchronization.

Example:

class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println(" ]");
}
}

class Caller implements Runnable


{
String msg;
Callme target;
Thread t;

public Caller(Callme targ, String s)


{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}

public void run()


{
target.call(msg);
}
}

class Synch
{

public static void main(String args[])


{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");

}
}

114
17. Applet & Abstract Windowing Toolkit(AWT)
17.1 Applets:

Java programs are classified into two groups.

1. Applications(Stand -alone program)


2. Applets (System Independent)

▪ Java applications are simple stand-alone Java programs that can run using the
Java interpreter from the command line.
▪ Java applets run from inside a World Wide Web browser that supports java
applets.

Definition:

An applet is a dynamic and interactive program that can run inside a Web
page displayed by the Java-capable browser such as Hot-Java or Netscape and
Internet Explorer-Java Browser is World Wide Web Browser used to view Web
pages, follow links and submit forms. It can also download and play applets on your
system.

Java applets have restrictions to ensure security and to prevent them from being
affected by viruses. Some of restrictions are listed below.

▪ Applets cannot read or write to the file system.


▪ Applets cannot communicate with any other server than the one in which they
were stored originally.
▪ Applets cannot run any programs on the system.

Note: You can also run your applets in appletviewer tool, which is available in
JDK.

java.lang java.awt java.applet

Object Component Container Panel Applet

17.2 Abstract Windowing Toolkit (AWT) is an API that is responsible for


building the Graphical User Interface(GUI). It is a part of the Java Foundation
Classes(JFC).

AWT includes rich set of user interface components,eg: label, button, textbox
etc.,and a powerful event handling model, graphics and image tools, layout
managers and support for data transfer using cut and paste throught clipboards.

AWT also supports Java Beans Architecutre. Every AWT component is a simple bean.
The java.awt package contains all classes for creating user interfaces and for painting
graphics and images.

The Awt has several subsystems that support the development of graphical user
Interface (GUI) programs. The subsystems include:

▪ Graphics package that allow drawing and rendering of lines and images

115
▪ Components such as Labels, Buttons and TextFields.
▪ Containers that include Frames, Panels and Dialogs.
▪ Layout managers that control the display in a portable manner.
▪ Event system, which allows the user to respond to interactions between the
components and containers in the applications.

17.3 Steps to Create an Applet:

Step 1: Type the following applet program in the text editor

import java.applet.Applet;
import java.awt.*;
public class AppletDemo extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to java applet”,100,100);
}
}

Step 2: Save the file as <filename>.java and compile it using javac.

Step 3: Now create an HTML file to access the applet program.

<applet code=”AppletDemo” width=500 height=500>


</applet>

Step 4: Save the file as <filename>.html

Step 5: Open the above file in a java compatible Broswer


eg:(Internet Explorer)
or
Execute the applet using appletViewer:

Syntax:

Appletviewer <filename>.htm.

HTML applet tag: The applet tag is used to start an applet from an applet viewer.

Code: Code is a required attribute that gives the name of the file containing your
applet’s compiled dot class file.

Width and Height: Width and Height are required attributes that give the size of
the applet display area.

The Graphics Co-ordinate system: (0,0)


Graphics co-ordinate system has the origin (0,0) in the X
top left corner positive x values are to be right, and
positive y values are down. All pixel values are integer.
There are no partial or fractional pixels. y1

drawString ()

Syntax : drawString (String message,int x, int y);


y x1

116
Here message is the string to be output beginning at x, y.

17.4 The Lifecycle of an Applet:

The java. applet. Applet includes five methods that are frequently used while
writing applets. They are init ( ), start( ), stop( ), destroy( )

Init method()

The init() method is executed only once at the start of applet execution.
Initialization of all variables, creation of objects, setting of parameters, ect. Can be
done in this method. So it typically includes code that needs to be executed once
when the applet starts executing.

Start() Method

This method is executed after the init() method. in case a java enabled browser is
used to run the applet, any time it is reloaded, the execution begins from the start()
method.

Stop method()

The stop() method is used to halt the running of an applet. In case the Java enabled
browser is used to run the applet, the stop() method is called the moment the Web
page is exited.

The 2nd and 4th method start and stop are normally used in conjunction to start,
then temporarily stop and again restart the applet execution (Minimize → stop ,
Maximize-start). Both these methods can be called several times in the applet.
This stop method is automatically invoked when the applet window is minimized.
Similarly the start is invoked when the applet viewer window is maximized.

The paint() Method

This method helps in drawing, writing and creating a colored background or an image
onto the applet. It takes an argument, which is an instance of the Graphics class.
To use this method, it is necessary to import the Graphics class on import
java.awt.Graphics.

The destroy() Method

This method is used to free the memory occupied by the variables and objects
initialized in the applet. Any clean up activity that needs to be performed can be done
in this method.

The repaint() Method

This method is used in case an applet is to be repainted. The repaint() calls the
update() method, to clear the screen of any existing content. The update() method
in turn calls the paint() method that then draws the contents of the current frame.
Repaint can be done mentioning time in milliseconds to performed in future. If the
time expires before update() can be called, update is not summoned.

117
repaint( ) update( )

paint( )

Program:

import java.awt.*;
import java.applet.*;
public class AppletLifeDemo extends Applet
{
public void init( )
{
System.out.println(“Executing init method”);
}
public void start( )
{
System.out.println(“Executing start method”);
}
public void paint(Graphics g)
{
g.drawString(“welcome to java”,100,100);
}
public void stop( )
{
System.out.println(“Executing stop method”);
}
public void destroy( )
{
System.out.println(“Executing destroy method”);
}
}

1. SetBackground( )

To set the background colour of an applet’s window, use background method .

Syntax:

setBackground(Color obj);

2. SetForeground( )

To set the fore ground color (Text color) use text color.

setForeground(Color obj);

118
17.5 Colors in java

Program:

import java.applet.*;
import java.awt.*;
public class AppletColorDemo extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
setForeground(Color.blue);
g.drawString(“Welcome To Java Applet”,100,100);
}
}

Standard Colors Available:


Color.black
Color.blue
Color.cyan
Color.darkGray
Color.gray
Color.lightGray
Color.green
Color.magenta
Color.orange
Color.pink
Color.red
Color.white
Color.yellow

Creating Custom Colors:

Using colour class we can create our own colours.

Syntax:

Color obj=new Color(int red, int green, int blue);

The range red, green and blue is 0 to 255.

import java.awt.*;
import java.applet.*;
//<applet code=AppletColor width=300 height=300 ></applet>
public class AppletColor extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,34,67);
Color c2=new Color(255,0,0);
setBackground(c1);
setForeground(c2);
g.drawString(“welcome to Java”,100,100);
}
}

119
showStatus( )
In addition to displaying information in its window, can also output a message to the
status window of the browser or applet viewer on which it is running. To do so call
showStatus with the String that you want displayed.

import java. awt.*;


import java.applet.*;
public class AppletStatusDemo extends Applet
{
public void paint(Graphics g)
{
showStatus(“our applet program”);
g.drawstring(“Welcome”,100,100);
}
}

17.6 Working with Graphics:

17.6.1Drawing lines:

Lines are drawn by means of the drawLine method.

drawLine (int x1,int y1,int x2,int y2);

It displays a line in the current drawing color that begins at x1, y1 and ends at x2
and y2.

Program :

import java.awt.*;
import java.applet.*;
public class AppletDraw1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.pink);
g.drawLine(100,100,150,200);
}
}
OUTPUT :

17.6.2 Drawing rectangles:

The drawRect and fillRect methods displayed an outlined and filled rectangle
respectively.

Syntax:

drawRect (int x1,int y1,int width, int height);


fillRect (int x1,int y1,int width, int height);

120
The upper-left corner of the rectangle is at x1,y1, the dimensions of the rectangles
rounded rectangle, use drawRoundRect and fillRoundRect.

Syntax:

drawRoundRect(int x1,int y1, int width, int height, int x1dia,int y1dia);
fillRoundRect(int x1,int y1,int width,int height,int x1dia,int y1dia);

A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at
x1, y1. The dimension of the rectangle are specified by width and height. The
diameter of the rounding are along the x-axis is specified by x.dia. The diameter of
the rounding are along the y-axis is specified by y.dia.

Program:

import java.awt.*;
import java.applet.*;
public class AppletDraw2 extends Applet Output :
{
public void paint(Graphics g)
{
g.setColor(Color.pink);
g.drawRect(50,50,50,20);
g.setColor(Color.red);
g.fillRect(100,100,50,20);
g.setColor(Color.blue);
g.drawRoundRect(150,150,50,20,5,55);
g.setColor(Color.green);
g.fillRoundRect(200,200,50,20,5,5);
}
}

17.6.3 Drawing ellipses and Circles.

To draw an ellipse we drawOval. To fill an ellipse, use fillOval.

Syntax:

drawOval(int x1,int y1,int width, int height);


fillOval (int x1,int y1, int width, int height);

The ellipse is drawn within a bounding rectangle whose upper left corner is specified
by x1,y1 and whose width and height.

Note: To draw a little, specify a square has the bounding rectangle.

import java.awt.*;
import java.applet.*;
public void paint(Graphics g) O/p:
{
g.setColor(Color.blue);
g.drawOval(100,100,200,200);
}

121
17.6.4 Drawing Arcs:

Arcs can be drawn with drawArc and fillArc.

Syntax:

drawArc(int x1,int y1, int width, int height, int start.angle, int end.angle);
fillArc(int x1,int y1, int width, int height, int start.angle,int end.angle)

The arc is bounded by the rectangle whose upper left corner is specified by x1,y1 &
whose width & height are specified by width and height. The arc is drawn from start
angle through the angular distance specified by end angle.
Angles are specified in degrees.

Program:

public void paint(Graphics g)


{
g.setColor(Color.red);
g.fillArc(100,100,200,100,0,180);
}

17.6.5 Drawing Polygons :

It is possible to draw arbitrarily shaped figures using drawPolygon and fillPolygon().

Syntax:
DrawPolygon(int x[ ], int y[ ], int no. of points);

The Polygon’s end points are specified by co-ordinate pairs contained within the x
and y arrays.

Program:

public void paint(Graphics g)


{
g.setColor(Color.red);
int x[]={200,300,100,300,100,200};
int y[]={50,300,100,100,300,50};
g.fillPolygon(x,y,6);
}

17.7 Working with Fonts:

The awt supports multiple type of fonts. The awt provides flexibility by abstracting for
dynamic selection of fonts.
To select a new font, you should first consider the font object that describes that
font.

Syntax:

Font obj =new Font(font name, font style, font size);

Here font name specifies the name of the font. The style of the font is specified by
font style. It may consist of one or more of these three constants.

122
Font.PLAIN, Font.BOLD,Font.ITALIC.
The size in points of the font is specified by font size.
To use a font that you have created, you must select it using set font.

Program:

import java.awt.*;
import java.applet.*;
public class AppletFont extends Applet
{
public void paint(Graphics g)
{
Font f=new Font(“Arial”,Font.BOLD+Font.ITALIC,25);
g.setFont(f);
g.setColor(new Color(255,0,255));
g.drawString(“Welcome to Java”,150,150);

Font f=new Font(“Times New


Roman”,Font.BOLD+Font.ITALIC,25);
g.setFont(f);
g.setColor(new Color(255,0,255));
g.drawString(“Thank you to Java”,150,150);

}
}

17.8 Images:
import java.applet.Applet;
import java.awt.*;
public class ImageDemo extends Applet
{
Image img;
public void init()
{
img=getImage(getCodeBase(),"image.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,10,10, this);
}
}

123
18. Event Handling
The user communicates with window programs by performing actions such as
clicking a mouse botton or pressing a key on the keyboard. These actions result in
the generating of events. The process of responding to an event is known as Event
Handling. Window program are said to be event-driven because they operate by
performing actions in response to events.

The jdk1.0 supported an approach to event handling referred to as an


inheritance model.

The jdk1.0 approach to event handling was replaced by an event delegation


model in jdk1.1; however, the old inheritance event model is still supported. The
event delagion model provides the capability to deliver events to specific objects a
capability that was lacking in jdk1.02

The event delegation approach is less complex and more efficient. It uses
special classes called adapter classes, whose objects listen for the occurance of
events on behalf of objects of other classes.

Act that results in the events Listener type


User clicks a button, presses return while typing ActionListener
in a text field, or chooses a menu item
User closes a frame (main window) WindowListener
User presses a mouse button while the cursor is MouseListener
over a component
User moves the mouse over a component MouseMotionlistener
Component becomes visible Componenetlistener
Component gets the keyboard focus Focuslistener
Table or list selection changes ListSelctionListener

Each event is represented by an object that gives information about the event and
identifies the event source. Event sources are typically components, but othe kinds
of objects can also be event soruces.

How to implements an event Handler:

Every event handler requires three bits of code:

1. In the declaration for the event handler class, code that specifies that the
class either implements a listener interface or extands a class that implements
a listener interface. For example

public class Myclass implements ActionListener


{
}

2. code that registers an instance of the event handler class as a listener upon
one or more components. For example

Syntax:
somecomponent.addActionListener(instanceof Myclass);
Eg:
obj.addActionListener(this);

3. code that implements the methods in the listener interface. For example

124
public void actionPerformed(ActionEvent e)
{
//code that reacts to the action….
}

the single argument to the method is an ActionEvent object that gives


information about the event and its source.

18.1 Handling Mouse:

These are two types of interfaces to handle mouse in Java.

1. MouseListener interface
2. MouseMotionListener interface

1. MouseListener Interface:

1. Mouse Clicked: This method is invoked when the mouse is pressed and
released at the same point.
2. MousePressed: This method is invoked when the mouse is pressed.
3. Mouse Released: This method is invoked when the mouse is released.
4. Mouse Entered: This method is invoked when the mouse entered into the
appletviewer.
5. Mouse Exited: This method is invoked when the mouse exited from the
applet viewer.

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDemo extends Applet implements MouseListener
{
String msg;
public void init( )
{
addMouseListener(this);
}
public void mouseClicked (MouseEvent me)
{
msg=”Mouse clicked”;
repaint( );
}
public void mousePressed (MouseEvent me)
{
msg=”Mouse pressed”;
repaint( );
}
public void mouseReleased (MouseEvent me)
{
msg=”Mouse Released”;
repaint( );
}
public void mouseEntered (MouseEvent me)
{
msg =”Mouse Entered”;

125
repaint( );
}
public void mouseExited (MouseEvent me)
{
msg = “Mouse Exited “;
repaint( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

2. MouseMotionListener interface:

This interface has two methods.


1. mouseMoved( ): This method is invoked when the mouse is moved around
the screen
2. mouseDragged( ): This method is invoked when the mouse is dragged
around the screen.

Program:

public class MouseMotionDemo extends Applet implements


MouseMotionListener
{
String msg;
public void init( )
{
addMouseListener(this);
}
public void mouseMoved (MouseEvent me)
{
msg= “Mouse Moved at(“+me.getX( ) + “,”+ me.getY( )+ “)”;
repaint( );
}
public void mouseDragged(MouseEvent me)
{
msg =”Mouse Dragged at ( “ + me.getX( )+”,”+me.getY( )+ “)”;
repaint( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

18.2 Keyboard Event:

To access the keyboard we have to use KeyListener interface.

This interface has three methods.

1. keyPressed: This method is invoked when the keyboard button is pressed.


2. keyReleased: This method is invoked when the keyboard button is released.
3. keyTyped: This method is invoked when the keyboard button is typed.

Program:

126
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyboardDemo extends Applet implements KeyListener
{
String msg;
public void init( )
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
msg=”Key Pressed”;
repaint( );
}
public void keyReleased(KeyEvent ke)
{
msg = “Key Released”;
repaint();
}
public void keyTyped(KeyEvent ke)
{
msg = “Key Typed”;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

127
19. AWT Controls:
19.1 User Interface Components:

A place in which the various drawing needs to be done must be provided and this is
called the container. The container is derived from java.awt.Container class. The
elements of the Userinface are called components. These components are derived
from the java.awt.Component class.

All the user interface components and container classes are derived from this class.

There are two major set of classes derived from the component class:

▪ The Container Classes - they are generic AWT components that can contain
other components

▪ The User Interface Component Classes - these include components like


Button, Label etc.

Controls are components that allow a user to interact with your application in various
base.

Applet
Panel

Object Component Container


Frame
Window

Dialog

19.2 User Interface Component Classes

The AWT package contains a number of component classes that are typical elements

Frame

Button

Checkbox
Object Component
TextArea

Text Component
TextField

Choice

List

Label

128
of any interactive user interface. These classes are derived from the abstract
Compoenent class. The figure shows the class hierarchy of these classes.

The Component class define a number of methods that can be used on any of the
classes that are derived from it. The methods listed below in table can be used on all
UI compoents as well as containers.

Methods Description
setSize(Dimension d) Resizes the corresponding component so that it has
width d.width and height d.height
setSize(int width, int Resizes the corresponding component so that it has
height) width and height
setFont(font f) Sets the font of the corresponding component
setEnabled(Boolean b) Enables or disables the corresponding component,
depending on the value of the parameter b.
setVisible(Boolean b) Shows or hides the corresponding component
depending on the value of prarament b.
setForground(Color c) Set the foreground color of the corresponding
component.
setBounding(int x, int y, int Moves and resizes the corresponding component.
width, int height)
setBounds(Rectangle r) Moves and resizes the corresponding component.
To conform to the new bounding rectangle r.
setBackground(Color c) Set the background color of the corresponding
component.
getBackground() Gets the background color of the corresponding
component.
getBounds() Get the bound sof the corresponding component in
the form of a Rectangle object
getFont() Gets the font of the corresponding component.
getForeground() Gets the foreground color of the corresponding
component.
getSize() Return the size of the corresponding component in
the form of a Dimension object.

19.2.1. Labels:

A Label is an object of type Label and it contains a string, which it displays.Labels do


not support any interaction with the user.

Syntax:

Label obj =new Label (String);

Program:

import java.awt.*;
import java.applet.*;
public class LabelDemo extends Applet
{
public void paint(Graphics g)
{
Label l1=new Label (“World”);
Label l2=new Label (“Vellore”);
add(l1);

129
add(l2);
}
}

19.2.2 Button:

The most widely used control is Button. A button is a component that contains a
label and that generates a event when it is pressed.

Syntax: Button obj = new Button (“String”);

Each time a button is pressed, an action event is generated to access action event,
we have to create ActionListener interface. That interface defined the
actionPerformed() method which is called when an event occurs. A Label is
obtained by getActionCommand() method.

1. Program to Change Background Colors.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonDemo extends Applet implements ActionListener
{
public void init( )
{
Label l1=new Label (“Click to Select Colors and set
BackGround”);

Button b1=new Button(“Red”);


Button b2= new Button(“Green”);
Button b3=new Button(“Blue”);
Button b4= new Button(“Pink”);
Button b5=new Button(“Black”);
Button b6=new Button(“White”);
add(l1);

add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Pink”))
setBackground(Color.pink);

130
else if(str.equals(“Black”))
setBackground(Color.black);
else
setBackground(Color.white);
}
}

2. Program to Change Font Properties to Text:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextFont extends Applet implements ActionListener
{
Font f;
public void init( )
{
Button b1=new Button (“Times New Roman”);
Button b2 =new Button (“Arial”);
Button b3= new Button(“Arial Black”);
Button b4=new Button(“Courier New”);
Button b5=new Button(“Comic Sans MS”);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListenter(this);

}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand( );
f= new Font(str,Font.BOLD,20);
repaint( );
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawstring(“World Computers”,100,100);
}
}

131
19.2.3 Text Field:

The textfield class implements a single line text entry area, usually called an edit
control.

Syntax: TextField obj = new TextField (int Size);

getText() - To obtain the String currently contained in the textfield


setText() – to set the text to the textfield

1. Program : To calculate sum of two nos. using TextField

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextDemo extends Applet implements ActionListener
{
TextField t1,t2;
Label r;
public void init( )
{
Label l1=new Label("Enter the 1st no: ");
Label l2=new Label("Enter the 2nd no: " );
Label l3=new Label("Result");
t1 = new TextField(10);
t2 = new TextField(10);
r = new Label(" ");
Button b1 = new Button("SUM");
Button b2 = new Button("SUB");
Button b3 = new Button("DIV");
Button b4 = new Button("MOD");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(r);
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str,str1;
str=ae.getActionCommand();
str1 =t1.getText( );
int n1=Integer.parseInt(str1);
str1 = t2.getText( );
int n2= Integer.parseInt(str1);
int n;
if(str.equals("SUM"))
{
n=n1+n2;
r.setText(n+"");
}

132
else if(str.equals("SUB"))
{
n=n1-n2;
r.setText(n+" ");
}
else if(str.equals("DIV"))
{
n=n1/n2;
r.setText(n+" ");
}
else if(str.equals("MOD"))
{
n=n1%n2;
r.setText(n+" ");
}

}
}

2. Program : To Calculate Square Root of given Number.

import java. awt.*;


import java.awt.event.*;
import java.applet.*;
public class TextFieldDemo2 extends Applet implements
ActionListener
{
TextField t1;
Label l3;
public void init( )
{
Label l1= new Label(“Enter a value :”);
Label l2= new Label(“Square root :”);
t1= new TextField(10);
l3 = new Label("");
Button b1= new Button(“SQRT”);
add(l1);
add(t1);
add(l2);
add(l3);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str;
str = t1.getText( );
double n1= Double.parseDouble(str);
double n = Math.sqrt(n1);
l3.setText(n+“ “);
}
}

Note: There may be times when you want the user to enter text should not
displayed, example, for password field You can display the other characters (*)
common for alphabets

133
setEchoChar.

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SetEchoDemo extends Applet implements ActionListener
{
TextField t1,t2;
String msg;
public void init();
{
Label l1= new Label (“User name”);
Label l2= new Label(“Password”);
t1 =new TextField(10);
t2= new TextField(10);
t2.setEchoChar(‘*’);
Button b1 = new Button(“Login”);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str1=t1.getText( );
String str2= t2.getText( );
if(str1.equals(“World”) && str2.equals(“admin”))
msg=”User name and password are correct”;
else
msg=”invalid username or password”;
repaint( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

19.2.4 TextArea:

Sometimes a Single line of text i/p is not enough for a given task. To handle these
situations, AWT includes a Simple multiline editor called TextArea.

Syntax: TextArea obj= new TextArea (int numlines, int numchar);

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{
public void init( )
{
TextArea t1= new TextArea(10,15);
add(t1);

134
}
}

19.2.5 Checkboxes:

A Checkbox is a control i.e. used to turn an option on or off. It consists of a small


box that can either contain a checkmark or not. There is a Label associated with
the check box that describes what option the box represent. We can change the
state of a checkbox by checking on it.

Syntax: Checkbox obj=new Checkbox (str,boolean);

It creates a check box whose label is specified by str (string). Each time a
checkbox is selected or deselected, an itemEvent is generated. To access ItemEvent
we have to implement ItemListener interface. That interface defines the
itemStateChanged method. getState returns the status of the checkbox. If we
selected the checkbox, it returns true. If we deselect the checkbox, it returns false.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class CheckDemo extends Applet implements ItemListener


{
Font f;
Checkbox b1,b2;
public void init()
{
b1=new Checkbox(“Bold”);
b2=new Checkbox(“Italic”);
add(b1);
add(b2);
b1.addItemListener(this);
b2.addItemListener(this);
}
public void itemStateChanged (ItemEvent ie)
{
if(b1.getState( )==true && b2.getState( )==true)
f=new Font(“Arial”,Font.BOLD+Font.ITALIC,20);
else if(b1.getState( )==true && b2.getState( )==false)
f=new Font(“Arial”,Font.BOLD,20);
else if(b1.getState( )==false && b2.getState( )==true)
f=new Font(“Arial”,Font.ITALIC,20);
else
f=new Font(“Arial”,Font.PLAIN,20);
repaint( );
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawString(“Welcome to Java”,100,100);
}
}

135
19.2.6 Checkbox Group:

It is possible to create a set of mutually execute checkboxes in which one and only
one check box in a group can be checked at any one time. These checkboxes are
often called Radio buttons. To create a set of mutually exclusive checkboxes, we
must first define the group to which they will belong and then specify the group when
you construct the checkboxes.

Syntax: CheckboxGroup obj=new CheckboxGroup( );


Checkbox obj=new Checkbox(String str,obj of
checkboxgroup, state(true/false)) ;

You can determine which checkbox in a group is currently selected by calling


getSelected Checkbox.

1. Program to Apply Text Color:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CheckDemo1 extends Applet implements ItemListener
{
CheckboxGroup cbg;
Checkbox c1,c2,c3,c4,c5;
public void init( )
{
cbg= new CheckboxGroup( );
c1= new Checkbox(“Red”,cbg,false);
c2= new Checkbox(“Green”,cbg,false);
c3= new Checkbox(“Blue”,cbg,false);
c4= new Checkbox(“Pink”,cbg,false);
c5= new Checkbox(“Magenta”,cbg,false);
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(cbg.getSelectedCheckbox( ) == c1)
setForeground(Color.red);
else if (cbg.getSelectedCheckbox( ) == c2)
setForeground(Color.green);
else if (cbg.getSelectedCheckbox( ) == c3)
setForeground(Color.blue);
else if (cbg.getSelectedCheckbox( ) == c4)
setForeground(Color.pink);
else
setForeground(Color.magenta);
repaint( );
}
public void paint(Graphics g)
{

136
Font f= new Font("Arial",Font.BOLD,25);
g.setFont(f);
g.drawString(“World Computer Centre”,100,100);
}
}

19.2.7 Choice Control:

The Choice class is used to create a pop-up of list of items from which the user may
choice. When inactive, a choice component takes up only enough space to show the
currently selected item. When the user clicks on it, the whole list of choices pops up
and a new selection can be made.

Syntax: Choice obj = new Choice( );

To add a selection to the list, call add. To determine which items is currently
selected we have to use which items is currently selected we have to use
getSelectedItem method. It returns a string containing the name of the item. To
access choice control we have to use ItemListener interface.

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ChoiceDemo extends Applet implements ItemListener
{
Choice c;
public void init( )
{
c = new Choice();
c.add(“Red”);
c.add(“Green”);
c.add(“Pink”);
c.add(“Blue”);
c.add(“Gray”);
add (c);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
String str=c.getSelectedItem( );
if(str.equals(“Red”))
setBackground(Color.red);
else if (str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else if (str.equals(“Blue”))
setBackground(Color.blue);
else
setBackground(Color.gray);
}
}

137
19.2.8 List Controls:

The list class provided a compact scrolling selection list unlike the choice object,
which shows only the single selected item in the menu, a list object can be
constructed to show any number of choices in a visible window.

Syntax: List obj= new List (int numRows);

Here, the value of numRows specifies the no. (number) of entries in the list that will
always be visible(others can be scrolled into view as needed). To add a selection to
the list, call add method. The getSelectedItem method returns a String containing
the name of the item. To process the list, we have to implement itemListener
interface.

Program:

import java.awt.*;
import java.awt.event.*;
public class ListDemo extends Applet implements ItemListener
{
List l;
public void init( )
{
l = new List (4);
l.add(“Red”);
l.add(“Green”);
l.add(“Pink”);
l.add(“Gray”);
l.add(“Magenta”);
l.add(“Blue”);
add (l);
l.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
String str=l.getSelectedItem( );
if(str.equals(“Red”))
setBackground(Color.red);
else if (str.equals(“Green”))
setBackground(Color.green);
else if (str.equals(“Pink”))
setBackground(Color.pink);
else if (str.equals(“Gray”))
setBackground(Color.gray);
else if (str.equals(“Magenta”))
setBackground(Color.magenta);
else
setBackground(Color.blue);
}
}

138
20. Layout Management
The Layout Management classes are a set of classes that implement the
java.awt.LayoutManger interface and help to position the components in a container.
The interface takes the task of laying out the child components in the container.
Resizing and moving the child components achieve this task. The advantage of this
type of mechanism is that when the container is resized the layout manager
automatically updates the interfaces.

The basic layout manager include:

1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. CardLayout

The first step is to instantiate a layout manger class, such as FlowLayout,


BorderLayout etc., the constructor of these classes, which comes in different flavors,
can be used to create a new layout manager object.

The next step is to associate the layout manager with the container on which it
should operate. The method setLayout() sets the layout manager of a container.

Once the layout manger for the container is set, components added to it will be
arranged depending on the layout specified.

20.1 FlowLayout

The FlowLayout class is simple layout manager that works like a word processor.
Components are displayed with their preferred size in order in which they are added
to the container. The flow layout lays out components lineswise from left the right.
When the line of components is filled, flow layout creates a new line and continues
laying out components on the next line. Like a word processor a FlowLayout+

FlowLayout Constructors:

Constructor Description
FlowLayout() Constructs a new flowlayout with centered
alignment, leaving a vertical and horizontal
gap of 5 pixels
FlowLayout(int align) Constructs a new flowlayout with the
alignment specified leaving a vertical and
horizontal gap of 5 pixels
FlowLayout(int align, int vgap, int Constructs a new flowlayout with the
hgap) alignment specified, leaving a vertical and
horizontal gap of 5 pixels

139
The various methods that can be used in combination with the flow layout is given
below.

Methods Description
getAlignment() Gets the alignment for the layout
getHgap() Gets the horizontal gap between components
getVgap() Gets the vertical gap between components
setAlignment(int align) Sets the alignment for the special layout.
setHgap(int hgap) Set the horizontal gap for the specified layout
setVgap(int vgap) Set the vertical gap for the specified layout

Program:

import java.awt.*;

//<applet code=FlowTest width=300 height=300></applet>

public class FlowTest extends java.applet.Applet


{
String str[ ]={"one","two","Three","Four","Five","Six","Seven"};
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,20,20));
for(int i=0;i<str.length;++i)
add(new Button(str[i]));

}
}

20.2 Grid Layout

The GridLayout class lays out components in a way very similar to a spreadsheet in
rows and columns. Specifying the number of rows and columns in the grid creates
the GridLayout. The components in a grid are resized of fit their cell. All components
in a grid layout are of the same size. The position of component in a grid is
determined by the order in which the components are add to the grid. Component
are display from left to right and top to bottom.

The grid layout can be constructed using the constructors listed below

Constructors Description
GridLayout() Creates a grid layout with a default of one
column per component in a single row
GridLayout(int rows, int cols) Creates a grid layout with the specified rows
and columns.
GridLayout(int rows, int cols, Creates a grid layout with the specified rows
int hgap, int vgap) and columns and specified horizontal and
vertical gaps.

The various methods that can be used in conjunction with the gird layout are listed
below

140
Methods Description
getColumns Gets the number of Columns in the layout
getRows() Gets the number of Rows in the layout
getHgaps() Gets the horizontal gaps for the layout
getVgap() Get the Vertical gaps for the layout
getColumns(int cols) Sets the number of columns in the layout
getRows(int rows) Sets the number of rows in the layout

Program:

import java.awt.*;

//<applet code=GridTest width=200 height=200></applet>

public class GridTest extends java.applet.Applet


{
public void init()
{
setFont(new Font("TimesRoman",Font.BOLD+Font.ITALIC,24));
setLayout(new GridLayout(4,2);
for(int i=1;i<=13;++i)
add(new Button(" " +i));
}
}

20.3 Border Layout :

The BorderLayout class enables specification, ie., where on the border of a container
each component should be palced. All areas need not be filled. The size of the areas
will depend on the components they contain.

With border layout, the placement of the components is specified as being, North,
South, East and West. The border layout resizes the Center component ot fill the
remaining center space.

The various constructors that can be used to create a border layout is given below.

Constructors Description
BorderLayout() Creates a new border layout with no gap
between the components
BorderLayout(int hgap, int vgap) Creates a new border layout with the
specified horizontal and vertical gap
between components.

The various methods that can be used in conjuction with the border layout is given
below.

Methods Description
getHgap() Returns the horizontal gap between components
getVgap() Returns the Vertical gap between components
setHgap() Set the horizontal gap between components to the value
specified.
setVgap() Set the vertical gap between components to the value
specified.

To add a component to a container with BorderLayout, an add() method, that is


slightly different from the one we have been using, is used, is used.

141
Eg: add("East",mybutton);

Program:

import java.awt.*;

//<applet code=BorderTest width=200 height=200></applet>

public class BorderTest extends java.applet.Applet


{
public void init()
{
setLayout(new BorderLayout(10,10));
add("South",new Button("Bottom of the applet"));
add("North",new Button("Top of the applet"));
add("East",new Button("Right"));
add("West",new Button("Left"));
add("Center",new TextArea("Appears at the center"));
}

/*public Insets getInsets()


{
return new Insets(20,20,10,10);
}*/
}

Insets:

Insets are used to proved spacing around the container.

public Insets getInsets()


{
return new Insets(10,5,15,20);
}

20.4 CardLayout:

The CardLayout allows only one of its components to be visible at a time. The
CardLayout considers each of its components as a card. The CardLayout is controlled
by a combo box. The state of the combo box determines with panel is displayed by
the CardLayout. Using the CardLayout, the user has the option to view the following

1. The first Component


2. The last Component
3. The Previous component
4. The next component
5. Any component by specifying its name

The Constructors are:

Constructors Description
CardLayout() Creates a new card layout whose gaps are
of size zero.
CardLayout(int h, int v) Creates a new card layout with the
horizontal gap and vertical gap

142
The methods are:

Methods Description
First(Container c) Display the first card of the container c
Last(Container c) Display the Last card of the container c
Next(Container c) Display the Next card of the container c
Previous(Container c) Display the Previous card of the container c

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

//<applet code=CardLayoutDemo width=300 height=300></applet>

public class CardLayoutDemo extends Applet implements ActionListener,


MouseListener
{
Checkbox Win98, winNT, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init()
{
Win=new Button("Windows");
Other=new Button("Other");
add(Win);
add(Other);
cardLO=new CardLayout();
osCards= new Panel();
osCards.setLayout(cardLO);
Win98=new Checkbox("Windows 98",null,true);
winNT=new Checkbox("Windows NT");
solaris=new Checkbox("Solaris");
mac=new Checkbox("MacOS");
Panel winPan= new Panel();
winPan.add(Win98);
winPan.add(winNT);
Panel otherPan=new Panel();
otherPan.add(solaris);
otherPan.add(mac);
osCards.add(winPan,"Windows");
osCards.add(otherPan,"Other");
add(osCards);
Win.addActionListener(this);
Other.addActionListener(this);
addMouseListener(this);
}
public void mousePressed(MouseEvent me)
{
cardLO.next(osCards);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void mouseReleased(MouseEvent me){}

143
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==Win)
{
cardLO.show(osCards,"Windows");
}
else
{
cardLO.show(osCards,"Other");
}
}
}

Program to Calculate Student Marks:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class NewResult extends Applet implements ActionListener
{
TextField t1,t2,t3,t4;

Label t,a,g,r,head;

Panel p1,p2,p3,h;
public void init()
{
Font f= new Font("Arial",Font.BOLD,20);
head = new Label("Result Sheet");
head.setFont(f);
head.setForeground(Color.blue);
h = new Panel();
h.setLayout(new FlowLayout());
h.add(head);

Label l1= new Label("Name");


Label l2= new Label("Mark1");
Label l3= new Label("Mark2");
Label l4= new Label("Mark3");
Label l5= new Label("Total");
Label l6 =new Label("Average ");
Label l7= new Label("Grade");
Label l8=new Label("Result");
Button b1= new Button("Result ");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
t4=new TextField(10);
t= new Label(" ");
a=new Label(" ");
g=new Label(" ");
r=new Label(" ");

p1=new Panel();
p1.setLayout(new GridLayout(4,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);

144
p1.add(t3);
p1.add(l4);
p1.add(t4);
p1.add(l5);
p1.add(t);
p1.add(l6);
p1.add(a);
p1.add(l8);
p1.add(r);
p1.add(l7);
p1.add(g);
p2=new Panel();
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
p2.add(b1);
p3=new Panel();
p3.setLayout(new GridLayout(3,1));
p3.add(h);
p3.add(p1);
p3.add(p2);
add(p3);
p3.setBounds(20,20,200,200);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=t2.getText();
int m1=Integer.parseInt(s);
s=t3.getText();
int m2=Integer.parseInt(s);
s=t4.getText();
int m3=Integer.parseInt(s);
int t=m1+m2+m3;
float a=Math.round((float)t/(float)3.0);

System.out.println(a);
String strtot=new String(t+"");
strtot.trim();
System.out.println(strtot);
char chtot[];
chtot=strtot.toCharArray();
StringBuffer str = new StringBuffer();
int i=0;
System.out.println("Printing in words ....");
try
{
while(i<chtot.length)
{
System.out.println(chtot[i]+"");
switch(chtot[i])
{
case '1': str.append(" One");
break;
case '2': str.append(" Two");
break;
case '3': str.append(" Three");
break;
case '4': str.append(" Four");
break;
case '5': str.append(" Five");
break;
case '6': str.append(" Six");

145
break;
case '7': str.append(" Seven");
break;
case '8': str.append(" Eight");
break;
case '9': str.append(" Nine");
break;
case '0': str.append(" Zero");
break;

}
i++;
}
}
catch(Exception e1){ }

this.t.setText(t+" "+str);
this.a.setText(a+"");

System.out.println(str);
if(m1>=40 && m2>=40 && m3>=40)
{
r.setText("Pass");
if(a>=75)
g.setText("Distinction");
else if(a>=60)
g.setText("First Class");
else if(a>=40)
g.setText("Second Class");
}
else
{
r.setText("Fail");
g.setText("No grade");
}
}
}

Adapter Class
Most listener interfaces contain more than one method. For example the
MouseListener interface contains five methods: Even if you care only about mouse
clicks, if your class directly implements mouselistener, then you must implements all
five mouselistener methods. Methods for those events you don't care about can have
empty bodies.

The API generally includes an adapter class for each listener interface with more than
one method. For example, the MouseAdapter class implements the MouseListener
interface. An adapter class implements empty versions of all its interfaces methods.

To use an adapter, you create a subclass of it, instead of directly implementing a


listerner interface. For example, by extending MouseAdapter, your class inherits
empty definitions of all five of the methods that Mouslistener contains.

/* an example of extending an adapter class instead of directly implementing a


listener interface */

public class MyClass extends MouseAdapter


{

146
…………..
someobject.addMouseListener(this);
…………
public void mouseClicked(MouseEvent e)
{
……
//Event handler implementation goes here
……….
}
}
Program for Adapter Class and Nested Class

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

//<applet code=FrameDemo width=300 height=300></applet>

class MyFrame extends Frame


{
boolean a;
MyFrame( )
{
super("New Window");
a=false;
addWindowListener(new W());
}
class W extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
try
{
setVisible(false);
dispose();
System.exit(0);
}
catch(Exception g)
{
}
}
}
}

public class FrameDemo extends Applet


{
int num=0;
public void init()
{
Button b=new Button("Create Window");
b.addActionListener(new B());
add(b);
}
class B implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
MyFrame mf = new MyFrame();
mf.setSize(300,300);
mf.setVisible(true);
mf.setTitle("window -"+num);

147
++num;
}
}
}

Listener Interface Adapter Class Listener Methods


ActionListener None actionperformed(ActionEvent)
AdjustmentListener None adjustmentvalueChanged(Ajustment
Event)
ComponentListener ComponentAdapter componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
ContainerListener ContainerAdapter componentAdded(ComponentEvent)
componentRemoved(ComponentEvent)
FocusListener FocusAdapter focusGained(FocusEvent)
focusLost(FocusEvent)
ItemListener None itemStateChanged(ItemEvent)
KeyListener KeyAdapter keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
TextListener None textValueChanged(TextEvent)
MouseListener MouseAdapter mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener MouseMotionAdapter MouseDragged(MouseEvent)
MouseMoved(MouseEvent)
WindowListener WindowAdapter windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowOpened(WindowEvent)

Summary:

1. The modern approach of handling events is baded on the delegation event


model, which defines standard and consistent mechanisms to generate and
process events.

2. In delegation event model, listeners must register with a source in order to


receive an event notification.

3. An event is an object that describes a state change in the source

4. A source is an object that generates an event

5. A listener is an object that is notified when an event occurs.

6. An adapter class proved an empty implementation of all the methods in an


event listener interface.

148
22. Frames and Menu

22.1 Frames:

The Frame class is used to create standard application windows. The Frame window
is a full-fledged window by itself that can contain the following user interface
elements. i.e the separate pop-up window their own files, Resides angles and menu
bars.

1. Title bar
2. Menu Bar
3. Control Elements - these are UI components that are added to the Frame
using the add() method of the Container.

Steps to create Frame Window.

1. Create a subclass of Frame window.


2. Create a constructor within the subclass.
3. Call base constructor using the super keyword.
4. Once you have defined a frame subclass, you can create an object of the
class. This causes the frame window to come into existence, but it will not be
initially visible. You make it visible by calling setVisible( ). You can set the
size of the window explicitly by calling setSize( ) method.

Frame Constructors are:

Constructors Description
Frame() Creates a title frame, which is initially invisible
Frame(String) Creates a fram with the String as the title.

Unlike Panels, a Frame object is rarely created directly from the applet. Since the
frame is a separate pop-window, the events generated by the UI element in the
frame are not sent to the applet. Instead, these events are sent to Frame object.

To handle these events, the Frame class should be customized by deriving a sub-
class from it. This sub-class can have all event handlers specific to the problem.

public class MyFrame extends Frame


{

//add your methods and event handlers here


}
Methods can be used in Frames are :

Methods Description
setVisible(Boolean) Makes the frame or window visible
setSize(Dimension) Resizes the frame to the specified width and
height
setLocation(int, int) Moves the frame to the specified coordinates.
getLocation() Returns the current coordinates of the Frame as
a points object. In case of top level windows like
frames the location is in screen coordinate
system.

Note: All the methods are belong to the Component class

149
The Frame class also provide methods that allows getting and setting the title of the
Frame and other methods are listed below.

Methods Description
getTitle() Returns the title of the Frame as a String
setTitle(String) Changes the title of the Frame to the
specified String.
dispose() Releases all the resources related to the
window. The window is removed from the
screen.

When the user attempts to close the frame an event, with id WINDOW CLOSING
event type is generated. The customized frame class should handle this event to
dispose the frame.

Program:

import java.awt.*;
import java.awt.event.*;

public class MyText extends Frame implements ActionListener


{
Label l1,l2,l3;
Button b1;
TextField t1,t2,t3;
MyText ()
{
super("Addition Window");
setLayout(new FlowLayout());
l1=new Label("Enter the first no:");
l2=new Label("Enter the second no:");
l3=new Label("Result : ");
t1= new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
b1= new Button("SUM");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str;
str = t1.getText( );
int n1= Integer.parseInt(str);
str = t2.getText( );
int n2=Integer.parseInt(str);
int n= n1+n2;
t3.setText(n+" ");
}
}
class FrameDemo
{
public static void main(String arg[])

150
{
MyText mf=new MyText ();
mf.setSize(300,300);
mf.setVisible(true);
}
}

22.2 Panel:

The Panel class in a non-abstract, recursively nestable, container. The panel can
contain UI components or other containers.

The panel object can be constructed using the following code:

Syntax: Panel p1 = new Panel();

The add() method of the Container class can be used to add a component to the
panel.
p1.add(myButton);

Like all containers, the layout of the Panel can be set using the setLayout() method

22.3 Menus

22.3.1 Normal Menus:

A menubar displays a list of top-level menu choice. Each choice is associated with a
drop-down menu. This concept is implemented in Java by the following classes.
1. MenuBar
2. Menu
3. Menu Item
In general a menuBar contains one or more menu objects. Each objects contains
a list of menu items. Each menu item represents something that can be selected by
the user.

Steps to create a Menu Bar:

1. Create a Frame Window.


2. Create an instance of Menu Bar.

Syntax: MenuBar obj = new MenuBar( );

3. create instances of menu that will deifned the selection displaced on the
menubar.
Syntax: Menu obj =new Menu (String option name);
4. create instances of menu item.
Syntax: MenuItem obj =new MenuItem (String option name);
5. Once you have created a menu item, you must add the item to a menu
object by using add.
6. Once you have added all items to a menu Object, you can add menu that
object to the menu bar using add.
7. Once you have added all menus to a menu bar, you can add menu bar to the
frame using setMenuBar( ).
8. Menus only generate events when an item of type menu is selected. They do
not generate events when a menu bar is accessed to display a drop-down

151
menu. Each time a menu item is selected, an actionevent is generated.
Thus you must implement ActionListener interface.

Program:

import java.awt.*;
import java.awt.event.*;

class Myframe extends Frame implements ActionListener


{
Myframe( )
{
super(“Frame Menu”);
MenuBar mbr= new MenuBar( );

Menu file = new Menu(“File”);


Menu edit = new Menu(“Edit”);
Menu color = new Menu(“Color”);

MenuItem f1=new MenuItem(“New”);


MenuItem f2=new MenuItem(“Open”);
MenuItem f3=new MenuItem(“Save”);
MenuItem bar=new MenuItem(“-“);
MenuItem f4=new MenuItem(“Close”);
MenuItem f5=new MenuItem(“Print”);
MenuItem f6=new MenuItem(“Exit”);

MenuItem e1=new MenuItem(“Cut”);


MenuItem e2=new MenuItem(“Copy”);
MenuItem e3=new MenuItem(“Paste”);

MenuItem c1= new MenuItem(“Red”);


MenuItem c2=new MenuItem(“Green”);
MenuItem c3=new MenuItem(“Blue”);
MenuItem c4=new MenuItem(“Pink”);
MenuItem c5=new MenuItem(“Magenta”);

file.add(f1);
file.add(f2);
file.add(f3);
file.add(bar);
file.add(f4);
file.add(f5);
file.add(f6);

edit.add(e1);
edit.add(e2);
edit.add(e3);

color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);

mbr.add(file);
mbr.add(edit);
mbr.add(color);

setMenuBar(mbr);

152
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else
setBackground(Color.magenta);
}
}
class MenuDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

22.3.2 Creating Sub Menu:

Program:

import java.awt.*;
import java.awt.event.*;
class MyMenu extends Frame implements ActionListener
{
Font f;
MyMenu ( )
{
super(“Font Menu”);
MenuBar mbr=new MenuBar( );

Menu file = new Menu(“File”);


Menu edit = new Menu(“Edit”);
Menu format = new Menu(“Format”);

Menu color = new Menu(“Color”);


Menu fname = new Menu(“Font Name”);
Menu fstyle = new Menu(“Font Style”);
Menu fsize = new Menu(“Font Size”);

MenuItem f1 = new MenuItem(“New”);


MenuItem f2 = new MenuItem(“Open”);
MenuItem f3 = new MenuItem(“Save”);
MenuItem f4 = new MenuItem(“Close”);
MenuItem f5 = new MenuItem(“Print”);
MenuItem f6 = new MenuItem(“Exit”);

153
MenuItem e1 = new MenuItem(“cut”);
MenuItem e2 = new MenuItem(“copy”);
MenuItem e3 = new MenuItem(“paste”);

MenuItem c1 = new MenuItem(“Red”);


MenuItem c2 = new MenuItem(“Green”);
MenuItem c3 = new MenuItem(“Blue”);
MenuItem c4 = new MenuItem(“Pink”);
MenuItem c5 = new MenuItem(“Magenta”);

MenuItem fn1 = new MenuItem(“Times New Roman”);


MenuItem fn2 = new MenuItem(“Arial”);
MenuItem fn3 = new MenuItem(“Comic Sans MS”);
MenuItem fn4 = new MenuItem(“Arial Black”);
MenuItem fn5 = new MenuItem(“courier new”);

MenuItem fs1 = new MenuItem(“Regular”);


MenuItem fs2 = new MenuItem(“Bold”);
MenuItem fs3 = new MenuItem(“Italic”);
MenuItem fs4 = new MenuItem(“Bold Italic”);

MenuItem s1 = new MenuItem(“24”);


MenuItem s2 = new MenuItem(“28”);
MenuItem s3 = new MenuItem(“32”);
MenuItem s4 = new MenuItem(“36”);
MenuItem s5 = new MenuItem(“40”);
file.add(f1);
file.add(f2);
file.add(f3);
file.add(f4);
file.add(f5);
file.add(f6);
edit.add(e1);
edit.add(e2);
edit.add(e3);

color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);
fname.add(fn1);
fname.add(fn2);
fname.add(fn3);
fname.add(fn4);
fname.add(fn5);
fstyle.add(fs1);
fstyle.add(fs2);
fstyle.add(fs3);
fstyle.add(fs4);
fstyle.add(fs5);
fsize.add(s1);
fsize.add(s2);
fsize.add(s3);
fsize.add(s4);
fsize.add(s5);

format.add(color);
format.add(fname);
format.add(fstyle);
format.add(fsize);

154
mbr.add(file);
mbr.add(edit);
mbr.add(format);
setMenubar(mbr);
f1.addActionListener(this);
f2.addActionListener(this);
f3.addActionListener(this);
f4.addActionListener(this);
f5.addActionListener(this);
f6.addActionListener(this);
e1.addActionListener(this);
e2.addActionListener(this);
e3.addActionListener(this);

c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
fn1.addActionListener(this);
fn2.addActionListener(this);
fn3.addActionListener(this);
fn4.addActionListener(this);
fn5.addActionListener(this);
fs1.addActionListener(this);
fs2.addActionListener(this);
fs3.addActionListener(this);
fs4.addActionListener(this);
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
s4.addActionListener(this);
s5.addActionListener(this);
f = new Font(“Times New Roman”,Font.PLAIN,20);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionPerformed( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else if(str.equals(“Magenta”))
setBackground(Color.magenta);
else if(str.equals(“Times New Roman”))

f=new Font(“Times New Roman”,f.getStyle( ),f.getSize( ));


else if(str.equals(“Arial”))
f=new Font(“Arial”,f.getStyle( ),f.getSize( ));
else if(str.equals(“Comic Sans MS”))
f=new Font(“Comic Sans MS”,f.getStyle( ),f.getSize( ));
else if(str.equals(“Arial Black”))
f=new Font(“Arial Black”,f.getStyle( ),f.getSize( ));
else if(str.equals(“Courier New”))
f=new Font(“Courier New”,f.getStyle( ),f.getSize( ));
else if(str.equals(“Regular”))
f=new Font(f.getName( ),Font.PLAIN,f.getSize( ) );
else if(str.equals(“Bold”))

155
f = new Font(f.getName( ),Font.BOLD,f.getSize( ));
else if(str.equals(“Italic”))
f=new Font(f.getName(),Font.Italic,f.getSize( ));
else if(str.equals(“Bold Italic”))
f=new Font(f.getName( ),Font.BOLD+Font.ITALIC,f.getSize());
else if(str.equals(“24”))
f=new Font(f.getName( ),f.getStyle( ),24);
else if(str.equals(“28”))
f =new Font(f.getName( ),f.getStyle( ),28);
else if(str.equals(“32”))
f =new Font(f.getName( ),f.getStyle( ),32);
else if(str.equals(“36”))
f = new Font(f.getName( ),f.getStyle( ),36);
else if(str.equals(“40”))
f = new Font(f.getName( ),f.getStyle( ),40);
repaint();
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawstring(“Welcome to Java”,100,100);
}
}
class SubMenuDemo
{
public static void main(String args[])
{
MyMenu mf = new MyMenu ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

156
22.3.3 Checkbox MenuItem:

You can create a checkable Menuitem by using the class Checkbox MenuItem.

Syntax:

CheckboxMenuItem obj= new CheckboxMenuItem (String option name);

Here option name is the name shown in the menu. Checkable items operable as
toggle. You can obtain the status of the checkable item by calling getState( ). If the
item is checked, getState( ) returns true. Otherwise it returns false.
Each time a checkbox MenuItem is checked or unchecked an itemevent is generated.
Thus we must implemented the ItemListener interface.

Program:

import java.awt.*;
import java.awt.event.*;

class Myframe extends Frame implements ActionListener,


ItemListener
{
Font f;
CheckboxMenuItem fs1,fs2;
Myframe( )
{
super("CheckBoxMenu");
MenuBar mbr = new MenuBar( );

Menu file = new Menu("File");


Menu edit = new Menu("Edit");
Menu format = new Menu("Format");

Menu color = new Menu ("Color");


Menu fname = new Menu ("fname");
Menu fstyle = new Menu ("fstyle");
Menu fsize = new Menu ("fsize");

MenuItem f1=new MenuItem("New");


MenuItem f2= new MenuItem("Open");
MenuItem f3=new MenuItem("Close");
MenuItem f4=new MenuItem("Save");
MenuItem f5=new MenuItem("Print");
MenuItem f6=new MenuItem("Exit");
MenuItem e1= new MenuItem("Cut");
MenuItem e2= new MenuItem("Copy");
MenuItem e3 = new MenuItem("Paste");

MenuItem c1= new MenuItem("Red");


MenuItem c2 = new MenuItem("Green");
MenuItem c3 = new MenuItem("Blue");
MenuItem c4 = new MenuItem("Pink");
MenuItem c5 = new MenuItem("Magenta");

MenuItem fn1= new MenuItem("Times New Roman");


MenuItem fn2 = new MenuItem("Arial");
MenuItem fn3 = new MenuItem("Comic Sans MS" );
MenuItem fn4 = new MenuItem("Arial Black");
MenuItem fn5 = new MenuItem("Courier New");

157
fs1 = new CheckboxMenuItem("Bold");
fs2 = new CheckboxMenuItem("Italic");

MenuItem s1 = new MenuItem("24");


MenuItem s2 = new MenuItem("28");
MenuItem s3 = new MenuItem("32");
MenuItem s4 = new MenuItem("36");
MenuItem s5 = new MenuItem("40");
file.add(f1);
file.add(f2);
file.add(f3);
file.add(f4);
file.add(f5);
file.add(f6);
edit.add(e1);
edit.add(e2);
edit.add(e3);
color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);
fname.add(fn1);
fname.add(fn2);
fname.add(fn3);
fname.add(fn4);
fname.add(fn5);
fstyle.add(fs1);
fstyle.add(fs2);
fsize.add(s1);
fsize.add(s2);
fsize.add(s3);
fsize.add(s4);
fsize.add(s5);
format.add(color);
format.add(fname);
format.add(fstyle);
format.add(fsize);
mbr.add(file);
mbr.add(edit);
mbr.add(format);
setMenuBar(mbr);
f1.addActionListener(this);
f2.addActionListener(this);
f3.addActionListener(this);
f4.addActionListener(this);
f5.addActionListener(this);
f6.addActionListener(this);
e1.addActionListener(this);
e2.addActionListener(this);
e3.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
fn1.addActionListener(this);
fn2.addActionListener(this);
fn3.addActionListener(this);
fn4.addActionListener(this);
fn5.addActionListener(this);

158
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
s4.addActionListener(this);
s5.addActionListener(this);

fs1.addItemListener(this);
fs2.addItemListener(this);
f=new Font("Times New Roman",Font.PLAIN,20);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Red"))
setForeground(Color.red);
else if(str.equals("Green"))
setForeground(Color.green);
else if(str.equals("Blue"))
setForeground(Color.blue);
else if(str.equals("Pink"))
setForeground(Color.pink);
else if(str.equals("Magenta"))
setForeground(Color.magenta);

else if(str.equals("Times New Roman"))


f = new Font("Times New Roman",f.getStyle( ),f.getSize( ));
else if(str.equals("Arial"))
f= new Font("Arial",f.getStyle( ),f.getSize( ));
else if(str.equals("Arial Black"))
f = new Font("Arial Black",f.getStyle( ),f.getSize( ));
else if(str.equals("Courier New"))
f = new Font("Courier New",f.getStyle( ),f.getSize( ));
else if(str.equals("Comic Sans MS"))
f=new Font("Comic Sans MS",f.getStyle( ), f.getSize( ));

else if(str.equals("24"))
f = new Font(f.getName( ),f.getStyle( ),24);
else if(str.equals("28"))
f= new Font(f.getName( ),f.getStyle( ),28);
else if(str.equals("32"))
f = new Font(f.getName( ),f.getStyle( ),32);
else if(str.equals("36"))
f = new Font(f.getName( ),f.getStyle( ),36);
else if(str.equals("40"))
f = new Font(f.getName( ),f.getStyle( ),40);
repaint( );
}
public void itemStateChanged(ItemEvent ie)
{
if(fs1.getState( )== true && fs2.getState( ) ==false)
f=new Font(f.getName( ),Font.BOLD,f.getSize( ));
else if(fs1.getState( )== false && fs2.getState( )==true)
f=new Font(f.getName( ),Font.ITALIC,f.getSize( ));
else if(fs1.getState( )== true && fs2.getState( )==true)
f=new Font(f.getName( ),Font.BOLD+Font.ITALIC,f.getSize( ));
else
f=new Font(f.getName( ),Font.PLAIN,f.getSize( ));
repaint();
}
public void paint(Graphics g)

159
{
g.setFont(f);
g.drawString("Welcome to Java",100,100);
}
}

class CMenu
{
public static void main(String args[])
{
Myframe mf= new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

22.3.4 Popup Menu (Shortcut Menu)

It works just like Menu but produces a menu that can be displayed at a specific
location. PopupMenu provides a flexible, useful, alternative for some types of menu
situation.

Steps to create PopupMenu:

1. create an instance of PopupMenu.


syntax: PopupMenu obj = new PopupMenu( );
2. create instances of MenuItem that will define the selections displayed on the
PopupMenu.
3. Once you have created a MenuItem, you must add the item to the PopupMenu
object by using add( );.
4. Once you added all the items to a PopupMenu object, you can add that object
to a framewindow by using add( );.

Program:

import java.awt.*;
import java.awt.event.*;
class Popup extends Frame implements ActionListener
{
PopupMenu P1;
Popup( )
{
super(“Popup Menu”);
P1= new PopupMenu( );
MenuItem c1 = new MenuItem(“Red”);
MenuItem c2 = new MenuItem(“Blue”);
MenuItem c3 = new MenuItem(“Green”);
MenuItem d = new MenuItem("-");
MenuItem c4 = new MenuItem(“Pink”);
MenuItem c5 = new MenuItem(“Magenta”);
P1.add(c1);
P1.add(c2);
P1.add(c3);
P1.add(d);
P1.add(c4);
P1.add(c5);
add(P1);
c1.addActionListener(this);
c2.addActionListener(this);

160
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
addMouseListener(new Mouse());
}
class Mouse extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
P1.show(me.getComponent(),me.getX(),me.getY( ));
}

}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else
setBackground(Color.magenta);
}
}
class PopMenuDemo
{
public static void main(String args[])
{
Popup mf= new Popup( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

22.4 Dialogs:

Dialog box, like frame, is pop-up llwindow on which user inteface components can be
laid out. Usally they are used to display message and get specific information from
the user. Though a dialog resembles and behaves like a frame, ther are some major
differences between the two. They are:

▪ Unlike frames, a dialog has parent (0r a owner) window. The dialog is
automatically closed when the parent window is closed.

▪ The dialog box usually contains a number of UI component suitably arranged


(laid out). Letting the user adjust the size of the dialog may affect the layout
of the component in the dialog.

161
▪ A dialog box can be made modal. A modal dialog prevents user input to other
windows in the application until dialog is closed.

162
Constructors Description
Dialog(Frame, boolean) Create a new dialog, which is initially invisible.
The frame acts as the parent of the dialog. The
dialog is closed when its parent is closed. The
Boolean value specifies whether the dialog is
modal or not
Dialog(Frame, String, boolean) Creates a new dialog with the specified string
as the title. The other two parameters are the
same as in the previous constructor.

22.5 File Dialog:

File Dialog provides a platform-specific dialog that lets us to choose a file and to save
or open it.

To create a file dialog use one of the constructors show below:

Constructors Description
FileDialog(Frame, String) Creates an Open File Dialog that lets the user
select a file name from a file listing
The Frame acts as the parent (owner) of the
dialog. The String is the title of the file dialog.
FileDialog(Frame, String, int) This constructor behaves exactly the same way as
the pervious one, except that the int parameter is
used to determine whether the dialog is for
loading or saving a file. The two options are
FileDialog.LOAD and FileDialog.SAVE.

Note: the file dialog does not actually load or save files. It is used only to select a
file from the file listing. The file dialog is modal dialog.

FileDialog f= new FileDialog(this, “Select File”);


f.setVisible(true);

Methods Description
GetDirectory() Returns the directory of the file selected as a String
GetFile() Returns the name of the file selected as as String. This
method returns a null string if the user dismisses the
dialog without selecing a file.

Program:

Creating Simple NotePad using Java

import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
public class Editor extends Frame
{
String filename;
TextArea tx ;
Clipboard clip=getToolkit().getSystemClipboard();

163
Editor()
{
setLayout(new GridLayout(1,1));
tx=new TextArea();
add(tx);
setTitle("untitled");
MenuBar mb=new MenuBar();
Menu F=new Menu("File");
MenuItem n=new MenuItem("New");
MenuItem o=new MenuItem("Open");
MenuItem s=new MenuItem("Save");
MenuItem e=new MenuItem("Exit");
n.addActionListener(new New());
F.add(n);
o.addActionListener(new Open());
F.add(o);
s.addActionListener(new Save());
F.add(s);
e.addActionListener(new Exit());
F.add(e);
mb.add(F);
Menu E=new Menu("Edit");
MenuItem cut=new MenuItem("Cut");
MenuItem copy=new MenuItem("Copy");
MenuItem paste=new MenuItem("Paste");
cut.addActionListener(new Cut());
E.add(cut);
copy.addActionListener(new Copy());
E.add(copy);
paste.addActionListener(new Paste());
E.add(paste);
mb.add(E);
setMenuBar(mb);

mylistener mylist=new mylistener();


addWindowListener(mylist);
}
class mylistener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
dispose();
}
}
class New implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
filename="untitled"
tx.setText(" ");
setTitle(filename);
}
}
class Open implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd=new FileDialog(Editor.this, "Select
File",FileDialog.LOAD);
fd.show();

164
if(fd.getFile()!=null)
{
filename=fd.getDirectory()+fd.getFile();
setTitle(filename);
ReadFile();
}
tx.requestFocus();
}
}
class Save implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd=new FileDialog(Editor.this,"Save
File",FileDialog.SAVE);
fd.show();
if(fd.getFile()!=null)
{
filename=fd.getDirectory()+fd.getFile();
setTitle(filename);
try
{
DataOutputStream d=new DataOutputStream(new
FileOutputStream(filename));
String line=tx.getText();
BufferedReader br=new BufferedReader(new
StringReader(line));
while((line=br.readLine())!=null)
{
d.writeBytes(line+"\r\n");
}
d.close();

}
catch(Exception ex)
{
System.out.println("File not found");
}
tx.requestFocus();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
void ReadFile()
{
BufferedReader d;
StringBuffer sb=new StringBuffer();
try
{
d=new BufferedReader(new FileReader(filename));
String line;
while((line=d.readLine())!=null)
sb.append(line+"\n");
tx.setText(sb.toString());
d.close();

165
}
catch(FileNotFoundException fe)
{
System.out.println("File not found");
}
catch(IOException ioe)
{
}
}
class Cut implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=tx.getSelectedText();
StringSelection ss=new StringSelection(sel);
clip.setContents(ss,ss);
tx.replaceRange("
",tx.getSelectionStart(),tx.getSelectionEnd());
}
}
class Copy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=tx.getSelectedText();
StringSelection clipString=new StringSelection(sel);
clip.setContents(clipString,clipString);
}
}
class Paste implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Transferable cliptran=clip.getContents(Editor.this);
try
{
String sel=(String)
cliptran.getTransferData(DataFlavor.stringFlavor);
tx.replaceRange(sel,tx.getSelectionStart(),tx.getSelec
tionEnd());
}
catch(Exception exc)
{
System.out.println("Not String flavor");
}
}
}
public static void main(String args[])
{
Frame f=new Editor();
f.setSize(500,400);
f.setVisible(true);
f.show();
}
}

166
23. JFC - Java Foundation Classes
23.1 Introduction to JFC

The earlier version of java were released with some simple libraries. JDK1.2 was
introduced with a new set of packages, the Java Foundation Classes, or JFC that
includes an improved user interface called the Swing Components.

23.2 Swings:

Swing componets facilitate efficient graphical user interface(GUI) development.


These components are a collection of lightweight visual components. Swing
components contain a replacement for the heavyweight AWT components as well
as complex user-interface components such as trees and tables.

Swing Components conatin a pluggable look and feel (PL&F). This allows all
applications to run with the native look and feel on different platforms. PL&F
allows applications to have the same behavior on various platforms(os). JFC contains
operating system neutral look and feel.

Swing Package can be imported as javax.swing

JComponent

JColor Abstract JCombo JFile JLabel JButton JList


Chooser Button Box Chooser

JToggle JMenu
Button Bar

JRadio JCheck
Button Box JCheckBox JMenu JRadioButton
Menu Item MenuItem

Windows
Applet

Dialog Frame JWindow

JApplet

JDialog JFrame

167
23.3.1 JOptionPane:

Dialog boxes are windows that typically are used to display important messages to
the user of an application. Java2 already includes class dialog containing
information.

Syntax : To Display Input Box.

JOptionPane.showInputDialog(String str);

The argument showInputDialog indicates to the user what to do in the textfield . The
message is called a prompt because it directs the user to take a specific action. The
user types characters in the text field, then clicks on button to written the string to
the program.

Note: If the user clicks the cancel button, a run time logical error will occur.

Syntax : To display a message box.

JOptionPane.showMessageDialog(Container obj,”msg information " ,title of


dialogbox”, type of message);

Here the first argument will be the keyword null. The second argument is the string
to display. The third argument is the string to display title bar at the dialog. The
fourth argument is the value indicating the type of message dialog to display.

Message Dialog type:-

1. JOptionPane.PLAIN_MESSAGE: It displays a dialog that simply contain a


message with no icon.
2. JOptionpane.ERROR_MESSAGE:
It displays a dialog that indicates an error to the application user.
3. JOptionPane.INFORMATION_MESSAGE:
It displays a dialogbox withan informational message to the application user.
The user can simpy dismiss the dialog.
4. JoptionPane.WARNING_MESSAGE:
It displays a dialog that wants the application user of a potential problem.
5. JoptionPane.QUESTION_MESSAGE:
It displays a dialog that posses a question to the application user. This
normally requires a response such as clicking a yes or no button.

SUM
 i
Ok 1 ?

Program:

import javax.swing.*;
class Jop
{
public static void main (String args[])
{
String str;
int a,b,c;

168
try
{
str = JOptionPane.showInputDialog("Enter the 1st no: ");
a = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Enter the 2nd no: ");
b = Integer.parseInt(str);
c = a+b;
JOptionPane.showMessageDialog(null,"SUM " +c, "Result Box",

JOptionPane. INFORMATION_MESSAGE);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Format Error", "Error Window",

JOptionPane. ERROR_MESSAGE);
}
}
}
23.3.2 JFrame :

Unlike a Frame, a JFrame has some notion of how to respond when the user
attempts to close the window. The default behavior is to simply hide the JFrame
when the user closes the window. To change the default behavior, you invoke the
method setDefaultCloseOperation(int). To make the JFrame behave the same as
a Frame instance, use

Program:

import javax.swing.*;
import java.awt.*;
class Myframe extends JFrame
{
Myframe()
{
super(“Frame Window”);
}
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString(“Welcome to java”,100,100);
g.drawOval(100,100,50,50);
}
}
class JFrameDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

169
23.3.3 JPanel:

JPanel is a generic lightweight container. JPanel can be used as a dedicated


drawing area that can receive new events and if often extended to create new
components.

Syntax
JPanel panelobj = new JPanel( );

To add Panel to Frame

Syntax :
getContentPane.add(panelobj);

23.3.4 JLabel:

Syntax
JLabel obj = new JLabel (String str);

Program:

import java.awt.*;
import javax.swing.*;
class Mypanel extends JFrame
{
Mypanel ( )
{
super(“Label Demo”);
JPanel jp = new JPanel( );
Font f= new Font("Verdana",Font.BOLD,20");
JLabel L1= new JLabel(“Welcome to JFC Swing“);
L1.setFont(f);
jp.add(L1);
getContentPane().add(jp);
}
}
class JLableDemo
{
public static void main (String args[])
{
Mypanel mf = new Mypanel ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.3.5 JButton:

Syntax: JButton obj = new JButton (String name);

Note:

23.3.5.1 Shortcut Key :

A Shortcut Key is the underlined character you find in buttons. You can select a
button by pressing a combination of the alt key a character. You can set the
shortcut key using setMnemonic method.

170
23.3.5.2 Adding Tool Tips:

Tool tips are short informative messages that you see when you reset the
mousecursor on a button.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyButton extends JFrame implements ActionListener
{
JPanel jp;
MyButton( )
{
super("ShortCut Frame");
jp = new JPanel( );
JButton b1 = new JButton("red");
JButton b2 = new JButton("green");
JButton b3 = new JButton("blue");
JButton b4 = new JButton("pink");
JButton b5 = new JButton("magenta");
b1.setMnemonic('r');
b2.setMnemonic('g');
b3.setMnemonic('b');
b4.setMnemonic('p');
b5.setMnemonic('m');
b1.setToolTipText("set red background color");
b2.setToolTipText("set green background color");
b3.setToolTipText("set blue background color");
b4.setToolTipText("set pink background color");
b5.setToolTipText("set magenta background color");

jp.add(b1);
jp.add(b2);
jp.add(b3);
jp.add(b4);
jp.add(b5);

getContentPane( ).add(jp);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals("red"))
jp.setBackground(Color.red);
else if(str.equals("green"))
jp.setBackground(Color.green);
else if(str.equals("blue"))
jp.setBackground(Color.blue);
else if(str.equals("pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
public static void main(String arg[])
{

171
MyButton mb = new MyButton();
mb.setSize(400,150);
mb.setVisible(true);
mb.setLocation(200,200);
}
}

23.3.5.3 Button with Image:

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyImage extends JFrame
{
MyImage ( )
{
super(“ImageButton”);
JPanel jp = new JPanel( );
JButton b1 = new JButton(“Image”);

Icon img = new ImageIcon(“ganesh.jpg”);


b1.setIcon(img);
jp.add(b1);
getContentPane().add(jp);
}
}
class JImageDemo
{
public static void main(String args[])
{
MyImage mf = new MyImage ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.4 Border Property

The Jcomponent class contains a Border property. This refer a class that implements
the Border interface. Painting of the border is handled by the component when a
border is specified for the component. When a border has been set for a Jcomponent
instance, the size of the border is used as the insets property for that component.

23.4.1 Adding Borders to Buttons

Program:

import java.awt.*;
import javax.swing.border.*;
import javax.swing.*;

class Mybrd extends JFrame


{
JPanel jp;
Mybrd( )
{
super("Border");
jp = new JPanel();
Font f= new Font("Arial",Font.BOLD,20);

172
JLabel l1 = new JLabel("World Computers");
JLabel l2 = new JLabel("World Computers");
JLabel l3 = new JLabel("World Computers");
JLabel l4 = new JLabel("World Computers");
l1.setFont(f);
Border line1 = BorderFactory.createMatteBorder(0,0,5,5,Color.gray);
Border line2 = BorderFactory.createBevelBorder(BevelBorder.RAISED);
Border line3=

BorderFactory.createEtchedBorder(Color.red,Color.yellow);
Border line4 = BorderFactory.createLineBorder(Color.pink,5);
l1.setBorder(line1);
l2.setBorder(line2);
l3.setBorder(line3);
l4.setBorder(line4);
jp.add(l1);
jp.add(l2);
jp.add(l3);
jp.add(l4);
getContentPane().add(jp);

getContentPane().add(jp);
}
}
class BorderDemo1
{
public static void main(String args[])
{
Mybrd mf = new Mybrd( );
mf.setSize( 300,300);
mf.setVisible(true);
}
}

23.5 Java 2D API :

The new Java 2D api provided advanced two dimentsional graphics, capabilities for
programmers who required detailed and complex graphical manipulations. Drawing
with the Java 2D api is accomplished with an instance of Graphics 2D.

Class Graphics 2D is a subclass of Graphics. To access the Graphics 2D capabilities,


we must downcast the graphics reference passed to paint to the Graphics 2D
reference with a statement such as Graphics 2D g2d = (Graphics2D)g ; class
gradient paint helps draw a shape in a gradually changing colours called a gradient.
The gradient paint constumer requires seven arguments. The 1st two arguments
specifies the starting co-ordinates for the gradient.
The third argument specifies starting colour of the gradient.
The 4th and 5th arguments specifies starting co-ordinate for the gradient.
The 6th argument specifies the ending colour. The last argument should be true.

GradientPaint(float x1, float y1, Color color1, float x2, float y2,
Color color2)
Constructs a simple acyclic GradientPaint object.
GradientPaint(float x1, float y1, Color color1, float x2, float y2,
Color color2, boolean cyclic)
Constructs either a cyclic or acyclic GradientPaint object depending on the boolean
parameter

173
Program:

23.6 JColorChooser:

One of the newer feature of Java is the predefined GUI Component JColorChooser
for selecting colours.

Syntax :
JChooseColor.showDialog(this,String title,default Color);

showDialog of class JColorChooser is used to dialog. This method returns the


selected color object. Method showDialog takes 3 arguments as this, a String to
display in the title bar of the dialog box and the initial color selected for the dialog.

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyColor extends JFrame implements ActionListener
{
JPanel jp;
Jbutton b1;
MyColor ()
{
super(“Color Chooser”);
b1 = new JButton(“Color”);
jp.add(b1);
b1.addActionListener(this);
getContentPane( ).add(jp);
}
}
public void actionPerformed(ActionEvent ae)
{
Color c;
c= JColorChooser.showDialog(this,”Color Box”,Color.red);
jp.setBackground(c);
}
}
class JColorChooserDemo
{
public static void main(String args[])
{
MyColor me = new MyColor ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

174
23.7 JTextField:

Program:

import java.awt.*;
import java.awt.event.*;
import javax.awt.swing.*;
import javax.awt.swing.event.*;
class MyText extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
MyText ( )
{
super(“Text Demo”);
JPanel jp = new JPanel( );
JLabel l1 = new JLabel (“Enter the 1st no :”);
JLabel l2 = new JLabel (“Enter the 2nd no:”);
JLabel l3 = new JLabel (“Result :”);
t1 = new JTextField(5);
t2 = new JTextField(5);
t3 = new JTextField(5);
JButton b1 =new JButton(“SUM”);
jp.add(l1);
jp.add(t1);
jp.add(l2);
jp.add(t2);
jp.add(t3);
jp.add(l3);
jp.add(t3);
jp.add(b1);
b1.addActionListener(this);
getContentPane( ).add(jp);//add panel to the JFrame
}
public void actionPerformed(ActionEvent ae)
{
String str;
int n1,n2,n3;
str = t1.getText( );
n1 = Integer.parseInt(str);
str = t2.getText( );
n2 = Integer.parseInt(str);
n3 = n1+n2;
t3.setText(n3+ “ “);
}
}
class JTextFieldDemo
public static void main(String args[])
{
MyText mf = new MyText( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

175
23.8 JPasswordField:

JPasswordField is a single line text field in which text can be entered by the user
from the keyboard or text can simply be displayed *.

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;

class Mypass extends JFrame implements ActionListener


{
JTextField t1;
JPasswordField t2;
JPanel jp;
Mypass( )
{
super("User Window");
jp=new JPanel();
JLabel l1 = new JLabel("User Name :");
JLabel l2 = new JLabel("Password :");
t1 = new JTextField(10);
t2= new JPasswordField(10);
JButton b1 = new JButton("Ok");
JButton b2 = new JButton("Close");
jp.add(l1);
jp.add(t1);
jp.add(l2);
jp.add(t2);
jp.add(b1);
jp.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
getContentPane( ).add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
try
{

if(str.equals("Ok"))
{

String uname=t1.getText();
uname=uname.trim();
String pass=t2.getText();
if(uname.equals("World") && pass.equals("admin"))
{

JOptionPane.showMessageDialog(null,"Username and password are


correct","MessageBox", JOptionPane.INFORMATION_MESSAGE);
}
else
{

JOptionPane.showMessageDialog(null,"Invalid username or password",


"Error Box",JOptionPane.ERROR_MESSAGE);

176
}
}
}
catch(Exception e)
{
System.out.println("Error in user "+e);
}

if(str.equals("Close"))
{
System.exit(0);
dispose();
}
}
}
class Jpass
{
public static void main(String args[])
{
Mypass mf = new Mypass( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.8 JCheckBox:

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Myframe extends JFrame implements ItemListener
{
JTextField t1;
JCheckBox c1,c2;
Myframe()
{
super(“Dialog Box”);
JPanel jp = new JPanel();
t1 = new JtextField(15);
c1 = new JCheckBox(“BOLD”);
c2 = new JCheckBox(“ITALIC”);
jp.add(t1);
jp.add(c1);
jp.add(c2);
c1.addItemListener(this);
c2.addItemListener(this);
getContentPane().add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
Font f;
if(c1.isSelected( ) == true && c2.isSelected ( ) == true)

f = new Font(“Times New Roman”, Font.BOLD+Font.ITALIC,20);


else if(c1.isSelected ( ) == true && c2 .isSelected() ==
false )

f = new Font(“Times New Roman”,Font.BOLD,20);

177
else if(c1.isSelected ( ) == false && c2 .isSelected() ==
true )

f = new Font(“Times New Roman”,Font.ITALIC,20);


else
f = new Font(“Times New Roman”,Font.PLAIN,20);
t1.setFont(f);
}
}
class JCheckboxDemo
{
public static void main(String args[ ])
{
Myframe mf = new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.9 JRadioButton:

JRadioButton are used for single selection among the group of buttons. Frist Create
ButtonGroup and then create a JRadioButton and add Each RadioButton to the
BorderGroup

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyRadio extends JFrame implements ItemListener
{
JRadioButton c1,c2,c3,c4,c5,c6;
JPanel jp;
MyRadio ( )
{
super(“Dialog Box”);
jp = new JPanel( );
ButtonGroup col = new ButtonGroup( );
c1 = new JRadioButton(“Red”);
c2 = new JRadioButton(“Green”);
c3 = new JRadioButton(“Blue”);
c4 = new JRadioButton(“Pink”);
c5 = new JRadioButton(“Magenta”);
c6 = new JRadioButton(“Black”);
col.add(c1);
col.add(c2);
col.add(c3);
col.add(c4);
col.add(c5);
col.add(c6);
jp.add(c1);
jp.add(c2);
jp.add(c3);
jp.add(c4);
jp.add(c5);
jp.add(c6);
c1.addItemListener(this);

178
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
getContentPane( ).add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource ( ) == c1)
jp.setBackground(Color.red);
else if(ie.getSource( ) == c2)
jp.setBackground(Color.green);
else if(ie.getSource( ) == c3)
jp.setBackground(Color.blue);
else if(ie.getSource( ) == c4)
jp.setBackground( Color.pink);
else
jp.setBackground(Color.black);
}
}
class JRadioDemo
{
public void main(String args[])
{
MyRadio mf = new MyRadio ( );
mf.setSize( );
mf.setVisible(true);
}
}

23.10 JCombobox:

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Mycombo extends JFrame implements ItemListener
{
JPanel jp;
JCombobox col;
Mycombo
{
super (“Jcombo Demo”);
jp = new JPanel ( );
col = new JCombobox();
col.addItem(“Red”);
col.addItem(“Green”);
col.addItem(“Blue”);
col.addItem(“Pink”);
col.addItem(“Magenta”);
col.addItem(“Yellow”);
jp.add(col);
col.addItemListener(this);
getContentPane( ).add(jp);
}
public void ItemStateChanged (ItemEvent ie)
{
int n = col.getSelectedIndex( );

179
if(n == 0)
jp.setBackground(Color.red);
else if(n == 1)
jp.setBackground(Color.green);
else if(n == 2)
jp.setBackground(Color.blue);
else if(n == 3)
jp.setBackground(Color. Yellow);
}
}
class JComboboxDemo
{
public static void main(String args[ ])
{
Mycombo mf = new Mycombo ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.11 JList:

A JList is functionally similar to JComboBox menu in that it allows the user to select
one or more object from the list of choices. A Jlist will generate event when it
selection changes, or when any of its items change. The difference between a JList
and a Jcombox menu are given below.

Unlike Jcombox, which display only the single-selected item, the list can be made to
show any number of choices in the visible window.

The JList can be constructed to allow mutiple selections.


Constructor Description
JList() Construct a JList with an empty model
JList(ListModel dataModel) Construct a JList that display the elements in the
specified, non-null model
JList(Object[] listData) Construct a JList that displays the element in the
specified array.
JList(Vector listdata) Construct a JList that displays the elements in
the specified Vector.

Program:

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
class MyList extends JFrame implements ListSelectionListener
{
JPanel jp;
JList col;
MyList( )
{
super("List Demo");
jp = new JPanel( );
String str[ ] =

{"Red","Green","Blue","Pink","Magenta","Yellow"};
col = new JList(str);

180
Border line2 =

BorderFactory.createBevelBorder(BevelBorder.RAISED);
col.setBorder(line2);
jp.add(col);
getContentPane( ).add(jp);
col.addListSelectionListener(this);
}

public void valueChanged(ListSelectionEvent ie)


{
int n = col.getSelectedIndex();
System.out.println(n);
if(n == 0)
jp.setBackground(Color.red);
else if(n == 1)
jp.setBackground(Color.green);
else if(n == 2)
jp.setBackground(Color.blue);
else if(n == 3)
jp.setBackground(Color.pink);
else if(n == 4)
jp.setBackground(Color.magenta);
else
jp.setBackground(Color.yellow);
}
}
class JListDemo
{
public static void main(String args[])
{
MyList mf = new MyList( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.12 JSlider:

JSlider enables the user to select from a range of integer values. JSlider has a thick
marks and the thumb that allows the user to select a value. Jsliders have either a
horizontal orientation or a vertical orientation.

Syntax : thumb min – starting value


value – thumb position
max – Final Value
JSlider obj = new JSlider(orientation,min,max,initial_value);

SwingConstants.HORIZONTAL or SwingConstants.VERTICAL

The second and third argument indicate the minimum and maximum integer values
in the range of values for this Jsliders. The last argument indicates the initial value
of the JSlider. JSliders generate ChangeEvent when a user interacts with the JSlider.
To accesss this event, we have to use ChangeListener(interface) has a method
StateChanged( ) to access the JSlider. Method getValue( ) returns the current
thumb position.

181
Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MySlider extends JFrame implements ChangeListener
{
JPanel jp;
JSlider s1,s2,s3;
MySlider ( )
{
super(“Slider Demo”);
jp = new JPanel( );
s1 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
s2 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
s3 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
jp.add(s1);
jp.add(s2);
jp.add(s3);
s1.addChangeListener(this);
s2.addChangeListener(this);
s3.addChangeListener(this);
getContentPane().add(jp);
}
public void stateChanged(ChangeEvent ce)
{
Color c = new Color(s1.getValue( ),s2.getValue( ),
s3.getValue( ));
jp.setBackground(c);
}
}
class JSliderDemo
{
public static void main(String args[])
{
MySlider mf = new MySlider ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

23.13 JPopMenu

Many of today’s application provide so called context-sensitive popup menus. In


swing, such menus are created with class JPopMenu.

Program:

Program : To Create a PopMenu using Adapter classes

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPopup extends JFrame implements
ActionListener
{
JPanel jp;
JPopupMenu col;

182
MyPopup ( )
{
super("PopMenu");
jp = new JPanel( );
col = new JPopupMenu( );
JMenuItem c1 = new JMenuItem("Red");
JMenuItem c2 = new JMenuItem("Green");
JMenuItem c3 = new JMenuItem("Blue");
JMenuItem c4 = new JMenuItem("Pink");
JMenuItem c5 = new JMenuItem("Magenta");
col.add(c1);
col.add(c2);
col.add(c3);
col.addSeparator();
col.add(c4);
col.add(c5);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
addMouseListener(new press());
addWindowListener(new W());
getContentPane( ).add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals ("Red"))
jp.setBackground(Color.red);
else if(str.equals("Green"))
jp.setBackground(Color.green);
else if(str.equals("Blue"))
jp.setBackground(Color.blue);
else if(str.equals("Pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
class press extends MouseAdapter
{

public void mousePressed (MouseEvent me)


{
col.show(me.getComponent( ),me.getX( ),me.getY( ));
}
}
class W extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
dispose();
System.exit(0);
}
}
}

class Jpop
{
public static void main(String args[])
{

183
MyPopup mf = new MyPopup ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.14 JMenuBar :

This component typically appears at the top of a JFrame, Jwindow and


JinternalFrame. It cannot be added directly of 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 othe component. It
cantinas a set JMenus, with each JMenu respesented a string within the JMenuBar.
When the user clicks one of the text string, the associated menu pop up under the
text string and displays its menu items.

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyMenu extends JFrame implements ActionListener


{
JPanel jp;
MyMenu ( )
{
super("Menu");
jp = new JPanel( );

JMenuBar mbr = new JMenuBar( );

JMenu file = new JMenu("File");


JMenu edit = new JMenu("Edit");
JMenu color = new JMenu("Color");

JMenuItem f1 = new JMenuItem("New");


JMenuItem f2 = new JMenuItem("Open");
JMenuItem f3 = new JMenuItem("Save");
JMenuItem f4 = new JMenuItem("Save as");
JMenuItem f5 = new JMenuItem("Close");
JMenuItem f6 = new JMenuItem("Exit");

JMenuItem e1 = new JMenuItem("Cut");


JMenuItem e2 = new JMenuItem("Copy");
JMenuItem e3 = new JMenuItem("Paste");

JMenuItem c1 = new JMenuItem("Red");


JMenuItem c2 = new JMenuItem("Green");
JMenuItem c3 = new JMenuItem("Blue");
JMenuItem c4 = new JMenuItem("Pink");
JMenuItem c5 = new JMenuItem("Magenta");
file.add(f1);
file.add(f2);
file.addSeparator();
file.add(f3);
file.add(f4);
file.add(f5);
file.add(f6);

184
edit.add(e1);
edit.add(e2);
edit.add(e3);

color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);

mbr.add(file);
mbr.add(edit);
mbr.add(color);

setJMenuBar(mbr);

c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
getContentPane().add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals("Red"))
jp.setBackground(Color.red);
else if(str.equals("Green"))
jp.setBackground(Color.green);
else if(str.equals("Blue"))
jp.setBackground(Color.blue);
else if(str.equals("Pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
}

class JMenuDemo
{
public static void main(String args[])
{
MyMenu mf = new MyMenu ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}

185

You might also like