0% found this document useful (0 votes)
2 views434 pages

Core Java Print

The document provides an overview of Java, highlighting its suitability for network applications due to its platform independence and security features. It discusses the architecture of networks, the functioning of the Internet, and the development of Java, including its history, versions, and features. Additionally, it compares Java with C++, emphasizing Java's object-oriented nature, memory management, and security capabilities.

Uploaded by

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

Core Java Print

The document provides an overview of Java, highlighting its suitability for network applications due to its platform independence and security features. It discusses the architecture of networks, the functioning of the Internet, and the development of Java, including its history, versions, and features. Additionally, it compares Java with C++, emphasizing Java's object-oriented nature, memory management, and security capabilities.

Uploaded by

rajender.s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

TEKZUNE TECHNOLOGIES 1

CORE JAVA NOTES


TEKZUNE TECHNOLOGIES 2

INTRODUCTION TO JAVA

Why languages, like c/c++ are not opted for a network and why
java is a language suited for a network, especially internet.

Interconnection of computers is called network. A network may


contain two or more computers connected with or without a
cable.

The primary purpose of a network is resource sharing, which


means a computer can share its resources like data, memory,
software, hardware, CPU, etc. with other computers on the
network. In the network, one computer may ask the other
computer for some service. The computer, which requests for
some service is called client and the other computer, which
provides that service to the client is called server. A network can
have several clients and servers and such a network is also called
client/server architecture.

Following are the requirements for setting up a network of


computers :

Hardware : Computer systems, Network Interface Cards(NIC),


cables, modems, hubs, satellites, etc.

Software : Any software, which supports networking features ,


like Unix, Linux, Windows NT, etc. so that data can be sent or
received.

Protocol : could be defined as a standard procedure for


regulating data transmission between computers. It specifies the
way to identify the destination and source computers and
establish a connection between them to receive or send data.

For example : TCP/IP or UDP protocols help to divide data into


small packets of several bytes, insert the packets into frames, and
then send the frames to the destination computer over the
network. Protocol is the underlying feature of the software used
on the network.
TEKZUNE TECHNOLOGIES 3

A network of computers within an organization is called Intranet.


An external network connecting an organizations network with
that of another organization is called Extranet.

How does Internet Function ?


Like any network, Internet also requires certain hardware,
software, and protocols to perform its functions. For example,
hardware like computer systems, cables, hubs, routers, satellites,
etc. are needed to connect different computers with each other.
The computer which is connected to Internet Service Providers
(ISP) computer is called client and the ISP’s computer is called
server. Other than ISP servers, many other servers are
maintained and used privately by some organizations. Currently
millions of servers are maintained on Internet. Some servers focus
on a single area like maintaining employee’s attendance in a
company or scheduling the ejobs for the employees of different
branches. Such servers are called application servers. Some
servers provide services purely related to internet, for example,
maintaining the websites and communicationg with clients on the
internet. Such servers are called Web Servers.
A client machine and a server machine on internet also need
software. The software that s installed on an internet client is
called web browser. Popular web browsers are Internet Explorer,
Netscape Navigator, Mozilla Firefox, Mosaic, etc. The software
that s installed on an Internet server machine is called web
server. There are several web serverxs, like IIS(Internet
Information Server), web logic, Web dynamics, Apache, JBoss, etc.
Apart from software, protocols are also used on Internet. The
most widely used protocol on internet is http, which stands for
hyper text transfer protocol. http is responsible for displaying the
html pages(or web pages) on your client machine when you
browse internet. When you download a file fromk Internet to your
client machine, you are using file transfer protocol(ftp). When you
send mails, SMTP(Simple Mail Transfer Protocol) is used, and
while receiving mails POP(Post office Protocol) is used.
TEKZUNE TECHNOLOGIES 4

Software Development for Internet


1. One cannot use C and C++ to develop Internet based
applications as the object code generated when we compile
the source code in C and C++ is platform dependent i.e. an
object code generated on one platform (operating system
and processor) cannot be run on other platform. Whereas
when we compile a java source code, a byte code is
generated and it is platform independent i.e. byte code
generated on one platform can be executed on any platform.
This byte code is generated with .class extension. If we
develop a software using java, the .class files can be
downloaded from Internet and can be executed on any other
computer system with any problem.
Major security problems for data on Internet along
Solution’s
EavesDropping : This means reading other data illegally on
Internet. For example, opening other emails and reading them
comes into this category. The solution for this problem is :
encryption and decryption.
Converting data into unreadable format is called encryption and
getting back the original data from encrypted format is called
decryption.
While encrypting the data, we use a password called key. Only
the person who knows the key can decrypt it and read it.
Encryption and Decrytpion can be achieved using java
technology.
Tampering: Not only reading others data but also modifying it
is called tampering. Encryption and decryption is the only
solution.

Impersonation: A person disguising himself as another person


on Internet is called Impersonation. Many people hide their
original identity and act as somebody else to make transactions.
The solution for this problem is digital signature. Digital signature
is file that contains personal identification information in an
TEKZUNE TECHNOLOGIES 5

encrypted format. Storing the personal information in digital


signature and sending this information along with the email
assures the receiver of the identity of the sender.

Virus: Virus represents a program hat can causer harm to the


data, software, and hardware of a computer system. Most of the
viruses spread with .exe, .doc, image (.gif, .jpg), audio, and video
files (.mpg, .avi, .mp3). Virus cannot spread with a .txt file
(example, the file in notepad). In java, we create .class files,
which are similar to .txt files and hence there is no chance of virus
affecting these files. Even if somebody intentionally tries to
incorporate the virus code into a .class file, JVM can verify its
presence before running the program and, if found, can abort
the .class file’s extension.
TEKZUNE TECHNOLOGIES 6

HISTORY OF JAVA
In January of 1991, Bill Joy, James Gosling, Chris Wrath, Ed Frank
and Mike Sheridan, Patrick Naughton, and several others met to
discuss about a project. Mike Sheradin was to focus on business
logic. Patrick Naughton was to begin work on graphics system.
James Gosling was to identify the proper programming language.
James Gosling thought of using C and C++, but they proved to be
system dependent and hence could not be used on different
processors, which the electronic devices might use. So he started
developing a new language, which was completely system
independent. This language was initially called Oak. Later
changed it to Java.
Originally it was named as "oak" and later it was renamed as Java
in 1995.
Originally developed to generate a software to embedd in
electronic application.
Versions of JAVA:
JDK - Java Development kit
1995 jdk1.0 ---| JAVA1
1997 jdk1.1 ---|
1999 jdk1.2 ---| JAVA2 or J2SE 2.0
2000 jdk1.3 ---|
2002 jdk1.4 ---|
2004 jdk1.5 ---|
2005 jdk1.6 ---| J2SE6.0 or J2SDK6.0
2011 jdk1.7
2014 jdk1.8

Flavours of JAVA:
Sun Microsystems Inc. has divided Java into 3 parts – Java SE,
Java EE, Java ME
Java SE(Standard): Java Standard Edition that contains basic
core java classes. This edition is used to develop standard applets
and applications.
TEKZUNE TECHNOLOGIES 7

Java EE(Enterprise): Java Enterprise Edition conatins classes


that are beyond JAVA SE. In fact, we need Java SE to use many of
the classes in Java EE. It concentrates mainly on providing
business solutions on a network.
Java ME(Micro): stands for Java Micro Edition. Java ME is for
developers who develop code for portable devices, such as PDA or
a cellular phone. Code on these devices needs to be small in size
and should take less memory.
Features of Java :
Pure Object-oriented programming language: Java does not
support stand alone functions. Everything must be in terms of
objects and classes.
Distributed: Information is distributed on various computers on
a network. Using Java, we can write programs, which capture
information and distribute it to the clients. This is possible
because Java can handle the protocols like TCP/IP and UDP.
Robust: means strong. There are two reasons.
1. Java has got excellent inbuilt exception handling features. An
exception is an error that occurs at run time. If an exception
occurs, the program terminates abruptly giving rise to
problems like loss of data. Overcoming such problems is
called exception handling.
2. It lies in its memory management features. Most of C and
C++ programs crash in middle bcoz of insufficient memory.
Such a problem will not occur in Java bcoz the user need not
to allocate or deallocate the memory and Everything will be
taken care of by JVM only.
Security.
Security problems like eavesdropping, tempering,
impersonation and virus can be eliminated by using Java on
Internet.
System Independent.
Java’s byte code is not machine dependent. It can run on any
machine with any machine, any processor, and any operating
system.
TEKZUNE TECHNOLOGIES 8

Portability.
If a program produces a same result on every machine, than
that program are called portable. This is why Java called
system independence.
Interpreted.
Java programs are compiled to generate the byte code. This byte
code can be downloaded and interpreted by the interpreter in
JVM.
High Performance: The problem with interpreter inside the JVM
is that it is slow. Because of this, Java programs used to run slw.
To overcome this problem, along with interpreter, JavaSoft people
have introduced JIT (Just in Time) compiler, which enhances the
speed of the execution. So now in JVM, both interpreter and JIT
compiler work together to run the program..

Multithreaded: A thread represents an individual process


toexecute a group of statements. JVM uses several threads to
execute different blocks of code. Creating multithreads is called
multithreaded.

Scalability: Java platform can be implemented on a wide range


of computers with varying levels of resources – from embedded
devices to mainframe computers. This is possible because Java is
compact and Platform independent.
The Java Virtual Machine :
Java Virtual Machine (JVM) is the heart of entire Java program
execution process. It is responsible for taking the .class file and
converting each byte code instruction into the machine language
instruction that can be executed by the microprocessor.
TEKZUNE TECHNOLOGIES 9

Architecture of Java Virtual Machine :

class loader
sub system

Method Heap Java pc Native


area Stacks registers method
stacks

Runtime data areas

Interpreter JIT compiler


Native method Native
interface method
libraries

Execution engine

Operating system

JVM(Java Virtual Machine):-- It is the environment where


java programs can be run. It is resoponsible to execute a java
program. It was developed in C language it is platform dependent
it does mean that a separate JVM is required by each platform. It
is a part of JDK(Java Development Kit).
Class Loader Sub System:
It performs the following functions.
1. Loads .class files
2. verifies Byte Code instructions
3. Allocates memory required
TEKZUNE TECHNOLOGIES 10

Memory: The memory of JVM is divided into 5 modules


1. Method Area: It stores Byte Code
2. Heap: Objects are created in Heap
3. Java Stack: Methods called are kept in Java Stack
4. Native Method Stack: Native Method called are kept in Native
method stack.
5. PC Register: Stores the address of code which is being
executed by the processor.
Execution Unit: It is responsible to execute the byte code, it
contains java interpreter (java) and JIT(Just In Time) compiler.
Interpreter executes instructions one after another where as JIT
translates all instructions into machine understandable code at a
time. JIT is faster than interpreter it is used whenever the byte
code is to be executed very fast.
Native Method Interface: It is a program which has native
methods from native method libraries into the memory of JVM.
Native Method Libraries is a set of predefined native methods.
Native Method: It is a function defined in languages other than
Java which can be reused in java with the help of technology i.e
JNI(Java Native Interface).
TEKZUNE TECHNOLOGIES 11

Differences between C++ and Java :


C++ Java
C++ is not a purely Java is purely object-
object-oriented oriented programming
programming language, language, since it is not
since it is possible to possible to write Java
write C++ programs program without using a
without using a class or class or an object.
an object.
Pointers are available in We cannot create and use
C++ pointers in Java.
Allotting memory and Allocation and
deallocating memory is deallocation of memory
the responsibility of the will be taken care of by
programmer. JVM.
C++ has goto statement. Java does not have goto
statement.
Automatic casting is In some cases, implicit
available in C++. casting is available. But it
is advisable that the
programmer should use
casting wherever
required.
Multiple inheritance No multiple Inheritance in
feature is available in C+ JAVA, but there are
+. means to achieve it.
Operator overloading is Operator overloading is
available in C++. not available in C++.
header files No header files.
3 access specifier 4 access specicifer.
Constructors and Only Constructor.
Destructors.
HotJava is an innovative World-Wide Web
browser, and the first major applications written using the Java
environment.
TEKZUNE TECHNOLOGIES 12

HotJava is the first browser to dynamically download and execute


Java code fragments from anywhere on the Internet, and to so so
in a secure manner.
1.1 Beginnings of the Java Language Project
Java is designed to meet the challenges of application
development in the context of heterogeneous, network-wide
distributed environments. Paramount among these challenges is
secure delivery of applications that consume the
minimum of system resources, can run on any hardware and
software platform, and can be extended dynamically.
Java originated as part of a research project to develop advanced
software for a wide variety of networked devices and embedded
systems. The goal was to develop a small, reliable, portable,
distributed, real-time operating environment. When the project
started, C++ was the language of choice. But over time the
difficulties encountered with C++ grew to the point where the
problems could best be addressed by creating an entirely new
language environment. Design and architecture decisions drew
from a variety of languages such as Eiffel, SmallTalk, Objective C,
and Cedar/Mesa. The result is a language environment that has
proven ideal for developing secure, distributed, network-based
end-user applications in environments ranging from networked-
embedded devices to the World-Wide Web and the desktop.
1.2 Design Goals of Java The design requirements of Java are
driven by the nature of the computing
environments in which software must be deployed.
The massive growth of the Internet and the World-Wide Web
leads us to a completely new way of looking at development and
distribution of software.
To live in the world of electronic commerce and distribution, Java
must enable the development of secure, high performance, and
highly robust applications on multiple platforms in heterogeneous,
distributed networks.
13 The Java Language Environment—October 1995
1
Operating on multiple platforms in heterogeneous networks
invalidates the traditional schemes of binary distribution, release,
upgrade, patch, and so on.
TEKZUNE TECHNOLOGIES 13

To survive in this jungle, Java must be architecture neutral,


portable, and dynamically adaptable.
The Java system that emerged to meet these needs is simple, so
it can be easily programmed by most developers; familiar, so that
current developers can easily learn Java; object oriented, to take
advantage of modern software development
methodologies and to fit into distributed client-server
applications; multithreaded, for high performance in applications
that need to perform
multiple concurrent activities, such as multimedia; and
interpreted, for maximum portability and dynamic capabilities.
Together, the above requirements comprise quite a collection of
buzzwords, so let’s examine some of them and their respective
benefits before going on.

Data types in Java


Group Data type Size Range Default
value
Integer byte 1 byte -27 to 27-1 0
short 2 byte -215 to 215-1 0

int 4 byte -231 to 231-1 0

long 8 byte -263 to 263-1 0

Floating float 4 byte 3.4e-038 to 0.0


point 3.4 e+038
-1
double 8 byte -1.7 e-308
to 0.0
1.7e+308-1
Boolean boolean One bit true or false false

Character char 2 byte null


TEKZUNE TECHNOLOGIES 14

Structure of Java Program


-----------------------------------
class FirstJavaProgram
{
public static void main(String args[ ])
{
[Link]("output of the program");
}
}
main:--- It is name of the method, the main() method is where your
program starts running.
void:---- It does not return any value.
static:--- This function can be called with out creating an object.
String :---- It is a predefined class included in [Link] package, it
can be used as a datatype.
args[ ] :---- It is the parameter.
String args[ ] :---- It can store command line arguments.
System :---- It is a predefined class included in [Link] package.
out :---- It is an object of System class, this says print to standard
Steps to Write and Execute a java program:

1. open any editor, for example: Notepad, wordpad, Editplus etc.


2. type the source code in the editor
3. Save it with a .java extension, file name should be same as class
name.
4. goto command prompt, and goto the drive where the java file is
saved.
5. to compile the file type,
javac [Link]
6. To execute the file type,
java FirstJavaProgram

Setting path for java


Go to location where Java has been installed, such as
C:\Program Files\Java\jdk1.7.0\bin
Copy the above path from the address bar and paste it as path by
following procedure
Right click on My Computer->Properties->AdvancedTab->Environment
Variables and Click on New button and set the path as
TEKZUNE TECHNOLOGIES 15

Variable name : path


Variable Value : C:\Program Files\Java\jdk1.7.0\bin;

Ok -> ok -> ok.

SIMPLE PROGRAMS
/*1. Program to display simple message in java*/

class Message
{
public static void main(String args[])
{
[Link]("welcome to java program");
}
}
Ouptput:
E:\>javac [Link]
E:\>java Message
welcome to java program
/*2. Program to perform addition of two numbers */
class Addition
{
public static void main(String args[])
{
int a,b,c;
a=5;
b=7;
c=a+b;
[Link]("Sum of two number is = " + c );
}
}
OUTPUT:
E:\>javac [Link]
E:\>java Adition
Sum of two number is = 12
TEKZUNE TECHNOLOGIES 16

/*3. Program to interchange or swap two numbers */


class S wap
{
public static void main(String args[])
{
int a,b,c;
a=5;
b=7;
[Link]("a="+ a+ "and b=" +b+"before swapping");

c=a;
a=b;
b=c;
[Link]("a="+ a+ "and b=" +b+"after swapping");
}
}
OUTPUT:
E:\>javac [Link]
E:\ >java Swap
a=5and b=7before swapping
a=7and b=5after swapping
/*4. Program to calculate customer bill */
class Customer
{
public static void main(String args[])
{
int cno,quantity,price,bill;
String name,item;

cno=777;
name="SYED HAMED";
item="MOBILE";
quantity=5;
price=2500;

bill=quantity*price;
[Link]("Customer Details are:");
TEKZUNE TECHNOLOGIES 17

[Link]("CUSTOMER NO:" + cno);


[Link]("CUSTOMER NAME:" + name);
[Link]("ITEM NAME:" + item);
[Link]("QUANTITY:" + quantity);
[Link]("PRICE:" + price);
[Link]("CUSTOMER BILL=" + bill);
}
}
OUTPUT:
E:\ >javac Customer. java
E:\ >java customer
Customer Details are:
CUSTOMER NO:777
CUSTOMER NAME: SYED HAMED
ITEM NAME: MOBILE
QUANTITY: 5
PRICE: 2500
CUSTOMER BILL=12500
TEKZUNE TECHNOLOGIES 18

CONTROL STATEMENTS
Statements in Java generally contain expressions and end with a
semi-colon. The two commonly used statements in any
programming language are as follows:

1) Sequential Statements: These are the statements which are


executed one by one.
2) Control Statements: These are the statements that are
executed randomly and repeatedly:
Control Statements :
Java supports control statement to change the flow of execution
from one statement to other statement based on some condition.
There are different control structures.
If statement
While loop
Do while
For loop
Switch statement
If : It is used to check a condition and if true will execute the
statement or statements.

Its syntax can be defined as


eg:
if(condition ){
statement 1;
statement 2;
}
It can be followed by an else statement which will be executed in
case when the if condition doesnot satisfy.
if(condition ){
// code comes here
}
else {
statement1;
statement2; }
TEKZUNE TECHNOLOGIES 19

/*5. Program to find greatest of two numbers */


public class SimpleIf
{
public static void main(String ar[])
{
[Link]("Program to find greatest of two numbers ");
int i=0,j=2;
if(i<j)
{
[Link]("I is less than J");
}
else
[Link]("J is less than I");
}
}
OUTPUT:
E:\ >javac [Link]
E:\ >java SimpleIf
Program to find greatest of two numbers
I is less than J
while loop:It is a loop that will be exeuted till the condition
specified in the while is satisfies.
If the condition satisfies then the code will be executed or else not
executed
Syntax for while loop is as follows:
while(conditon){
//code here
}
/*6 Program to print numbers from 1 to 10 */
public class WhileLoop
{
public static void main(String args[])
{
int x=1;
while(x<=10) {
[Link]("The value of x is=" +x);
TEKZUNE TECHNOLOGIES 20

x++;
}
}
}
OUTPUT:
E:\ >javac [Link]
E:\ >java WhileLoop
The value of x is=1
The value of x is=2
The value of x is=3
The value of x is=4
The value of x is=5
The value of x is=6
The value of x is=7
The value of x is=8
The value of x is=9
The value of x is=10

Do-while :-
Here atleast once the code will be executed [Link] the
code is first written and then at the end of block the conditon is
written (condition checking).
Syntax for do while
while(conditon){
//code here
}
do-while
do{
//code here
}while(condition)
/* 7. P rogram to print infinity number */
public class Do_While
{
public static void main(String args[]) {
int x=1;
do{
[Link]("The value of x is=" +x);
TEKZUNE TECHNOLOGIES 21

x++;
//if(x>10) break;
} while(x>=0);
}
}
OUTPUT:
E:\>javac Do_While.java
E:\ >java Do_While
The value of x is=1
The value of x is=2
The value of x is=3
The value of x is=4
The value of x is=5
The value of x is=6
The value of x is=7
The value of x is=8
The value of x is=9
The value of x is=10
The value of x is=11
The value of x is=12
Note to break the series press CTRL+C from keyboard
/* 8. Program for Command Line Arguments */
class CommandLineArg
{
public static void main(String args[])
{
int n=[Link];
[Link]("no. of args are" + n);
for(int i=0;i<n;i++)
{
[Link]("args["+i+"]=" +args[i]);
}
}
}

OUTPUT:
E:\>javac [Link]
E:\>java CommandLineArg 11 22 33 44 55
TEKZUNE TECHNOLOGIES 22

no. of args are5


args[0]=11
args[1]=22
args[2]=33
args[3]=44
args[4]=55
ForStatement:The for loop is also same as do-while or while
loop, but it is ore compact syntactically.
The for loop executes a group of statements as long a a condition
is true.
for( Initialization ; Expression ;Increment/Decrement )
{
Statement | Block of Statements
}
1) In the first part of for loop we initialize the value of the variable
like i=1;
2) In the second part of the for loop we checking the condition.
As long as the condition is true the program will execute.
like x<=10;
3) In the third part of the for loop we increment or decrement
the value of variable.
like i++/i--
/*9 Program to print numbers from 1 to 10 */
public class SimpleFor
{
public static void main(String args[])
{
int x=10;
for(int i=1;i<=x;i++)
{
[Link]("The value of x is="+i);
}
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 23

E:\>javac [Link]
E:\>java SimpleFor
The value of x is=1
The value of x is=2
The value of x is=3
The value of x is=4
The value of x is=5
The value of x is=6
The value of x is=7
The value of x is=8
The value of x is=9
The value of x is=10
/*10. Program to print numbers Ascending and Descending
Order */
class Demo
{
public static void main(String args[])
{
int i;
int n;
n=[Link](args[0]);
for(i=1;i<=n;i++)
{
[Link]("Ascending Order = " + i);
}
[Link]();

for(i=n;i>0;i--)
{
[Link]("Descending Order = " + i);
}
}
}
OTUPUT:
E:\>javac [Link]
E:\>java Demo 10
Ascending Order = 1
TEKZUNE TECHNOLOGIES 24

Ascending Order = 2
Ascending Order = 3
Ascending Order = 4
Ascending Order = 5
Ascending Order = 6
Ascending Order = 7
Ascending Order = 8
Ascending Order = 9
Ascending Order = 10
Descending Order = 10
Descending Order = 9
Descending Order = 8
Descending Order = 7
Descending Order = 6
Descending Order = 5
Descending Order = 4
Descending Order = 3
Descending Order = 2
Descending Order = 1
/*11. Program to perform reverse of a given number using
command line argument*/
class Reverse
{
public static void main(String args[])
{
int n,i,rem=0,sum=0;
n=[Link](args[0]);
do
{
rem=n%10;
sum=sum*10+rem;
n=n/10;
}
while(n>0);
[Link]("Reverse of a given number is = "+sum);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 25

E:\>javac [Link]
E:\>java Reverse 123
Reverse of a given number is = 321

/*12. Program to perform Sum of given number digits


command line argument*/
class SumDigits
{
public static void main(String args[])
{
int rem, sum=0;
int n=[Link](args[0]);
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
[Link]("Sum of digit is"+sum);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java SumDigits 456


Sum of digit is15
For-each loop:
This loop is specifically designed to handle the elements of a
collection. Collection represents a group of elements. For
example, we can take an array as a collection.
/*13. Example program using ‘For-Each’ loop */
class ForEach
{
public static void main(String args[])
{
int x[]={10,20,30,40,50};
TEKZUNE TECHNOLOGIES 26

for(int i:x)
{
[Link]("The value of i = " + i);
}
}
}

OUTPUT:
E:\>javac ForEach
E:\>java ForEach
The value of i = 10
The value of i = 20
The value of i = 30
The value of i = 40
The value of i = 50

/* 14. Program to find the season of a year */


import [Link].*;
public class Season {
public static void main(String args[]) throws IOException {
int n=[Link](args[0]);

if(n==12||n==1||n==2)
[Link]("This is Winter season");
else if(n==3||n==4||n==5)
[Link]("This is Summer season");
else if(n==6||n==7||n==8)
[Link]("This is Rainy season");
else if(n==9||n==10||n==11)
[Link]("This is Spring season");
else
[Link]("This is not a valid month");
}
}
TEKZUNE TECHNOLOGIES 27

OUTPUT:
E:\>javac [Link]

E:\>java Season 3
This is Summer season

continue : It ends only the current iteration. Program goes to


the end
of the loop body.
It ends the current iteration so that the rest of the statement in
the loop body is not executed.
OR
'continue' is used inside a loop to repeat the next iteration of the
loop. When 'continue' is executed, subsequent statements in the
loop are not executed and control of execution goes back to the
next repetition of the loop.

/* 15. Example program on ‘Continue’ statement */


class TestContinue
{
public static void main(String args[])
{
int sum=0,number=0;

while(number<5)
{
number++;
if(number == 2 || number == 3) continue;
sum=sum+number;
}
[Link]("The sum is = " + sum);
}
}
/*
In the above program, number variable values all added to the
sum
from 0 to 5 except 2 and 3 only not added to the sum.
*/
TEKZUNE TECHNOLOGIES 28

OUTPUT:
E:\>javac [Link]

E:\>java TestContinue
The sum is = 10
TEKZUNE TECHNOLOGIES 29

INPUT AND OUTPUT


A stream represents flow of data from one place to
another place. A stream can carry data from keyboard to
memory or from memory to printer or from memory to file.
Basically, there are two types of streams: input and
output streams.

Input streams are those streams which receive or read


data coming from some other place.

Output streams are those streams which send or write


data to some other place.

All streams are represented by classes in [Link]


( input and output) package. This package contains a lot
of classes, all of which can be classified into two basic
categories: input streams and output streams.

[Link]: This represents InputStream object, which by


default represents standard input device, i.e. keyboard.

[Link]: This represents PrintStream object, which by


default represents standard output device, i.e. monitor.

[Link]: This also represents PrintStream object,


which by default represnts standard output device, i.e.
monitor.

Difference between [Link] and [Link]:

They both represent the monitor by default and hence can


be used to send data or results to the monitor. But
[Link] is used to display messages and results
whereas [Link] is used to display error messages.

Accepting Input from the Keyboard:


TEKZUNE TECHNOLOGIES 30

Connect the keyboard to an input stream object. Here we


can use InputStreamReader that can read data fron
keyboard.

InputStreamReader obj = new


InputStremReader([Link]);

Connect InputStremReader to BufferedReader, which is


another input type of stream. We are using it as it got
methods to read data properly, coming from the stream.
BufferedReader br = new Bufferedreader(obj);

Together we can write as


BufferedReader br = new BufferedReader(new
InputStremReader([Link]));

Accepting a single character from the keyboard:

char ch = [Link]();
but it returns ASCII number.

char ch = (char)[Link]();

Accepting a String from keyboard:


String name = [Link]();

Accepting an integer value from the keyboard:


String str = [Link]();
int n = [Link](str);
or
int n= [Link]([Link]());

Accepting a float value from keyboard:


float f = [Link]([Link]);

Accepting a double value from keyboard:


double d = [Link]([Link]);
TEKZUNE TECHNOLOGIES 31

Accepting a byte value from keyboard:


byte d = [Link]([Link]);

Accepting a short value from keyboard:


Short s = [Link]([Link]);

Accepting a long value from keyboard:


long d = [Link]([Link]);

Accepting a boolean value from keyboard:


boolean d = [Link]([Link]);

ACCEPTING INPUT FROM THE KEYBOARD:

Input represents data given to a program and output represents


data displayed as a result of a program.

A stream is required to accept from the keyboard. A stream


represents flow of data from one place to another place.
A stream can carry data from keyboard to memory or from
memory to printer or from memory to file.

There are two types of streams


1) Input Stream: These are the streams which receive or read
data from keyboard .
Keyboard is represented by [Link], here (System) is a class
and (in) is an object ot it.

2) Output Stream: These are the streams which send or write


data to some other place.
Monitor is represented by PrintStream class. But we can't use
directly the object of PrintStream, so we create object of 'System'
class as '[Link]'.

/*16. Example program on Employee Details*/

import [Link].*;
TEKZUNE TECHNOLOGIES 32

import [Link].*;

public class Employee


{
public static void main(String args[]) throws IOException
{
//create BufferedReader object to //accept data
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Accept Employee details


[Link]("Enter id: ");
int id=[Link]([Link]());

[Link]("Enter gender (M/F):");


String gender=([Link]());

[Link]("Enter name:");
String name=[Link]();

//display the employee details


[Link]("ID=" +id);
[Link]("Gender=" +gender);
[Link]("Name=" + name);
}
}
OUTPUT:

E:\INPUT_OUTPUT>javac [Link]

E:\INPUT_OUTPUT>java Employee
Enter id: 77
Enter gender (M/F):Male
Enter name:Junaid

ID=77
Gender=Male
Name=Junaid
TEKZUNE TECHNOLOGIES 33

/*16. Example program on Arithmetic Details*/

import [Link].*;
import [Link].*;

public class Arithmetic {


public static void main(String args[]) throws IOException
{

//Accept data from keyboard


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//take input into str from keyboard


[Link]("Enter three numbers seperated by comma:");
String str=[Link]();

//Split the string at comma


StringTokenizer st=new StringTokenizer(str,",");

//Take the two tokens into s1,s2


String s1=[Link]();
String s2=[Link]();
String s3=[Link]();

//trim the spaces in s1, s2


s1=[Link]();
s2=[Link]();
s3=[Link]();

//convert s1 and s2 into double type and store in n1, n2


double n1=[Link](s1);
double n2=[Link](s2);
int n3=[Link](s3);

//perform arithmetic operations


[Link]("Result of Addition:" + (n1+n2+n3));
TEKZUNE TECHNOLOGIES 34

[Link]("Result of Subtraction:" + (n1-n2-n3));


[Link]("Result of Multiplication:" + (n1*n2*n3));
[Link]("Result of Division:" + ((n1/n2)/n3));

}
}
/*

OUTPUT:
E:\>javac [Link]

E:\ >java Arithmetic


Enter two numbers:20.5,5

Result of Addition:25.5
Result of Subtraction:15.5
Result of Multiplication:102.5
Result of Division:4.1

/*17. Example program on Different Data Types*/

import [Link].*;
import [Link].*;

public class DiffTypes


{
public static void main(String args[]) throws IOException
{

//To accept data from keyboard


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Ask for input seperated by commas


[Link]("Enter name, age, salary:");

//accept input into a string


String str=[Link]();
TEKZUNE TECHNOLOGIES 35

//use StringTokenizer to split input at commas


StringTokenizer st=new StringTokenizer(str," " );

//Taking 3 tokens as strings


//First token represents name, second represents age and third
represents salary
String s1=[Link]();
String s2=[Link]();
String s3=[Link]();

//trim any spaces before and after the tokens


s1=[Link]();
s2=[Link]();
s3=[Link]();

//Convert s1 into string, s2 into int and s3 into a float


String name=s1;
int age=[Link](s2);
float salary=[Link](s3);

//display the entered data


[Link]("Name=" + name);
[Link]("Age=" + age);
[Link]("Salary="+ salary);
}
}

OUTPUT:
E:\ >javac [Link]

E:\>java DiffTypes
Enter name, age, salary:
JUNAID 22 5000

Name=JUNAID
Age=22
Salary=5000.0
TEKZUNE TECHNOLOGIES 36

/*18. Program to find whether the entered year is


LeapYear or not. */

import [Link].*;
public class LeapYear {
public static void main(String args[]) throws IOException
{
//Accept year
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter year:");
int year=[Link]([Link]());

//If the year is century and divisible by 400


if(year%100==0&&year%400==0)
[Link]("Entered year is leap year");
//If it is not century year and divisible by 4
else if(year%100!=0&&year%4==0)
[Link]("Entered year is leap year");
//otherwise it is not a leap year
else
[Link]("The year is not a leap year");
}
}

OUTPUT:
E:\>javac [Link]

E:\>java LeapYear
Enter year:1999
The year is not a leap year

E:\>java LeapYear
Enter year:2002
The year is not a leap year

E:\>java LeapYear
Enter year:2004
Entered year is leap year
TEKZUNE TECHNOLOGIES 37

/*18. Program to print ‘Fibbonacci’ series of a given no. */

import [Link].*;
public class Fibbo {
public static void main(String args[]) throws IOException {
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("How many Fibonacci?");


int n=[Link]([Link]());

//Take first two fibonacci as 0 and 1


long f1=0,f2=1;

[Link](f1);
[Link](f2);

//Find next fibonacci no.


long f=f1+f2;
[Link](f);

//Already 3 fibonacci are displayed. So count will first start at 3


int count=3;
while(count<n)
{
f1=f2;
f2=f;
f=f1+f2;
[Link](f);
count++;
}
}
}

E:\>javac [Link]

E:\>java Fibbo
How many Fibonacci?
TEKZUNE TECHNOLOGIES 38

7
0
1
1
2
3
5
8

import [Link].*;

class Student
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter following student details ");


[Link]();
[Link]("Enter Student Id and Name :");
int rno=[Link]([Link]());
String name=[Link]();

[Link]("Enter any 3 subject marks");


int s1=[Link]([Link]());
int s2=[Link]([Link]());
int s3=[Link]([Link]());

int total=s1+s2+s3;

float avg=total/3;

[Link]("Student details are");


[Link]();
[Link]("Roll No : " + rno);
[Link]("Name : " + name);
[Link]("Total marks : " + total);
[Link]("Average : " + avg);
TEKZUNE TECHNOLOGIES 39

}
}
TEKZUNE TECHNOLOGIES 40

ARRAYS
ARRAYS: An array represents a group of ements of same data
type. It can store a group of elements. So we can store a group of
int values or group of float values or groupt of strings in an array.
But we cannot store come int values and some float values in the
array.
The advantage of using arrays is that the simplify programming
by replacing a lot of statements by just one or two staatements.

The arrays can be categories into two parts as :

1) Single Dimensional Array (or 1D arrays)


2) Multi Dimensional Array ( or 2D, 3D, ... arrays)

1 Dimensional Array:
-------------------------------
syntax:

datatype arrayname[ ] = new datatype[ size ];

eg:
int x[ ] = new int[5];
(or)
int[ ] x=new int[5];

it creates an array of integer type with 5 as it's size.


it stores data of the datatype declared.
it can be retrieved by using the index value.
the first element is refered with 0 index

x[0] ---> first element


x[1] ---> second element

Array Initialization:

int x[ ] = {10,20,30,40,50};

x[0]=10;
x[1]=20;
TEKZUNE TECHNOLOGIES 41

2) Multi Dimensional Array:


-------------------------------
syntax:

datatype arrayname[ ][ ] = new datatype[ row size ]


[column size];

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

/*19. Program to print array elements */]

class Arr {
public static void main(String args[])
{
int marks[]=new int[5];

marks[0]=65;
marks[1]=64;
marks[2]=78;
marks[3]=69;
marks[4]=88;
for(int i=0;i<5;i++)
{
[Link]("The elements are:" + marks[i]);
}

}
}
OUTPUT

E:\>javac [Link]

E:\>java Arr
The elements are:65
The elements are:64
The elements are:78
The elements are:69
The elements are:88
TEKZUNE TECHNOLOGIES 42

/*20. Program to print array elements */

class Arr1 {
public static void main(String args[])
{
int marks[]={50,56,67,78,77};
for(int i=0;i<5;i++)
{
[Link]("The elements are:" + marks[i]);
}

}
}
OUTPUT

E:\>javac [Link]

E:\>java Arr1
The elements are:50
The elements are:56
The elements are:67
The elements are:78
The elements are:77

/*21. Program to display the result of a student */


import [Link].*;

public class Array1


{
public static void main(String args[]) throws IOException
{

//Accept data from keyboard


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Ask how many subjects from the keyboard


TEKZUNE TECHNOLOGIES 43

[Link]("Enter how many subjects?");


int n=[Link]([Link]());

//Creating 1D array with size n


int[] marks=new int[n];

//store elements into the array


for(int i=0;i<n;i++)
{

[Link]("Enter marks:");
marks[i]=[Link]([Link]());
}

//find total marks


int tot=0;
for(int i=0;i<n;i++)
tot=tot+marks[i];

//display total marks


[Link]("The total marks are:" + tot);

//Find percentage
float percentage=(float)tot/n;
[Link]("Percentage=" +percentage);
}
}

OUTPUT

E:\>javac [Link]

E:\>java Array1
Enter how many subjects?
5
Enter marks:50
Enter marks:60
Enter marks:70
Enter marks:80
TEKZUNE TECHNOLOGIES 44

Enter marks:90
The total marks are:350
Percentage=70.0

/* 22. Program to Sort the given series using Bubble sort


technique */

import [Link].*;

public class Array1Sort {


public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//create an int array


[Link]("How many elements?");
int n=[Link]([Link]());
int arr[]=new int[n];

//Accept integer elements into an array


for(int i=0;i<n;i++)
{
[Link]("Enter int:");
arr[i]=[Link]([Link]());
}

//Using bubble sort technique

int temp; // temporary variable

for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
//If first element is bigger than second than swap
if(arr[i]>arr[j])
{
temp=arr[i];
TEKZUNE TECHNOLOGIES 45

arr[i]=arr[j];
arr[j]=temp;
}
}

}
//displayed the stored array
[Link]("The stored array is :");
for(int i=0;i<n;i++)
[Link](arr[i]);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Array1Sort
How many elements?
5
Enter int: 7
Enter int: 19
Enter int: 23
Enter int:2
Enter int: 14
The stored array is :
2
7
14
19
23

/* 23. Program to perform Transpose of a matrix */

import [Link].*;
import [Link];

class Transpose {
public static void main(String args[]) throws IOException
{
TEKZUNE TECHNOLOGIES 46

//Use scanner to accept data from keyboard


Scanner sc=new Scanner([Link]);

//Accept rows columns of a matrix


[Link]("Enter how many rows and columns?");
int r=[Link]();
int c=[Link]();

//create an array with size[r][c]


int arr[ ][ ]=new int[r][c];

//Accept matrix from keyboard


[Link]("Enter elements of matrix:");

for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
[Link]("Enter arr["+i+"]["+j+"]");
arr[i][j]=[Link]();
}
}
[Link]("Before the transpose of a Matrix:");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
[Link](arr[i][j] + " ");
}
[Link]("\n");
}
[Link]("After the transpose of a matrix:");
//Take columns as rows and vice versa and display
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
{
[Link](arr[j][i]+ " ");
}
TEKZUNE TECHNOLOGIES 47

[Link]("\n");
}
}
}

OUTPUT
E:\>javac [Link]

E:\>java Tranpose
Enter how many rows and columns?3
3
Enter elements of matrix:
1
2
3
4
5
6
7
8
9
Before the transpose of a Matrix:
123
456
789
After the transpose of a matrix:
147
258
369
TEKZUNE TECHNOLOGIES 48

Extra Programs in Arrays


//23.1. Program for Merging of array values into third array
class ArrMerge
{
public static void main(String args[])
{
int i,j,arr1[]={10,20,30},arr2[]={40,50,60};
int arr3[]=new int[6];
for(i=0;i<3;i++)
{
arr3[i]=arr1[i];
}
for(j=0;j<3;i++,j++)
{
arr3[i]=arr2[j];
}
[Link]("Array elements after merging");
for(i=0;i<6;i++)
{
[Link](arr3[i]);
}
}
}

//23.2 Program to merge two arrays (one value from first


array then next value from another array)
//[Link]
import [Link].*;

class Example
{
int arr1[]={1,3,5,7};
int arr2[]={2,4,6,8};
int arr3[]=new int[10];
int i,j,k,l,b,c,x=0;
static int a;

void merge()
{
TEKZUNE TECHNOLOGIES 49

for(i=a;i<=8;i++)
{
for(j=a;(j<[Link])&&(j<=a);j++)
{
arr3[x]=arr1[j];
}
x++;
for(k=a;(k<[Link])&&(k<=a);k++)
{
arr3[x]=arr2[k];

a++;
x++;
}

[Link]("Array elements are");


for(l=0;l<a-1;l++)
{
[Link]("Result is = " + arr3[l]);
}

} //merge
} //class

//Save file with this name


//[Link]
class ArrayMerge
{
public static void main(String args[])
{
Example e=new Example();
[Link]();

}
}

//23.3. Removing duplicate elements from array


TEKZUNE TECHNOLOGIES 50

class RemoveDuplicate
{
public static void main(String args[])
{
int i,j,k,n=8;
int arr[]={10,20,50,10,30,20,10,40};

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
arr[j]=0;
n=n-1;
for(k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
j=j-1;
}
}
}
[Link]("Elements after deleting duplicates are:\n\n");

for(i=0;i<n;i++)
{
[Link](arr[i]);
}

}
}

STRINGS
Strings: A group of characters is nothing but strings.
For example, a person enters his/her details like name,age
credit card number, address etc. which are nothing but in the
TEKZUNE TECHNOLOGIES 51

form of strings only.

String is a class in [Link] package. But in java, all classes are


also considered as data types. So we can take String as a data
type.

There are three ways to create String in Java:

1) We can create a string just by assigning a group of characters


to a string type variable:

String s;
s="Hello";

we can combine the above two statement into one as:


String s=("Hello");

2) String s=new String("Hello");


Here we are doing two things. First, we are creating object using
new operator. Then we are storing the string : "Hello" in that
object.

3) The third type is, here first we have to create char array and
then convert char array into string.

char arr[]={'c'.'h','a','i','r'.'s'};
String s=new String(arr);

Among the three types mention above, the first is better.

Some of the methods in the String class are:

1) String concat(String s): This method concatnates or joins two


strings (s1 and s2) and returns a third string s3 as a result.
for example,
String s3=[Link](s2);

2) int length(): This method returns the length or number of


characters of a string.
TEKZUNE TECHNOLOGIES 52

For example, [Link]() gives the number of characters in the


string s1.

3) char charAt(int i): This method returns the character at the


specified location i.
Suppose we call this method as:
[Link](5), then it gives the 5th character in the string s1.

4) int compareTo(int i): This method is useful to compare two


strings and to know which string is bigger or smaller.

5) String substring(int i): This method is useful to extract sub


string from main string.

/*24. Performing simple operations using ‘String’. */


import [Link];
//Demo of string class methods

class StrDemo
{
public static void main(String args[])
{
//Create strings in 3 ways
String s1="A book on Java";
String s2=new String("I like it");
char arr[]={'D','r','e','a','m','t','e','c','h',',','P','r','e','s','s'};
String s3=new String(arr);

//Display all the 3 strings


[Link]("s1 = " + s1);
[Link]("s2 = " +s2);
[Link]("s3 = " +s3);

//Find length fo first string


[Link]("Length of s1=" + [Link]());

//Concatenate two strings


[Link]("s1 and s2 joined=" + [Link](s2));
TEKZUNE TECHNOLOGIES 53

//Concatenate three strings with +


[Link](s1 +" from" + s3);

//Test if string s1 start with A


boolean x=[Link]("A");
if(x)
[Link]("s1 starts with \'A\'");
else
[Link]("s1 does not start with \'A\' ");

//Extract substring from s2, starting from 0th char to 6th char
String p=[Link](2,7);
[Link]("p = " + p);

//Extract substring from s3, starting from 0th char to 8th char
String q=[Link](5,9);
[Link]("q = " + q);

//Concatenate the strings p and q


[Link](p+q);

//convert s1 into upper and lowercase


[Link]("Upper s1=" +[Link]());
[Link]("Lower s1=" +[Link]());

}
}
OUTPUT:
E:\>javac [Link]

E:\>java StrDemo
s1 = A book on Java
s2 = I like it
s3 = Dreamtech,Press
Length of s1=14
s1 and s2 joined=A book on JavaI like it
A book on Java fromDreamtech,Press
s1 starts with 'A'
p = like
TEKZUNE TECHNOLOGIES 54

q = tech
like tech
Upper s1=A BOOK ON JAVA
Lower s1=a book on java

/*25. Performing simple operations using ‘String’. */

import [Link];

class StrDemo1
{
public static void main(String args[])
{
//Create strings in 3 ways
String s1="Hyderabad is a city of India";
[Link]("S1 = " + s1);

String s2=[Link]("Hyderabad","Bangalore");
[Link]("S2 = " + s2);

String s3="Coupon";
[Link]("S3 = " + s3);
String s4=[Link]("on","le");
[Link]("S4 = " + s4);

String s5="a+b#c";
[Link]("S5 = " + s5);
String s6=[Link]("[+]","A");
[Link]("S6 = " + s6);

String s7=[Link]("[#]","B");
[Link]("S7 = " + s7);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java StrDemo1
S1 = Hyderabad is a city of India
TEKZUNE TECHNOLOGIES 55

S2 = Bangalore is a city of India


S3 = Coupon
S4 = Couple
S5 = a+b#c
S6 = aAb#c
S7 = aAbBc

/* 26. Program performing Splitting a string */

class Strsplit
{
public static void main(String args[])
{
//Take a string str which is to be broken
String str="Hello, this is a book on Java";
String s[];

//Split the string where a space is found in str


s=[Link](" ");

//Display the pieces from s


for(int i=0;i<[Link];i++)
[Link](s[i]);
}
}
OUTPUT
D:\>javac [Link]

D:\>java Strsplit
Hello,
this
is
a
book
on
Java

/*27. Program to perform Copying a string into an array */


TEKZUNE TECHNOLOGIES 56

class Strcpy
{
public static void main(String args[])
{
String str="Hello, this is a book on Java";
char arr[]=new char[20];

//copy from str into arr starting from 7th character to 20th
character
[Link](7,21,arr,0);

[Link](arr);
}
}
OUTPUT
E:\>javac [Link]

E:\>java Strcpy
this is a book

/*28. Program to compare two strings */

class Strcompare
{
public static void main(String args[])
{
String s1="Hello";
String s2=new String("Hello");

if(s1==s2) //if([Link](s2))
[Link]("Both are same");
else
[Link]("Both are not equal");

}
}
OUTPUT:

E:\>javac [Link]
TEKZUNE TECHNOLOGIES 57

E:\>java Strcompare
Both are not equal

/*29. Search for a String - Linear Search */

import [Link].*;
class Search
{
public static void main(String args[]) throws IOException
{
//To accept data from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Ask how many strings


[Link]("How many strings?");
int n=[Link]([Link]());

//Create a string type array with size n


String str[]=new String[n];

//Store strings into str[]


for(int i=0;i<n;i++)
{
[Link]("Enter a string:");
str[i]=[Link]();
}
//Accept the string to search
[Link]("Enter the string to search:");
String search=[Link]();

//Take boolean var.


boolean found=false;

//Search for the string in str[]


for(int i=0;i<n;i++)
{
if([Link](str[i]))
TEKZUNE TECHNOLOGIES 58

{
[Link]("Found at position:" + (i+1));
found=true;
}
}
//If not found, display message
if(!found)
[Link]("Not found in the group");
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Search
How many strings?5
Enter a string:Hyderabad
Enter a string:DELHI
Enter a string:BOMBAY
Enter a string:MADRAS
Enter a string:indore
Enter the string to search:
bombay
Found at position:3
TEKZUNE TECHNOLOGIES 59

String: String class objects are immutable and hence their


contents cannot be modified.

StringBuffer Class: StringBuffer class objects are mutable,


so they can be modified. Moreover the methods that manipulate
data of the object are not available in String class. Such methods
are available in StringBuffer class.

StringBuilder class: It is very similar to StringBuffer class, but


main difference between the two is that the StringBuffer class is
synchronized by default and StringBuilder class is not
synchronized. This means, when several threads process or act on
a StringBuffer class oject, they are executed one by one on the
object, thus ensuring reliable results. But in case of StringBuilder
object, since it is not synchronized, it allows several threads to act
on it simultanesously. Thismay lead to inaccurate results in some
cases.

Synchronizing the object islike locking the object. This means,


when a thread acts on the object, it is locked and any other
thread should wait till the current thread completes and unlocks
the object. Thus, synchronizationdoes not allow more than 1
hread to act simultanesuly on the object. Implementing the
synchrinization mechanism will take some time ofr the JVM. Hence
StringBuffer class will take more execution time thatn the
StringBuilder, which does not implement this mechanism.

/*30. Program to find reverse of a given string */

import [Link].*;
class Reverse
{
public static void main(String[] args) throws IOException
{
//Create empty string buffer object
StringBuffer sb=new StringBuffer();

//To accept data from keyboard


BufferedReader br=new BufferedReader(new
TEKZUNE TECHNOLOGIES 60

InputStreamReader([Link]));

//accept surname
[Link]("Enter surname: ");
String sur=[Link]();

//Accept middle name


[Link]("Enter middle name: ");
String mid=[Link]();

//Accept last name


[Link]("Enter last name: ");
String last=[Link]();

//append sur to sb
[Link](sur);

//append last to sb
[Link](last);

//Display the name till now


[Link]("Name= " + sb);

//Insert mid after sur name in sb


int n=[Link](); //n represents [Link] characters in sur name
[Link](n,mid);

//Display full name


[Link]("Full Name= " + sb);

//Display the name in reverse order


[Link]("In reverse = " + [Link]());
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Reverse
Enter surname:
TEKZUNE TECHNOLOGIES 61

SACHIN
Enter middle name:
RAMESH
Enter last name:
TENULKAR
Name= SACHINTENULKAR
Full Name= SACHINRAMESHTENULKAR
In reverse = RAKLUNETHSEMARNIHCAS

/*31. Program to find whether entered string is


'PALINDROME' or not*/

import [Link].*;
class Palindrome
{
public static void main(String args[]) throws IOException
{
//To accept data from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter a string: ");


String str=[Link]();

//Store a copy of original string in temp


String temp=str;

//Convert the string into StringBuffer


StringBuffer sb=new StringBuffer(str);

//Now reverse the string in StringBuffer


[Link]();

//Convert the StringBuffer into a string


str=[Link]();

//Compare the original string available in temp with


//this reversed string
if([Link](str))
TEKZUNE TECHNOLOGIES 62

[Link](temp + " is Palindrome ");


else
[Link](temp + " is not a Palindrome ");
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Palindrome
Enter a string:
Hyderabad
Hyderabad is not a Palindrome

E:\>java Palindrome
Enter a string:
MALAYALAM
MALAYALAM is Palindrome

/*32. Example program for StringBuilder class */


class StrBuilder
{
public static void main(String args[])
{
String s="Welcome to Java Programming";

StringBuilder sb=new StringBuilder(s);

[Link]("Before Deleting = " + sb);

[Link]("After Deleting = " + [Link](11,15));


}
}

OUTPUT:
E:\>javac [Link]

E:\>java StrBuilder
TEKZUNE TECHNOLOGIES 63

Before Deleting = Welcome to Java Programming


After Deleting = Welcome to Programming
TEKZUNE TECHNOLOGIES 64

Introduction to OOPS

PROCEDURE ORIENTED PROGRAMMING(POP) :The language


whrere the programmer uses
functions or procedure to perform a particular task is known as
Procedure Oriented language.

Problems with Procedure Oriented Approach:


1) Here the main focus is on making functions for performing task
which means whenever he wants to
perform a new task, he would be writing a set of functions.

2) There will be no reuseability of previous functions in other


programs.

3) If the code of the software exceeds 10,000 lines of code and


before reaching 1,00,000, suddenly there
may be a chance that programmer could lost control over the
program.

4) The other problem with (Procedure Oriented Approach) is that,


programming is done in one place and
its use is in another place like in "SPACE" which is considered to
be unnatural for human beings.

NEED TO DEVELOP A NEW LANGUAGE:

Due to the above problems with POP, there is a need to


replace this language and this new language is nothing but your
object oriented programming system.

OBJECT ORIENTED PROGRAMMING SYSTEM(OOPS):


OOPS: Object oriented programming approach is a programming
methodology to design computer
programs using classes and objects.

Features of OOPS are:


TEKZUNE TECHNOLOGIES 65

1) Class/Object: A group of objects exhibiting same behavior like


variables and methods come under
the same group called a class.
A class represents a group name given to several objects.
For example, take the person class where Ahmed,Ali,Sami are the
objects. So person is the class name
with four objects.

Example for creating an object:

Box mybox=new Box();

The above mybox is an object of type Box class.


The NEW operator dynamically allocates memory for an object
and returns a reference to it.
This reference is the address in memory of the object allocated by
new.

Suppose, if we write

1) Box mybox; //declare reference to object


2) Box mybox=new Box(); //allocate a Box object

The first line declares mybox as a reference to an object of type


Box.
After this line executes,mybox contains the value null,which
indicates
that it does not yet point to an actual object. Any attempt to use
mybox at this point will result in a compile-time error.

The next line allocates an actual object and assigns a reference to


it
to mybox.

2) Encapsulation: It is a mechanism where the data (variables)


and code (methods) that act on the data
will bind together.
TEKZUNE TECHNOLOGIES 66

For example, take a class example, here we write variables and


methods inside the [Link], class is
binding them together. So class is an example of encapsulation.

3) Abstraction: There may be a lot of data, a class contains and


the user does not need the entire data.
The user requires only some part of the some part of the available
data. In this case, we can hide the
unnecessary data from the user and expose only that data that is
of interest to the user. This is called
Abstraction.

4) Inheritance: The process of creating the new class from the


existing class, the new class will acquire
all the features of the existing class, this is called 'Inheritance'.
Example: parents where children acquire all the features and add
their own features.

5) Polymorphism: The 'polymorphism' word came from the


Greek word 'Poly' means many and
'morphos' means forms. Thus, polymorphism represents the
ability to assume several different forms.

Garbage Collection:
Since objects are dynamically allocated by using the 'new'
operator, then how an object are destroyed and their memory
released for later reallocation.

Java takes adifferent approach, it handles deallocation for you


automatically. The technique that accomplishes this is called
'garbage collection'. It works like this, when no references to an
object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed. There is no
explicit need to destroy objects.

Garbage collection only occurs sporadically (periodically) during


the execution of your program. It will not occur simply because
one or more objects exist that are no longer used.
TEKZUNE TECHNOLOGIES 67

finalize() method
Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-Java
resource such as a file handle or character font, then we might
want to make sure these resources are freed before an object is
destroyed.

To handle such situations, Java provides a mechanism called


'finalization'. By using finalization, we can define specific actions
that will occur when an object is just about to be reclaimed by the
garbage collector.

To add a finalizer to a class, we simply define the 'finalize()'


method. The Java run time calles that method whenever it is
about to recycle an object of that class. Inside the finalize()
method, we will specify those actions that must be pefroemed
before an object is destroyed.

The gargabe collector runs periodically, checking for objects, that


are no longer referenced by any running state or indirectly
through other referenced objects.

Access Specifiers: An access specifier is a key word that


specifies how to access the members of a class
or a class itself.
We can use access specifiers before a class and its members.

There are four access specifiers:

1) Private: 'private' members of a class are not accessible any


where outside the class. They are
accessible only within the class by the methods of that class.

2) Public: 'public' members of a class are accessible every where


outside the class. So any other
program can read them and use them.

3) protected: 'protected' members of a class are accessible


outside the class, but generally, within the
TEKZUNE TECHNOLOGIES 68

same directory.

4) default: If no access specifiers is written by the programmer,


then the java compiler uses a 'default'
access specifier. 'default' members are accessible outside the
class, but the within the same directory.

/*32.a Example program on a class*/

public class Person


{
//Variables are nothing but Properties
int age;
String name;

//actions - method
void display() {
[Link]("Hello I am " + name);
[Link]("My age is" + age);
}
}

//Note: Only compile this program not execute because there


is //no main() method in this program

E:\>javac [Link]

/*32.b Example program on a class and objects*/

public class Simple_Class


{
public static void main(String args[])
{
//Creating an object of person class
TEKZUNE TECHNOLOGIES 69

Person obj=new Person();

// Initializing the variables using the reference


[Link]="JUNAID";
[Link]=21;

//call the talk() method


[Link]();

}
}

OUTPUT:

E:\>javac Simple_Class.java

E:\>java Simple_Class
Hello I am JUNAID
My age is21

/*33.a Example program on a class and objects*/

class Sample
{
int a,b,c;

void add()
{
c=a+b;
[Link]("Sum of two numbers = " + c);
}
}

E:\>javac [Link]

/*33.b Example program on a class and objects*/

class SampleDemo
TEKZUNE TECHNOLOGIES 70

{
public static void main(String args[])
{
Sample s=new Sample();

s.a=10;
s.b=20;
[Link]();
}
}

OUTPUT:

E:\>javac [Link]

E:\>java SampleDemo
Sum of two numbers = 30

/*34.a Example program on a class and objects*/

class Sample1
{
private int a,b,c;

void add(int x,int y)


{
a=x;
b=y;

c=a+b;
[Link]("Sum of two numbers = " + c);
}
}

E:\>javac [Link]

/*34.b Example program on a class and objects*/

class SampleDemo1
TEKZUNE TECHNOLOGIES 71

{
public static void main(String args[])
{
Sample1 s=new Sample1();
[Link](10,20);
}
}

OUTPUT:

E:\>javac [Link]

E:\>java SampleDemo1
Sum of two numbers = 30

/*35.a Example program on a class and objects*/

class Sample2
{
private int a,b,c;

int add(int x,int y)


{
a=x;
b=y;

c=a+b;
return c;
}
}

E:\>javac [Link]

/*35.b Example program on a class and objects*/

class SampleDemo2
{
public static void main(String args[])
{
TEKZUNE TECHNOLOGIES 72

Sample2 s=new Sample2();


int sum;

sum=[Link](10,20);
[Link]("Sum of two numbers = " + sum);
}
}

E:\>javac [Link]

E:\>java SampleDemo2
Sum of two numbers = 30

/*36. Initializing the instance variables */


class Person1
{
//Instance variables are initialized here
String name="Hassan";
int age=30;

//methods
void talk()
{
[Link]("Hello I am" + name);
[Link]("My age is " + age);
}
}

class Demo
{
public static void main(String args[])
{
//Create person class obj
Person1 obj=new Person1();

//initialize Person class variables again here


[Link]="Sami";
[Link]=22;
TEKZUNE TECHNOLOGIES 73

//call the talk() method


[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java Demo
Hello I amSami
My age is 22

Introducing Nested and Inner Classes:

It is possible to define a class within another class; such classes


are known as nested classes. The scope of a nested class is
bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B is known to A, but no outside of A. A
nested class has access to the members, including private
members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the
nested class.

There are two types of nested classes: static and non-static.


A static nested class is one which has the static modifier applied.
Because it is static, it must access the members of its enclosing
class through an object. That is, it cannot refer to members of its
enclosing class directly. Because of this restriction, static nested
classes are seldom used.
The most important type of nested is the inner class.
An inner class is a non-static nested class. It has access to all of
the variables and methods of its outer class and may refer to
them directly in the same way that other non-static members of
the outer class do. Thus,ln an inner class is fully within the scope
of its enclosing class.

The following program illustrates how to define and use an inner


class. The class named Outer hasone instance variable named
TEKZUNE TECHNOLOGIES 74

outer_x, one instance method named test(), and defines one inner
class called Inner.

/*37. Example program on Inner class Concept */

class Outer
{
int outer_x=100;
void test()
{
Inner inner=new Inner();
[Link]();
}

//this is an inner class

class Inner
{
void display()
{
[Link]("display: outer_x=" + outer_x);
}
}
}

class InnerDemo {
public static void main(String args[]) {
Outer outer=new Outer();

[Link]();
}
}

OUTPUT:

E:\>javac [Link]

E:\>java InnerDemo
TEKZUNE TECHNOLOGIES 75

display:outer_x=100

/*38. This program will not compile */

class Outer1
{
int outer_x=100;

void test()
{
Inner1 inner =new Inner1();
[Link]();
}

class Inner1
{
int y=20; //y is local to Inner
void display()
{
[Link]("display:outer_x==" +outer_x);
}
}

void showy()
{
[Link](y); //error, y not known here
}
}

class InnerDemo1 {
public static void main(String args[]) {
Outer1 outer=new Outer1();
[Link]();
}
}

E:\>javac [Link]
[Link]: cannot find symbol
symbol : variable y
TEKZUNE TECHNOLOGIES 76

location: class Outer1


[Link](y); //error, y not known here
^
1error

/*39. Example program before Constructor concept */

class Box {
double width;
double height;
double depth;

//This is method
double volume() {
return width*height*depth;
}
}
TEKZUNE TECHNOLOGIES 77

public class BoxDemo {

public static void main(String args[]) {

Box mybox1=new Box();


Box mybox2=new Box();
Box mybox3=new Box();

double vol;

//Assign values to mybox1's instance variables

[Link]=10;
[Link]=20;
[Link]=30;

//Here we are invoking the method volume()


vol=[Link]();

//Print the result of first object

[Link]("The volume of first box is=" +vol);

//Assign values to mybox2's instance variables

[Link]=3;
[Link]=8;
[Link]=20;

vol=[Link]();

//Print the result of second object

[Link]("The volume of second box is=" +vol);

//Assign values to mybox3's instance variables


TEKZUNE TECHNOLOGIES 78

[Link]=6;
[Link]=12;
[Link]=15;

vol=[Link]();

//Print the result of third object

[Link]("The volume of third box is=" +vol);

}
}

OUTPUT:

E:\>javac [Link]

E:\>java BoxDemo
The volume of first box is=6000.0
The volume of second box is=480.0
The volume of third box is=1080.0

Constructor: A constructor initializes an object immediately


upon [Link] has the same name as the class in which it
resides and is syntactically similar to a methods.

Once defined, the constructor is automatically called immediately


after the object is created, before the new operator completes.

Constructor will look strange because they have no return type,


not even void.
This is because immmplicit return type of a class' constructor is
the class type itself.
TEKZUNE TECHNOLOGIES 79

/*40. Example program on Constructor concept */

public class Box1 {

double width;
double height;
double depth;

//This is constructor for Box Class


Box1()
{
width=10;
height=20;
depth=30;
}
// This is method

double volume() {

return width*height*depth;
}
}

public class ConsDemo


{
public static void main(String args[])
{
Box1 mybox1=new Box1();
Box1 mybox2=new Box1();
Box1 mybox3=new Box1();

double vol;

vol=[Link]();

//Printing the result of first object


[Link]("The volume of first box is=" +vol);

vol=[Link]();
TEKZUNE TECHNOLOGIES 80

//Printing the result of second object


[Link]("The volume of second box is="+vol);

vol=[Link]();
//Printing the result of third object
[Link]("The volume of third box is="+vol);
}
}

OUTPUT
E:\>javac [Link]

E:\>java ConsDemo
The volume of first box is=6000.0
The volume of second box is=6000.0
The volume of third box is=6000.0

Parameterized Constructor: While the Box() constructor in the


preceding example does initialize a Box object,but it is not very
useful, as all boxes gave the same dimensions.
what is needed is a way to construct Box objects of various
dimensions. The easy solution is to add parameters to the
constructor.

/*41. Example program on Parameterized Constructor


concept */
public class Box2{

double width;
double height;
double depth;
//This is parameterized constructor
Box2(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
//This is mothod
TEKZUNE TECHNOLOGIES 81

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

public class Paracons {


public static void main(String args[])
{
Box2 mybox1=new Box2(2,3,4);
Box2 mybox2=new Box2(10,20,15);
Box2 mybox3=new Box2(15,16,12);

double vol;
//Printing value of first box
vol=[Link]();
[Link]("The volume for first box is=" +vol);

//Printing value of second box


vol=[Link]();
[Link]("The volume for second box is=" +vol);

//Printing value of third box


vol=[Link]();
[Link]("The volume for third box is=" +vol);
}
}
OUTPUT
E:\>javac [Link]

E:\>java Paracons
The volume for first box is=24.0
The volume for second box is=3000.0
The volume for third box is=2880.0
Constructor Overloading: When two or more constructor within
a class has the same name as long as their parameters are
different then we call it as “constructor overloading”.
TEKZUNE TECHNOLOGIES 82

/*42. In the following program we declare three


constructors to initialize the dimensions of a box in
various ways (Constructor Overloading). */

class Box3 {
double width;
double height;
double depth;

//constructor used when all dimensions specified


Box3(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}

//constructor used when no dimensions specified


Box3()
{
width=-1; //We use -1 to indicate an uninitialized box
height=-1;
depth=-1;
}

//Constructor used when cube is created


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

//compute and return value


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

class Overloadcons
TEKZUNE TECHNOLOGIES 83

{
public static void main(String args[])
{
//Create boxes using the various constructors
Box3 mybox1=new Box3(10,20,30);
Box3 mybox2=new Box3();
Box3 mycube=new Box3(7);

double vol;

//Get volume of first box


vol=[Link]();
[Link]("Volume of first box is:" + vol);

//Get volume of second box


vol=[Link]();
[Link]("Volume of second box is:" + vol);

//Get volume of cube


vol=[Link]();
[Link]("Volume of cube is:" + vol);
}
}
OUTPUT
E:\>javac [Link]

E:\>java Overloadcons
Volume of first box is:6000.0
Volume of second box is:-1.0
Volume of cube is:343.0
TEKZUNE TECHNOLOGIES 84

METHODS
Methods: A method represents a group of statements that
performs a task. Task can be anything like calculation or
processing of data.

The syntax for method:


type method-name(parameter-list1,parameter-list2...)
{
//Body of method

Above, type specifies the type of the data the method will return
and method-name is the name of the method.
The parameter-list specifies no. of arguments the method will
return or receives.

When the method is not returning any value then its return -type
must be 'void'. As void returns nothing.

The methods can be with parameter or without parameters.

/*43. Program for method with no parameter and no


return-type.*/
class Addition
{
//Variables are nothing but Properties

int num1;
int num2;

//actions - method
void sum()
{
[Link]("The sum of two no = " +
(num1+num2));

}
TEKZUNE TECHNOLOGIES 85

public class Methods


{
public static void main(String args[])
{
//Creating an object of Addition class
Addition obj=new Addition();

// Initializing the variables using the reference


obj.num1=10;
obj.num2=21;

//call the sum() method


[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java Methods
The sum of two no = 31

/*44. Program for method with return type. */

class Method_Ret
{
//Instance variables
double num1,num2;

double sum()
{
double res=num1+num2;
return res;
}

}
TEKZUNE TECHNOLOGIES 86

class Method1
{
public static void main(String args[])
{
Method_Ret s=new Method_Ret();
s.num1=10;
s.num2=15.5;
double x=[Link]();
[Link]("The sum:" +x);
}
}

OUTPUT:

E:\>javac [Link]

E:\>java Method1
The sum:25.5

Instance Methods:
Instance methods are the methods which act upon the instance
variables. To call the instance methods, object is needed, since
the instance variables are contained in the object. We call the
instance methods by using '[Link]()'.

->The speciality of instance methods is that they can access not


only instance variables but also static variables directly.

There are two types of instance methods:


-------------------------------------------------
[] Accessor methods
[] Mutator methods

->Accessor methods are the methods that simply access or read


the instance variables. They do not modify the instance variables.

->Mutator methods not only access the instance but also modify
them.
TEKZUNE TECHNOLOGIES 87

/*45. Example program onAccessor and mutator methods */


class Person
{
//instance variables
private String name;
private int age;

//mutator methods to store data


public void setName(String name)
{
[Link]=name;
}

public void setAge(int age)


{
[Link]=age;
}
//accessor methods to read data
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}

class InstanceMethods
{
public static void main(String args[])
{
//create an empty Person class object
Person p=new Person();

//store some data into the object


[Link]("Junaid");
[Link](24);
TEKZUNE TECHNOLOGIES 88

//access data from object


[Link]("Name= " + [Link]());
[Link]("Age = " + [Link]());
}
}

OUTPUT:
E:\>javac [Link]

E:\>java InstanceMethods
Name= Junaid
Age = 24

/*46. Program for a method with two parameters and


return type.*/

class methodpara{
double sum(double num1,double num2)
{
double res=num1+num2;
return res;
}
}

class Methodpar
{
public static void main(String args[])
{
methodpara s=new methodpara();

double x=[Link](10,15.5);
[Link]("The sum is:" + x);
}
}

OUTPUT:
E:\>javac [Link]
TEKZUNE TECHNOLOGIES 89

E:\>java Methodpar
The sum is:25.5

this: 'this' is a keyword that refers to the object of the


class where it is used. In other words, 'this' refers to the
object of the present class. Generally, we write instance
variables, constructors and methods in a class. All these members
are referenced by 'this'. When an object is created to a class,
a default reference is also created internally to the object.
This default reference is nothing 'this'. So 'this' can reer to
all the things of the present object. */

/*47. Program on ‘THIS’ keyword concept.*/

class Sample
{
private int x;

Sample()
{
this(55); //call present class para constructo and send 55
[Link](); //call present class method
}

//parameterized constructor
Sample(int x)
{
this.x=x; //refer present class instance variable
}

//method
void square()
{
[Link]("Square value x = " + x*x);
}
}

class ThisDemo
{
TEKZUNE TECHNOLOGIES 90

public static void main(String args[])


{
Sample s=new Sample();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java ThisDemo
Square value x = 25

/*Static Methods: A static method is a method that does not act


upon instance variables of a class. A static method is declared
by using the keyword 'static'. Static methods are called using
[Link](). The reason why staic methods can not
act
on instance variables is that the JVM first executes the static
methods and then only it creates the objects. Since the objects
are not available at the time of calling the static methods,
the instance variables are also not available. */

/*48. Program or a static method that accepts data and


returns the result.*/

class Sample
{
static double sum(double num1,double num2)
{
double result=num1+num2;
return result;
}
}

class StaticMethod
{
public static void main(String args[])
{
double x=[Link](10,22.4);
TEKZUNE TECHNOLOGIES 91

[Link]("Sum = " + x);


}
}

OUTPUT:
E:\>javac [Link]

E:\>java StaticMethod
Sum = 32.4

/*Note: This program will not execute and shows error


because static method is trying to access instance
variable of a class*/

/*49. Program to test whether a static method can access the


instance variable or not*/

class Test
{
// intance variable
int x;

//parameterized constructor
Test(int x)
{
this.x=x;
}

//static method accessing x value


static void access()
{
[Link]("x= " + x);
}
}

class StaticDemo
{
public static void main(String args[])
TEKZUNE TECHNOLOGIES 92

{
Test obj=new Test(55);
[Link]();
}
}

OUTPUT:

E:\javac [Link]
[Link]: non-static variable x cannot be referenced
from a static context
[Link]("x= " + x);
1 error

/*50. Program to test whether a static method can access


the static variable or not. */

//Static method accessing static variable


class Test1
{
//static variable
static int x=55;

//static method accessing x value


static void access()
{
[Link]("x = " +x);
}
}

class StaticDemo1
{
public static void main(String args[])
{
[Link]();
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 93

E:\>javac [Link]

E:\>java StaticDemo1
x = 55

/*51. Program to call 'STATIC' method from 'NON-STATIC'


context*/
class Test1
{

static int a=10,b=3,c;

void add()
{
c=a+b;
[Link]("Sum of two static integers = " + c);

sub();
}
static void mul()
{
c=a*b;
[Link]("Product of two static integers = " + c);
//add();
}
//static method accessing x value
static void sub()
{
c=a-b;
[Link]("Sub of two numbers = " + c);
}
}
class StaticDemo2
{
public static void main(String args[])
{
Test1 obj=new Test1();
[Link]();
TEKZUNE TECHNOLOGIES 94

//Test.a=5;
//Test.b=7;

[Link]();
[Link]();
}
}
OUTPUT:

E:\Methods>javac [Link]

E:\Methods>java StaticDemo2
Sum of two static integers = 13
Sub of two numbers = 7
Sub of two numbers = 7
Product of two static integers = 30
Static Block: A static block is a block of statements declared
as 'static', some thing like this:
static {
statements;
}
- ->JVM executes a static block on a highest priority basis. This
means JVM first goes to static block even before it looks or the
main() method in the program. This is shown in the following
example as:

/*52. Program to test 'STATIC' block before ‘main()’


method */

class Test3
{
static {
[Link]("Static block1");
}

static {
[Link]("Static block2");
}
TEKZUNE TECHNOLOGIES 95

public static void main(String args[])


{

[Link]("Static method or in main() method");

static {

[Link]("Static block3");
}

OUTPUT
E:\>javac [Link]

E:\>java Test3
Static block1
Static block2
Static block3
Static method or in main() method

/*53. Calling a static method from another static method*/


public class TestMax
{
public static void main(String args[])
{
int i=5,j=3;
int k=max(i,j);
[Link]("The maximum between " + i + " and " + j
+ " is " + k);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
TEKZUNE TECHNOLOGIES 96

}
}

OUTPUT:
E:\>javac [Link]

E:\>java TestMax
The maximum between 5 and 3 is 5

Recursion: A method calling itself again and again is called as


recursive method and this phenomenon is known as 'Recursion'.

/*54. Example program on ‘RECURSION’ concept*/

class Recursion
{
static long factorial(int num)
{
long result;
if(num==1)
return 1;

result =factorial(num-1)*num;

return result;
}

public static void main(String args[])


{
[Link]("Factorial of 5 is :");
[Link]([Link](5));
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Recursion
Factorial of 5 is :
TEKZUNE TECHNOLOGIES 97

120

Passing Objects to Methods


We can also pass class objects to methods, and return objects
from the methods. This means, when we send an object to a
method, its bit by bit copy will be sent to the method. So when we
come out of the method, we find the original value unchanged.

When we pass objects to a method, actually a copy of the


references of object is passed to the method where they will be
interchanged. Outside the method, the original object will remain
same. So, when we come out of method, we find the values are
not changed.

/*55. Example program on passing objects as arguments


to methods. */

class Employee
{
int id;

Employee(int id)
{
[Link]=id;
}
}

class Check
{
void swap(Employee obj1,Employee obj2)
{
Employee temp;
temp=obj1;
obj1=obj2;
obj2=temp;
}
}
TEKZUNE TECHNOLOGIES 98

class PassObjects
{
public static void main(String args[])
{
Employee obj1=new Employee(10);
Employee obj2=new Employee(20);

Check c=new Check();

//display data before calling


[Link]([Link] + "\t" + [Link]);

[Link](obj1,obj2);

//display data after calling


[Link]([Link] + "\t" + [Link]);
}
}

OUTPUT

E:\>javac [Link]

E:\>java PassObjects
10 20
10 20

/*
In the preceding program we have seen even though we are
passing the objects as arguments to methods their values in the
main() remain same. So, how can we interchange the values ?

One possible solution is to use only one object and take two
variables and interchange their values in the object.
*/

/*56. Example program on passing single object as


argument to method. */
TEKZUNE TECHNOLOGIES 99

class Employee1
{
int id1,id2;

Employee1(int id1,int id2)


{
this.id1=id1;
this.id2=id2;
}
}

class Check1
{
void swap(Employee1 obj)
{
int temp;
temp=obj.id1;
obj.id1=obj.id2;
obj.id2=temp;
}
}

class PassObjects1
{
public static void main(String args[])
{
Employee1 obj=new Employee1(10,20);

Check1 c=new Check1();

//display data before calling


[Link](obj.id1 + "\t" + obj.id2);
[Link](obj);

//display data after calling


[Link](obj.id1 + "\t" + obj.id2);
}
}
TEKZUNE TECHNOLOGIES 100

OUTPUT
E:\>javac [Link]

E:\>java PassObjects1
10 20
20 10
Factory Methods:
Factory methods are static methods only, but their intension is to
create an object depending on the user choice. Precisely, a
factory method is a method that returns an object to the class, to
which it belongs.
For example, getNumberInstance() is a factory method. The
reason is, it belongs to NumberFormat clas and returns an object
to NumberFormat class.

We can consider factory methods as alternative way to create


objects, other than the 'new' operator. So, new operator is not the
only way to create objects in Java.

At the time of creating objects, if the user has several types of


options(values) to be passed to the object, then several
overloaded constructors should be written in the class. For
example, there are 10 different types of values to be passed, then
10 constructors are needed to accept those 10 types to pass any
type of value through a parameter. Generally, the parameter is
used to pass different types of values. Based on the value passed,
the object is created by the factory method.

What is factory method?

A factory method is a method that creates and returns an object


to the class to which it belongs. A single factory method replaces
several constructors in the class by accepting different options
from the user, while creating the object.

There are four ways of creating objects in Java:


------------------------------------------------------------
1. Using new operator
TEKZUNE TECHNOLOGIES 101

Employee obj=new Employee();


Here, we are creating Employee class object 'obj' using new
Operator.

2. Using factory methods:


NumberFormat obj=[Link]();
Here, we are creating NumberFormat object using the factory
method getNumberInstance().

3. Using newInstance() method


Here, we should follow two step as:

(i). First, store the class name 'Employee' as a string into an


object. For this purpose, factory method forName() of the class
'Class' will be useful:
Class c=[Link]("Employee");
We should note that there is a clas with the name 'Class' in
[Link] package.

(ii). Next, create another object to the class whose name is nin
the object c. For this purpose, we need newInstance() method of
the class 'Class', as:
Employee obj=(Employee)[Link]();

4. By cloning an alraedy available obkect, we can create annother


object. Creating exact copy of an existing object is called
'cloning'.

Employee obj1=new Employee();


Employee obj2=(Employee)[Link]();

/*Using getNumberInstance() method to create an object to


NumberFormat class.

/*57. Write a program for calculating and displaying area of a


circle. The area is formatted to have 7 maximum integer digits
and 2 minimum fraction digits. */
*/
import [Link].*;
TEKZUNE TECHNOLOGIES 102

class Factory_Method
{
public static void main(String args[])
{
final double PI=(double)22/7;
double r=15.5;

double area=PI*r*r;
[Link]("Area = " + area);

//Creating NumberFormat class object


NumberFormat obj=[Link]();

//Store the format information into obj


[Link](2);
[Link](7);

//Apply the format to area value


String str = [Link](area);

//Display formatted area value


[Link]("Formatted area = " + str);
}
}

OUTPUT:
E:\>javac Factory_Method.java

E:\>java Factory_Method
Area = 755.0714285714286
Formatted area = 755.0714286

/*There is another way of using getNumberInstance()


method as:

getNumberInstance(Locale constant);
TEKZUNE TECHNOLOGIES 103

In the above, the parameter represents a constant that represent


the name of a country (locality) as [Link], [Link]
etc.
For example, to format a number according to the numerical
format of United States, we can pass that constant to the
NumberFormat object, as:
NumberFormat
obj=[Link]([Link])

In the place of getNumberInstance() method, if constructors are


provided in the NumberFormat class, they should be created
someting like: NumberFormat([Link]),
NumberFormat([Link]),..

In this way, several constructors should be created. This


awkwardness is avoided by using a single factory method
getNumberInstance() and passing the required name of the
country to it.

We can consider factory methods as alternative way to create


objects, other than the 'new' operator. So, new operator is not the
only way to create objects in Java.
*/

Math class: This class contains the methods needed to perform


basic mathematical unctions.
Methods of Math class are:
public static double sin(double radians)
public static double cos(double radians)
public static double tan(double radians)
public static double asin(double radians)
public static double exp(int)
public static double log(double )
public static double pow(int,int)
public static double pow(double,double)
public static double sqrt(double)
public static double max(int,int)
public static double min(int,int)
TEKZUNE TECHNOLOGIES 104

public static double random()

/*58. Example program on ‘MATH’ class. */

public class MathClass


{
public static void main(String args[])
{
[Link]("Performing various arithmetic operations: ");
[Link]();
[Link]("The log value of 12 is " + [Link](12));
[Link]("The exponential value of 2 is " +
[Link](12));
[Link]("The sin value of 37 is " + [Link](37));
[Link]("The cos value of 77 is " + [Link](77));
[Link]("The 3 power 3 value is " + [Link](3,3));
[Link]("The square root value of 49 is " +
[Link](49));
[Link]("The max value between 12 and 19 is " +
[Link](12,19));
[Link]("The min value between 12 and 19 is " +
[Link](12,19));
}
}

OUTPUT:
E:\>javac [Link]

E:\>java MathClass
Performing various arithmetic operations :

The log value of 12 is 2.4849066497880004


The exponential value of 2 is 162754.79141900392
The sin value of 37 is -0.6435381333569995
The cos value of 77 is -0.03097503173121646
The 3 power 3 value is 27.0
The square root value of 49 is 7.0
The max value between 12 and 19 is 19
The min value between 12 and 19 is 12
TEKZUNE TECHNOLOGIES 105

/*59. Example program to generate random characters. */

public class RandomCharacter


{
//Generate a random character between ch1 and ch2
public static char getRandomCharacter(char ch1,char ch2)
{
return (char)(ch1 + [Link]()*(ch2-ch1+1));
}

//Generate a random lower case letter


public static char getRandomLowerCaseLetter()
{
return getRandomCharacter('a','z');
}

//Generate a random upper case letter


public static char getRandomUpperCaseLetter()
{
return getRandomCharacter('A','Z');
}

//Generate a random digit character


public static char getRandomDigitCharacter()
{
return getRandomCharacter('0','9');
}

//Generate a random digit character


public static char getRandomCharacter()
{
return getRandomCharacter('\u0000','\uFFFF');
}
}

public class TestRandomCharacter


TEKZUNE TECHNOLOGIES 106

{
public static void main(String args[])
{
final int NUMBER_OF_CHARS = 175;
final int CHARS_PER_LINE =25;

//Print random characters between 'a' and 'z', 25 chars per line
for(int i=0;i<NUMBER_OF_CHARS; i++)
{
char ch=[Link]();
if((i+1) %CHARS_PER_LINE ==0)
[Link](ch);
else
[Link](ch);
}
}
}

OUTPUT:

E:\>javac [Link]

E:\>java TestRandomCharacter
hfdtjzhdmhspcuiscqtkczkis
ihlpvoomvuzxtulzibnwaeyvq
xrnavjojhogosxincbknyeblw
wzjrvgdcpqztiadahqohmbdvr
fhtwhbfyfhfhviqunavtkihrj
jscytvohktlnybesebfshszkf
bfxzlzanmxdyzmomseoardoig
TEKZUNE TECHNOLOGIES 107

RELATION BETWEEN OBJECTS


It is possible to create objects for different classes and establish
relationship between them. When the objects are related, this is
possible to access and use members of one object in another
object. THis becomes an advantage when an object should start
processing a data where another object has left. It is also helpful
to pass data from one object to another object and from there to
another object in a chained form.

There are three ways to relate objects in Java:


i. Using references
[Link] inner class concept
iii. Using inheritance.

Relating Objects using References:


-------------------------------------------
Let us create two classes, 'One' and 'Two'. Suppose we want to
access the members of class Two, in class One, we should relate
their objects. For this, just declare the reference variable of class
Two as an instance variable in class One.

class One
{
Two t;
} //Here 't' is the reference of class Two

Now this reference variable 't' can be used to refer to all the
members of class Two from One.

/*60. Write a program to take class One and class Two, and create
the reference of class Two in class One. Using this reference, let
us refer to the instance variables and methods of class Two.
*/

class One
{
int x;
Two t; //class Two's reference
TEKZUNE TECHNOLOGIES 108

//constructor that receives Two's reference


One(Two t)
{
//copy Two's reference into t
this.t=t;
x=10;
}

//method to display class One and class Two variables


void display()
{
[Link]("One's x= " + x);
//call class Two's method
[Link]();
//access class Two's variable
[Link]("Two's variable= " + t.y);
}
}

class Two
{
//instance variable
int y;

Two(int y)
{
this.y=y;
}

//method to display y
void display()
{
[Link]("Two's y= " + y);
}
}

class Relate
{
TEKZUNE TECHNOLOGIES 109

public static void main(String args[])


{
//create class Two object and store 22 there.
Two obj2=new Two(22);

//create class One object and pass class Two object to it


One obj1=new One(obj2);

//call class One's method


[Link]();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Relate
One's x= 10
Two's y= 22
Two's variable= 22

/*61. Write a program to take class One and class Two, and create
the reference of class Two in class One. Using this reference, let
us refer to the instance variables and methods of class Two. */

class One
{

Two obj2; //class Two's reference

//constructor that receives Two's reference


One(Two obj2)
{
//copy Two's reference into t
this.obj2=obj2;
}

double cube(double x)
{
TEKZUNE TECHNOLOGIES 110

//call class Two's method using obj2


double result=x*[Link](x);
//return result to Relate1 class
return result;
}
}

class Two
{
//obj3 is class Three's reference
Three obj3;

//initialize obj3
Two(Three obj3)
{
this.obj3=obj3;
}

double square(double x)
{
//call class Three's method using obj3
double result =x*[Link](x);

//return result to class One


return result;
}
}

class Three
{
double get(double x)
{
//just return x value to class Two
return x;
}
}

class Relate1
{
TEKZUNE TECHNOLOGIES 111

public static void main(String args[])


{

//create class Three object obj3


Three obj3=new Three();

//create class Two object obj2 and pass obj3


Two obj2=new Two(obj3);

//create class One object obj1 and pass obj2 to it


One obj1=new One(obj2);

//call cube() of class One


double result1=[Link](5);
[Link]("Cube of 5 = " + result1);

//call square() method of class Two


double result2=[Link](6);
[Link]("Square of 6 = " + result2);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Relate1
Cube of 5 = 125.0
Square of 6 = 36.0

/*
Inner Class:
--------------
Inner class is a class written within another class. Inner class is
basically a safety mechanism, since it is hidden from other
classes in its outer class.
TEKZUNE TECHNOLOGIES 112

To make instance variables not available outside the class, we


use 'private' access specifier before the variables. Thisis now we
provide the security mechanism to variables.

Similarly, insome cases, we want to provide security for the


ebntire class. In this case, can we use 'private' access specifier
before the class ?.

The problem is, if we use provate access specifier, before a class,


the class is not available to the java compiler or JVM. So it is
illegal to use 'private' before a class name in Java.

But, private specifier is allowed before an inner class and thus it


isuseful to provide security for the entire inner class. Onece
private is used before the inner class, it is not avaialable to other
classes.
This means an object to inner class cannot be created in any
other class.
*/

/*62. Let us make a program to create the outer class BankAcct


and the inner class Interest in it.*/

import [Link].*;

class BankAcct
{
private double bal;

BankAcct(double b)
{
bal=b;
}

void contact(double r) throws IOException


{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
TEKZUNE TECHNOLOGIES 113

[Link]("Enter password:");
String passwd=[Link]();

if([Link]("sohail"))
{
Interest in=new Interest(r);
[Link]();
}

else
{
[Link]("Sorry, you are not an authorized person ");
return;
}
}

//inner class
private class Interest
{
private double rate;

Interest(double r)
{
rate=r;
}

void calculateInterest()
{
double interest=bal*rate/100;
bal+=interest;
[Link]("Updated Balance is = " + bal);
}
}
}

class InnerClass
{
public static void main(String args[]) throws IOException
{
TEKZUNE TECHNOLOGIES 114

BankAcct account=new BankAcct(10000);


[Link](9.5);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java InnerClass
Enter password:
sohail
Updated Balance is = 10950.0

E:\>java InnerClass
Enter password:
abcd
Sorry, you are not an authorized person
TEKZUNE TECHNOLOGIES 115

INHERITANCE
Inheritance: The process of creating a new class from the
existing class, this new class will acquire or have all the features
of the existing class, is known as Inheritance.
or
Deriving a new class from the existing classes such that the new
classes acquire all the features of existing classes is called
Inheritance.

The existing class is called Parent or super class and new class is
called child or sub class.

We use the keyword 'extends', this means all the members of the
parent class are available to child [Link] use the parent class in
child class.

The syntax is:


class subclass extends superclass
{
body of class;
}

/*63. Example program Single Inheritance */

//Super class ‘Teacher’


class Teacher
{
//instance variables
int id;
String name;
String address;
float sal;

//Method to set id value


void setId(int id)
{
[Link]=id;
}
TEKZUNE TECHNOLOGIES 116

//Getter method to retrieve id


int getId()
{
return id;
}

//To store name


void setName(String name)
{
[Link]=name;
}

//To retrieve name


String getName()
{
return name;
}

//To store address


void setAddress(String address)
{
[Link]=address;
}

//To retrieve address


String getAddress()
{
return address;
}

//To store salary


void setSal(float sal)
{
[Link]=sal;
}

//To retrieve salary


float getSal()
{
TEKZUNE TECHNOLOGIES 117

return sal;
}
}

//Sub class Student


public class Student extends Teacher
{
int marks;

//To store marks


void setMarks(int marks)
{
[Link]=marks;
}

int getMarks()
{
return marks;
}
}

//Using Student class


class Use
{
public static void main(String args[])
{
//Create an object to Student class
Student s=new Student();

//Store data into object, for this use purpose setter methods
[Link](1001);
[Link]("Syed Sohail");
[Link]("43-2-3/1, Shanti Nagar, Malakpet,
Hyderabad");
[Link](542);

//Now display the entered data using getter methods


[Link]("Id=" + [Link]());
[Link]("Name=" + [Link]());
TEKZUNE TECHNOLOGIES 118

[Link]("Address=" + [Link]());
[Link]("Marks=" + [Link]());
}
}

OUTPUT
E:\>javac [Link]

E:\>java Use
Id=1001
Name=Syed Sohail
Address=43-2-3/1, Shanti Nagar, Malakpet, Hyderabad
Marks=542

Method Overriding: When a method in sub class has the same


and same parameter as in the super class then the method of sub
class will override the method of super class then it is called as
Method Overriding.

/*64. Example program on MethodOverriding */

class One
{
//Super class variable
int i=10;

//Super class method


void show()
{
[Link]("Super class method:i=" + i);
}
}

//This is sub class


class Two extends One
{
//sub class variable
int i=20;
TEKZUNE TECHNOLOGIES 119

//sub class method


void show()
{
[Link]("Sub class method:i=" + i);
}
}

class Three
{
public static void main(String args[])
{
//Create sub class object
Two t=new Two();

//This will call sub class method only


[Link]();
}
}

OUTPUT:

E:\>javac [Link]
E:\>javac [Link]
E:\>javac [Link]

E:\>java Three
Sub class method:i=20

/*65. Example program on Method Overriding */

super: super is the keyword with which we call the members of


the super class in sub class.

class One1
{
//Super class variable
int i=10;
TEKZUNE TECHNOLOGIES 120

//Super class method


void show()
{
[Link]("Super class method:i=" + i);
}
}

//This is sub class


class Two1 extends One1
{
//sub class variable
int i=20;

//sub class method


void show()
{
[Link]("Sub class method:i=" + i);
[Link]("Super class i=" + super.i);
[Link]();
}
}

class MethodOverriding
{
public static void main(String args[])
{
//Create sub class object
Two1 t=new Two1();

//This will call sub class method only


[Link]();
}
}
OUTPUT:
E:\>javac [Link]

E:\>java MethodOverriding
Sub class method:i=20
Super class i=10
TEKZUNE TECHNOLOGIES 121

Super class method:i=10

/*[Link] EXAMPLE IS FOR MULTI-LEVEL INHERITANCE*/

class student
{
protected int roll_number;
protected String name;
void get_info(int a,String n)
{
roll_number=a;
name=n;
}

void put_info()
{
[Link]("Roll number: " + roll_number);
[Link]("Student Name: " + name);
}
}

class test extends student


{
protected double sub1;
protected double sub2;

void get_marks(double x,double y)


{
sub1=x;
sub2=y;
}

void put_marks()
{
[Link]("Marks in SUB1 = " + sub1);
[Link]("Marks in SUB2 = " + sub2);
}
}
TEKZUNE TECHNOLOGIES 122

class result extends test //Second level derivation


{
double total;

void display()
{
total=sub1+sub2;
put_info();
put_marks();
[Link]("Total= " + total);
}
}
class MultiLevel
{
public static void main(String args[])
{
result student1=new result(); //student1 is an object of result

student1.get_info(111,"Suresh");
student1.get_marks(75.0,85.0);

[Link]();
}
}
OUTPUT:
E:\>javac [Link]

E:\>java MultiLevel
Roll number: 111
Student Name: Suresh
Marks in SUB1 = 75.0
Marks in SUB2 = 85.0
Total= 160.0

/*66. THIS EXAMPLE IS FOR using keyword "super" in


MULTI-LEVEL INHERITANCE */

class student1
{
TEKZUNE TECHNOLOGIES 123

int x=10;

void put_info()
{
[Link]("In Student x = " + x);
}
}

class test1 extends student1


{
int x=20;

void put_marks()
{
[Link]("Super class x = " + super.x);
[Link]("In test class x = " + x);

}
}

class result1 extends test1 //Second level derivation


{

int x=30;
void display()
{
put_info();
put_marks();
[Link]("In result class x = " + x);
[Link]("Super class x = " + super.x);
}
}

class MultiLevel1
{
public static void main(String args[])
{
result1 obj=new result1(); //student1 is an object of result
TEKZUNE TECHNOLOGIES 124

[Link]();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java MultiLevel1
In First x = 10
Super class x = 10
In Second class x = 20
In Third class x = 30
Super class x = 20

/*67. The following program creates a super class called Figure


that stores the dimensions of various two-dimensional objects. It
also defines a method called area () that computes the areas of
an object. The program derives two subclasses from Figure. The
first is Rectangle and the second is Triangle. Each of these
subclasses overrides area () so that it returns the area of a
rectangle and a triangle.*/

//Using run-time polymorphism

class Figure
{
double dim1;
double dim2;

Figure(double a,double)
{
dim1=a;
dim2=b;
}

double area()
{
[Link]("Area for Figure is undefined.");
return 0;
TEKZUNE TECHNOLOGIES 125

}
}

class Rectangle extends Figure


{
Rectangle(double a,double b)
{
super(a,b);
}

//override area for rectangle


double area()
{
[Link]("Inside Area for Rectangle.");
return dim1*dim2;
}
}

class Triangle extends Figure


{
Triangle(double a ,double b)
{
super(a,b);
}

//override area for right triangle


double area()
{
[Link]("Inside Area for Triangle.");
return dim1*dim2;
}
}
class FindArea
{
public static void main(Strig args[])
{
Figure f=new Figure(10,10);
Rectangle r=new Rectangle(9,5);
TEKZUNE TECHNOLOGIES 126

Triangle t=new Triangle(10,8);

Figure figref;

figref=r;
[Link]("Area is " + [Link]());

figref=t;
[Link]("Area is " + [Link]());

figref=f;
[Link]("Area is " + [Link]());

}
}

OUTPUT:
E:\>javac [Link]

E:\>java FindAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 80.0
Area for Figure is undefined.
Area is 0.0
Polymorphism

Polymorphism: Polymorphism came from the two Greek words


'poly' meaning many and 'morphos' meaning forms. The ability to
exist in different orms is called 'polymorphism', In java, a variable,
and object or method can exist in different forms, thus performing
various tasks depending on the context. Because same variable
or method can perorm different tasks, the programmer has the
advantage of writing flexible code.

Polymorphism with Variables:


TEKZUNE TECHNOLOGIES 127

When using variables, some times inherently the data type of the
result is decided by the compiler and accordingly execution
proceeds. For example, in the below statement:

[Link](a+b);

Java compiler decides the data type of the result of the


expression a+b depending on the data types of a and b. If a and b
are int type, then a+b will also be taken as int type. If a and b are
float type variables, then a+b will be taken as float type. If a is int
and b is float, then the compiler converts a also into float and
then sum is found. Thus, the result a+b is exhibiting polymorphic
nature. It may exist as anint or as a float oas aome other data
type depending on the context. This is also called as 'Coersion'.

Polymorphism with Methods:


If the same method performs different tasks, then that method is
said to exhibit polymorphism. Now, the crucial thing is to decide
which method is called in a particular context. This decision may
happen either at compile time or runtime.

This will lead to two types of polymorphism, Static Polymorphism


and Dynamic Polymorphism. The word 'static' represents compile
time and 'dynamic' represents at run time.

Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic
polymorphism. This means when a method is called, the method
call is bound to the method body at the time of running the
program, dynamically. In this case, Java compiler does not know
whcih method is called at the time of compilation. Only JVM knows
at runtime which method is to be executed. Hense, this is also
called 'runtime polymorphism' or 'dynamic polymorphism'.

Let us take an example:


class Sample
{
void add(int a,int b)
{
TEKZUNE TECHNOLOGIES 128

[Link]("Sum of two nos = " + (a+b));


}

void add(int a,int b,int c)


{
[Link]("Sum of three nos = " + (a+b+c));
}
}

class abc
{
public static void main(String args[])
{
Sample s=new Sample();
[Link](10,20);
}
}

Now, who will decide which method is to be executed? Is it Java


compiler or JVM? Because the methods are called by using an
object, the Java compiler cannot decide at the time of compilation
which method is actually called by the user. It has to wait till the
object is created for Sample class. And the creation of object
takes place at runtime by JVM. Now, JVM should decide which
method is actually called by the user at runtime (dynamically).

/*68. Program implementing Dynamic polymorphism concept


which two having two methods with same name but different
signarutes or parameters*/

class Sample
{
void add(int a,int b)
{
[Link]("Sum of two = " + (a+b));
}

void add(int a,int b,int c)


{
TEKZUNE TECHNOLOGIES 129

[Link]("Sum of three = " + (a+b+c));


}
}

class Poly
{
public static void main(String args[])
{
Sample s=new Sample();
[Link](10,20);
[Link](10,20,30);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Poly
Sum of two = 30
Sum of three = 60

/*69. Program where calculate() method of super class is


overridden by the calculate() method of sub class. The behaviour
of the calculate() method is dynamically decided. */
class One
{
void calculate(double x)
{
[Link]("Square value = " + (x*x));
}
}

class Two extends One


{
void calculate(double x)
{
[Link]("Square root = " + [Link](x));
}
}
TEKZUNE TECHNOLOGIES 130

class Poly1
{
public static void main(String args[])
{
Two t=new Two();
[Link](25);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Poly1
Square root = 5.0

/*
Static Polymorphism: The polymorphism exhibited at
compilation time is called static polymorphism. Here the Java
compiler knows without any ambiguity (confusion) which method
is called at the time of compilation. Of course, JVM executes the
method later, but the compiler knows and can bind the method
call with method code (body) at the time of compilation. So, it is
also called 'static binding' or 'compile time polymorphism'.

The example for static polymorphism is 'static method’,’ private


methods and final method. The reason why all these methods are
called as static polymorphism is that all of these methods
maintain only one copy in memory that is available to the objects
of the class.
So the Java compiler knows which method is called at the time of
compilation and it needs not wait till the objects are created.
Since at the time of compilation, the method call can be bound
with actual method body, this comes under static polymorphism.

Polymorphism with Static Methods:


--------------------------------------------
TEKZUNE TECHNOLOGIES 131

A static method is a method whose single copy in memory is


shared by all the objects of the class. Static methods belong to
the class rather than to the objects. So they are also called class
methods. When static methods are overloaded or overridden,
since they do not depend on the objects, the Java compiler need
not wait till the objects are created to understand which method
is called.
*/

/*70. Example program on ‘STATIC POLYMORPHISM’ */


class One
{
static void calculate(double x)
{
[Link]("Square value = " + (x*x));
}
}

class Two extends One


{
static void calculate(double x)
{
[Link]("Square root = " + [Link](x));
}
}

class Poly2
{
public static void main(String args[])
{
One o=new Two();
[Link](25);
}
}

/*
Note: In the above program, the super class method is called. If
sub class reference is used to call the calculate() method, then
TEKZUNE TECHNOLOGIES 132

sub class method is called. In class Poly2, we created super class


references to sub class object , as:

One o=new Two();


Here 'o' is super class reference variable. Using this variable, we
are calling the calculate() method as [Link](25). So the super
class calculate() method is executed.
*/

OUTPUT:
E:\>javac [Link]

E:\>java Poly2
Square value = 625.0

/*71. Example program for static polymorphism using


keyword 'static' */
//This program will not compile and give error
class One2
{
static void calculate1(double x)
{
[Link]("Square value = " + (x*x));
}
}

class Two2 extends One2


{
void calculate1(double x)
{
[Link]("Square root = " + [Link](x));
}
}

class Poly3
{
public static void main(String args[])
{
Two2 t=new Two2();
TEKZUNE TECHNOLOGIES 133

t.calculate1(25);
}
}

OUTPUT:

E:\>javac [Link]
[Link]: calculate1(double) in Two2 cannot override
calculate1(double) in
One2; overridden method is static
void calculate1(double x)
^
1 error

/*72. Example program for static polymorphism using


keyword 'final' */
class One3
{
final void calculate1(double x)
{
[Link]("Square value = " + (x*x));
}
}

class Two3 extends One3


{
void calculate1(double x)
{
[Link]("Square root = " + [Link](x));
}
}

class Poly4
{
public static void main(String args[])
{
Two3 t=new Two3();
t.calculate1(25);
}
TEKZUNE TECHNOLOGIES 134

OUTPUT:
E:\>javac [Link]
[Link]: calculate1(double) in Two3 cannot override
calculate1(double) in
One3; overridden method is final
void calculate1(double x)
^
1 error

/*73. In the following program, we are creating a super


class object from the sub class object. */
class One1
{
void calculate(double x)
{
[Link]("Square value = " + (x*x));
}
}

class Two1 extends One1


{
void calculate(double x)
{
[Link]("Square root = " + [Link](x));
}
}

class Poly_2
{
public static void main(String args[])
{
One1 o=new Two1();
[Link](25);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 135

E:\>javac Poly_2.java

E:\>java Poly_2
Square root = 5.0
TEKZUNE TECHNOLOGIES 136

TYPE CASTING

Converting one data type into another data type is called 'type
casting' or simply 'casting'. Whenever we asign a value to a
variable using assignment operator, the Java compiler checks or
uniormity and hence the data types at bot the sides should be
same. If the data types are not same, then we should convert the
types to become same at the both sides. To convert the data
type, we use 'cast operator. Cast operator means writing the data
type between simple braces, before a variable or method whose
value is to be converted.

Types of Data Types


There are two types of data types, as given here:

i. Primitive Data Types or Fundamental Data Types

The data types which represent a single entity (or value) are
called 'primitive data types'. For example, take 'int' type, it can
store only one integer value. Take 'boolean' value, it can store
either true or false - only one value. So they come under primitive
data types.
The following are the primitive data types:

char, byte, short, int, long , float, double, boolean

ii. Referenced Data Types or Advanced Data Types

These data types represent several values. For example, take an


array. It can store several values. Similarly take a class. It can
different values. So they are called advanced data types. We can
access an array or an object of a class in memory through
references. So, they are also called 'referenced data types'. The
following are eamples for referenced data types:

array, class(String, StringBuffer, Employee, Manager etc)

-->We can convert a primitive data type into another primitive


data type using casting. Similarly, it is possible to convert a
TEKZUNE TECHNOLOGIES 137

referenced data type into another referenced data type by using


casting.
But we cannot convert a primitive data type into a referenced
data type by using casting.

Casting Primitive Data Types

It is possible to convert one primitive daa type into another


primitive data type. This is done in two ways, widening and
narrowing. The primitive data types are classeied into two types,
lower types and higher types. Naturally, the lower types are the
types which use less memory and which can represent lesser
number of digits in the value. The higher types use moer memory
and can represent more number of digits. To recognize the lower
and higher types, the following digram is useful:

byte, short, char, int, long, float, double


lower <----------------------------------->higher

Widening in Primitive Data Types


________________________________

Converting a lower data type into a higher data type is called


widening. For example
char ch='A';
int num=(int)ch; //num contains 65,the ASCII value of'A'.
Here, we are converting char type variable 'ch' into int.

int x=9500;
float sal=(float)x;
Here, we are converting int type variable 'x' into float.

Implicit Casting: Automatic casting done by the Java compiler


internally is called implicit casting. Implicit casting is done when
to convert a lower data type into a higher data type.

Explicit Casting: The casting done by the programmer is called


eplicit casting. Explicit casting is compulsory while converting rom
a higher data type toa lower data type.
TEKZUNE TECHNOLOGIES 138

Narrowing in Primitive Data Types


_________________________________

Converting a higher data type into a lower data type is called


'narrowing'.
Example:
int n=66;
char ch=(char)n; //ch contains 'B' ASCII code

double d=12.54;
int n=(int)d;

Casting Referenced Data Types:


---------------

A class is a referenced data type. Converting a class type into


another class type is also poible through casting. But the calles
should have some relationship between them by the way of
inheritance.

For example, you cannot convert a 'Dog' class into a 'Horse' class,
as those classes do not have any relationship between them. But
you can convert a 'College' class into a 'University' class, since
'College' is derived from 'University'. And you can convert a
'Department' class into a 'College', since 'Department is a sub
clas of College.

University<------------- super class


^
|
|
|
College <------------ sub class
^
|
|
|
Department <----------- sub - sub class
TEKZUNE TECHNOLOGIES 139

Generalization and Specialization:

Generalization: Converting a sub class type into a super class


type is called 'generallization', because we are making the sub
class to become more general and tis scope is widening. This is
also called widening or upcasting. Widening is safe because the
classes will become more general.
For example, if we say lemon is a fruit, there be no objection.
Hence, java compiler will not ask for cast operator in
generalization. It will do implicit casting.

Specialization: Converting a super class type into a sub class


type is called 'specialization'. Here, we are coming down from
more general form to a specific form and hence the scope is
narrowed. Hence, this is also called narrowing or down-casting.
Narrowing is note safe because, the classes will become more and
more specific thus giving rise to more and more doubts. For
example, if we say so and so fruit
is a citrus, we should show proof for the statement, since we are
becoming more specific. In this case, Java compiler specifically
asks the programmer to use cast operator.

Generally, any class reference can be used to refer to that clas


object only. For example,

Example e; //Here e is the reference variable of Example class

e=new Example(); //Here e, is used to refer to Example class


object

But when, we try to use a reference to refer to a differentclass


object, we need casting. For example, if class One's reference is
used to refer to class Two's object as:

One o=new Two();


TEKZUNE TECHNOLOGIES 140

At the left side, we got the refernce 'o' whose data type is class
One. At the right side, we got the object whose data type is class
Two . Now it is essential, we convert the object's data type into
class One using cast operator as:

One o=(One) new Two(); //convert class Two's type as class


one

Here, sub class object type is converted into super class. This is
an example for widning or upcasting. In this case, even if we do
not use cast operator, there will not be any error message,as the
Java compiler will do implicit casting. Similarly, we can convert
class One's tpe as class Two's type in this case:

Two t=(Two) new One(); //Convert class One's type as class


Two

Here, we are converting from super class sub class, which comes
under narrowing or down casting. In this case, cast operator is
compulsory as this is unsafe operation.

/*
Widening in Refenced Data Types
-----------------------------------------
Let us observe the difference between widening and narrowing in
case of rerenced data types.

74. Write a program to see the widening effect where super class
reference is used to refer to sub class object.
*/

class One
{
void show1()
{
[Link]("Super class method");
}
}
TEKZUNE TECHNOLOGIES 141

class Two extends One


{
void show2()
{
[Link]("Sub class method");
}
}

class Cast
{
public static void main(String args[])
{
One o; // o is super clas reference
o=(One)new Two(); //o is referring to sub class object
//The above is widening
o.show1();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Cast
Super class method

/*75. Write a program to override the super class show1()


method in sub class. Now only the sub class method is
executed.*/

class One1
{
void show1()
{
[Link]("Super class method");
}
}

class Two1 extends One1


{
TEKZUNE TECHNOLOGIES 142

void show1()
{
[Link]("Sub class method");
}
}

class Cast1
{
public static void main(String args[])
{
One1 o; // o is super clas reference
o=(One1)new Two1(); //o is referring to sub class object
//The above is widening
o.show1();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Cast1
Sub class method

/*76. Write a program for creating super class reference to


refer to sub class object.*/

class One2
{
void show1()
{
[Link]("Super class method");
}
}
class Two2 extends One2
{
void show2()
{
[Link]("Sub class method");
}
TEKZUNE TECHNOLOGIES 143

class Cast2
{
public static void main(String args[])
{
One2 o; // o is super clas reference
o=new Two2(); //super class reference to refer to sub class
objects
Two2 t=(Two2)o; //This is narrowing -- convert class one1
//reference type as class Two's type
t.show1();
t.show2();
}
}

OUTPUT:

E:\>javac [Link]

E:\>java Cast2
Super class method
Sub class method

/*
Widening in Refenced Data Types
-----------------------------------------
Let us observe the difference between widening and narrowing in
case of rerenced data types.

77. Write a program to see the widening effect where


super class reference is used to refer to sub class object.
*/

class One
{
void show1()
{
[Link]("Super class method");
TEKZUNE TECHNOLOGIES 144

}
}

class Two extends One


{
void show1()
{
[Link]("Sub class method");
}
}

class CastDemo
{
public static void main(String args[])
{
One o; // o is super clas reference
o=(Two) new Two(); //o is referring to sub class object
//The above is widening
o.show1();
// o.show1();
}
}

OUTPUT:

E:\>javac [Link]

E:\>java CastDemo
Sub class method
The OBJECT Class
----------------------
There is a class with the name 'Object' in [Link] package which
is the super class of all classes in Java. Every class in Java is a
direct or indirect sub class of the Object class. The Object class
defines the methods to compare objects, to convert an object into
a string, to notify threads (processes) regarding the availability of
an object.
TEKZUNE TECHNOLOGIES 145

Object class reference can store any reference of any object. This
becomes an advantage when we want to write a method that
needs to handle objects of unknown type. If we define a
parameter of Object type, any class object can be passed to the
method. Thus, the method can receive any type of object and
handle it.

The methods of Object class are given below:

-------------------------------------------------------------------------
Method |Description
-------------------------------------------------------------------------
equals() |This method compares the references of two
|objects and if they are equal, it returns true,
|otherwise false. The way it compares the
objects |is dependent on the objects.
-------------------------------------------------------------------------
toString() |This method returns a string representation of an
|object. For example, the string representation of
|an Integer object is an integer number displayed
|as string.
-------------------------------------------------------------------------
getClass()|This method gives an object that contains the
|name of a class to which an object belongs.
|
hashCode() |This method returns hash code number of an
|object.
-------------------------------------------------------------------------
notify() |This method sends notification to a thread which
|is waiting for an object.
-------------------------------------------------------------------------
notifyAll() |This method sends a notification for all waiting
|threads for the object.
-------------------------------------------------------------------------
wait() |This method causes a thread to wait till a
|notification is received from a notify() or
|notifyAll() methods.
-------------------------------------------------------------------------
TEKZUNE TECHNOLOGIES 146

clone() |This method creates a bit wise exact copy of an


|existing object.
-------------------------------------------------------------------------
finalize() |This method is called by the garbage collector
|when an object is removed from memory.

/*
Let us use getClass() method to know the name of the class o
which an object belongs. In the below program, we are taking
Myclass which contains an int value. There is another class
KnowName which contains a static method printName().

78. Write a program where an object is passed to


printName() method and the class name of the object is
displayed by the method.
*/

class Myclass
{
int x;
Myclass(int x)
{
this.x=x;
}
}

//This class contains method to receive an object and display


the //classname
class KnowName
{
static void printName(Object obj)
{
//get the class nam into an object co f the class 'Class'
Class c=[Link]();
//get the name of the class using getName()
String name=[Link]();
[Link]("The class name is = " + name);
TEKZUNE TECHNOLOGIES 147

}
}

class GetClassName
{
public static void main(String args[])
{
Myclass obj=new Myclass(10);
[Link](obj);
}
}

OUTPUT:
E:\>javac [Link]

E:\>java GetClassName
The class name is = Myclass

/*
Let us see how to compare two objects by using equals() method
of Object class. This method normally compares the references of
two objects. If both the references refer to same object, thenit
gives true, otherwise it gives false. But in case of String objects
and wrapper class objects of the objects. If the contents are same
then it returns true, otherwise false.

In the below program, we are using equals() method to compare


two objects of a general class 'Myclass' and two objects of
wrapper class 'Integer'. in case of Myclass objects, if the
references are same, then equals() method gives true, otherwise
false. In case of Integer objects, it gives true if the contents are
same, otherwise false.

79. Write a program where equals() method compares


Myclass objects references. The same equals(0 method is
used to compare Integer class objects contents.
*/
TEKZUNE TECHNOLOGIES 148

class Myclass
{
int x;
Myclass(int x)
{
this.x=x;
}
}

class Compare
{
public static void main(String args[])
{
//create two Myclass objects with same contents
Myclass obj1=new Myclass(15);
Myclass obj2=new Myclass(15);

//create two wrapper class objects and store same content


//but in this case, references of objects will be different.
Integer obj3=new Integer(15);
Integer obj4=new Integer(15);

if([Link](obj2))
[Link]("obj1 and obj2 are same");
else
[Link]("obj1 and obj2 are not same");

if([Link](obj4))
[Link]("obj3 and obj4 are same");
else
[Link]("obj3 and obj4 are not same");
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Compare
obj1 and obj2 are not same
TEKZUNE TECHNOLOGIES 149

obj3 and obj4 are same


TEKZUNE TECHNOLOGIES 150

ABSTRACT CLASSES
Abstract Method and Abstract Class:

Abstract Method: An abstract method does not contain any


body. It contains only the mehtod header. So we can say it is an
incomplete method.

Abstract Class: An abstract class is a class that generally


contains some abstract methods. Both the abstract class and the
abstract methods should be declared by using the key word
'abstract'.

Since, abstract class contains incomplete methods, it is not


possible to estimate the total memory required to create the
object. So, JVM can not create objects to an abstract class. We
should create sub classes and all the abstract methods should be
implemented(body should be written) in the sub classes. Then, it
is possible to create objects to the sub classes since they
complete classes.
*/

/*80. In the below program, there is one abstract class called


‘Myclass’ and for this abstract we have created three sub classes
and in those sub classes we have implemented the method
according to our requirement. */
abstract class Myclass
{
//This is abstract method
abstract void calculate(double x);
}

class sub1 extends Myclass


{
//calculate square value
void calculate(double x)
{
[Link]("Square=" + (x*x));
}
}
TEKZUNE TECHNOLOGIES 151

class sub2 extends Myclass


{
//calculate square root value
void calculate(double x)
{
[Link]("Square root=" + [Link](x));
}
}

class sub3 extends Myclass


{
//calculate cube value
void calculate(double x)
{
[Link]("The cube =" +(x*x*x));
}
}

class Different
{
public static void main(String args[])
{
//create sub class object
sub1 obj1=new sub1();
sub2 obj2=new sub2();
sub3 obj3=new sub3();

//let the objects call and use calculate() method


[Link](3);
[Link](4);
[Link](5);
}
}

OUTPUT
TEKZUNE TECHNOLOGIES 152

E:\>javac [Link]

E:\>javac [Link]

E:\>java Different
Square=9.0
Square root=2.0
The cube =125.0

/*81. Example program for abstract class ‘Car’, this class has
concrete as well as abstract methods and for this class we have
created sub classes such as ‘Maruti’ and ‘Santro’. */

//This is an abstract class


abstract class Car
{
//Every car will have a registration number
int regno;

//Initialize the value of regno


Car(int r)
{
regno=r;
}

//All cars will have a fuel tank and same mechanism to


//open the tank
//
void openTank()
{
[Link]("Fill the tank");
}

//All the cars will have steering but differerent cars will
//have different steering mechanism.
abstract void steering(int direction, int angle);

//All cars will have brakes but different cars will have
//different braking mechanisms.
TEKZUNE TECHNOLOGIES 153

abstract void braking(int force);


}

//This is a concrete sub class, derived from 'Car' class


class Maruti extends Car
{
//Store regnoin super class var
Maruti(int regno)
{
super(regno);
[Link]("Registration no for Maruti = " + regno);
}

//Maruti uses ordinary steering


void steering(int direction,int angle)
{

[Link]("We are driving Maruti car");


[Link]("");
[Link]("Take a turn");
[Link]("This is ordinary steering");
}

//Maruti uses hydarulic brakes


void braking(int force)
{
[Link]("Brakes applied");
[Link]("These are hydraulic brakes");
}
}
//This is a concrete class derived from class car
class Santro extends Car
{
//Store regno at super class
Santro(int regno)
{
super(regno);
[Link]("Registration no for Santro = " + regno);
}
TEKZUNE TECHNOLOGIES 154

//Santro uses power steering


void steering(int direction,int angle)
{

[Link]("We are driving Santro car");


[Link]("");
[Link]("Take a turn");
[Link]("This car uses power steering");
}

//Santro uses gas breaks


void braking(int force)
{
[Link]("Brakes applied");
[Link]("This cars uses gas brakes");
}
}

//main method
class Usecar
{
public static void main(String args[])
{
//Create sub class objects
Maruti m=new Maruti(1001); //1001 is a regno
Santro s=new Santro(5005); // 5005 is a regno

//Create a reference to super class: Car


Car ref;

//To use santro


ref=s;

//Use features of te car


[Link]();
[Link](1,90);
[Link](500);
TEKZUNE TECHNOLOGIES 155

}
}

OUTPUT:

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>java Usecar
Registration no for Maruti = 1001
Registration no for Santro = 5005
Fill the tank
We are driving Santro car

Take a turn
This car uses power steering
Brakes applied
This cars uses gas brakes

/*82. Program to write abstract clas with an instance


variable: rate, a concrete method: getRate() and an
abstract method: calculateBill().
*/

//Calculating electricity bill for commercial and domestic plans

abstract class Plan


{
//Take rate as protected to access it in sub classes
protected double rate;

//Acept rate into rate variable. Since rate will change


//depending on plan, we declare abstract method
public abstract void getRate();
TEKZUNE TECHNOLOGIES 156

//calculate the electricity bill by taking units


public void calculateBill(int units)
{
[Link]("Bill amount for " + units + "units:");
[Link](rate*units);
}
}

class CommercialPlan extends Plan


{
//store commercial rate as Rs. 5.00 per unit

public void getRate()


{
rate=5.00;
}
}

class DomesticPlan extends Plan


{
//store domectic rate as Rs. 2.60 per unit
public void getRate()
{
rate=2.6;
}

//[Link]
class Calculate
{
public static void main(String args[])
{
//Create reference p to abstract class
Plan p;
TEKZUNE TECHNOLOGIES 157

//calculate commercial bill for 250 units


[Link]("Commercial Connection: ");
p=new CommercialPlan();//use referene to referto sub class obj
[Link]();
[Link](250);

//calculate domestic bill for 150 units


[Link]("Domestic Connection");
p=new DomesticPlan();//use reference to refer to sub class obj
[Link]();
[Link](150);
}
}
OUTPUT:

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>java Calculate
Commercial Connection:
Bill amount for 250units:
1250.0
Domestic Connection
Bill amount for 150units:
390.0

INTERFACES
Interfaces: An interface contains only abstract methods which
are all incomplete methods. So it is not possible to create an
object to an interface. In this case,we can create separate classes
where we can implement all the methods of the interface. These
classes are called implementation classes. Since, implementation
TEKZUNE TECHNOLOGIES 158

classes will have all the methods with body, it is possible to create
objects to the implementation of the abstract methods of the
interface.
The advantages of interfaces is that, we can implement the
methods without writing its body.
The best example for interfaces is the credit card, where the
methods like rupees, dollar, pound,frank are converted according
to the need of the user.

/*83. Example program on interfaces where interface


‘[Link]’ interface is being implemented in
implementation class ‘[Link]’ and we are creating
object for this class in ‘[Link]’ class*/

//[Link]
public interface creditcard
{
double dollars(double d);
double pounds(double p);
double rial(double r);
}

//[Link]
public class Bank implements creditcard
{
public double dollars(double d)
{
return (d*48.43);
}

public double pounds(double p)


{
return (p*73.82);
}

public double rial(double r)


{
return (r*14.0);
}
TEKZUNE TECHNOLOGIES 159

//[Link]
import [Link].*;
public class Conversion
{
public static void main(String[] args) throws IOException{

Bank r=new Bank();


Bank d=new Bank();
Bank p=new Bank();
int option;
double amount;
double n;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("Following are Currency Coversion
options");

[Link]("1. Dollars");
[Link]("2. Pounds");
[Link]("3. Rial");
[Link]();
[Link]("Please enter your choice ?: ");
option=[Link]([Link]());
[Link]("Please enter the amount: ");
n=[Link]([Link]());
switch(option)
{
case 1:
amount=[Link](n);
[Link]("The equivalent dollars amount in
rupees" + amount );
break;

case 2:
amount=[Link](n);
TEKZUNE TECHNOLOGIES 160

[Link]("The equivalent pounds amount in


rupees" + amount );
break;

case 3:
amount=[Link](n);
[Link]("The equivalent rial amount in
rupees" + amount );
break;

default:
[Link]("Invalid choice! Try between (1..3) ?");

}
}
}
OUTPUT:

E:\INTERFACES>javac [Link]

E:\INTERFACES>javac [Link]

E:\INTERFACES>javac [Link]

E:\INTERFACES>java Conversion
Following are Currency Coversion options
1. Dollars
2. Pounds
3. Rial

Please enter your choice ?:


2
Please enter the amount:
500
The equivalent pounds amount in rupees36910.0

/*84. Example program where class ‘Child’ is implementing


two interfaces such as ‘Father’ and ‘Mother’.*/
TEKZUNE TECHNOLOGIES 161

//Multiple inheritance using Interfaces


interface Father
{
float HT=6.2f;
void height();
}

interface Mother
{
float HT=5.8f;
void height();
}

//[Link]
class Child implements Father,Mother
{
public void height()
{
//Child got average height of its parents
float ht=([Link]+[Link])/2;
[Link]("Child's height=" + ht);
}
}

//[Link]
class Multi
{
public static void main(String args[])
{
Child ch=new Child();
[Link]();
}
}

OUTPUT

E:\>javac [Link]

E:\>javac [Link]
TEKZUNE TECHNOLOGIES 162

E:\>java Multi
Child's height=6.0

/*85. Another program on interfaces concept*/

//[Link]
interface MyInter
{
//All methods of an interface are by default public and abstract.
//So, we need not declare them explicity as public abstract.
void connect();
void disconnect();
}

//[Link]
class OracleDB implements MyInter
{
public void connect()
{
[Link]("Connecting to oracle database....");
}
public void disconnect ()
{
[Link]("Disconnecting from oracle:");
}}
//[Link]
class SybaseDB implements MyInter
{
public void connect()
{
[Link]("Connecting to Sybase...");
}

public void disconnect()


{
[Link]("Disconnected from Sybase.");
}
TEKZUNE TECHNOLOGIES 163

//[Link]
import [Link].*;

class InterfaceDemo
{
public static void main(String args[]) throws Exception
{
//Accept the implementation classname from commandline
arguments and store it in the object c.
Class c=[Link](args[0]);

//create an object to the class whose name is in c.


//Let the reference variable of interface point to it.
MyInter mi=(MyInter)[Link]();

//call methods of the object using mi.


[Link]();
[Link]();
}
}

OUTPUT

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>javac [Link]

E:\>java InterfaceDemo OracleDB


Connecting to oracle database....
Disconnecting from oracle:
TEKZUNE TECHNOLOGIES 164

E:\>java InterfaceDemo SybaseDB


Connecting to Sybase...
Disconnected from Sybase.

/*86. Example program where one interface is extended by


another interface.*/

/*One interface can inherit another by use of the keyword


extends. The syntax is the same as for inheriting classes. When a
class implements an interface that inherits another interface, it
must provide implementations for all methods defined within the
interface chain.*/

interface A
{
void m1();
void m2();
}

interface B extends A
{
void m3();
}

class MyClass implements B


{
public void m1()
{
[Link]("Implementing m1().");
}

public void m2()


{
[Link]("Implementing m2().");
}

public void m3()


{
[Link]("Implementing m3().");
TEKZUNE TECHNOLOGIES 165

}
}

class InterfaceExtended
{
public static void main(String args[])
{
MyClass obj=new MyClass();
obj.m1();
obj.m2();
obj.m3();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java InterfaceExtended
Implementing m1().
Implementing m2().
Implementing m3().

/*Another example program on Extended interface concept


*/
interface First
{
void max(int a,int b);
void min(int x,int y);
}

interface Second extends First


{
void square(int s);
}

class MyClass implements Second


{
public void max(int a,int b)
TEKZUNE TECHNOLOGIES 166

{
if(a>b)
{
[Link]("Max value is = " + a);
}

else
{
[Link]("Max value is = " + b);
}
}
public void min(int x,int y)
{
if(x<y)
{
[Link]("Min value is = " + x);
}

else
{
[Link]("Min value is = " + y);
}
}

public void square(int n)


{
[Link]("Square value = "+ (n*n));
}
}

class InterfaceExtended1
{
public static void main(String args[])
{
MyClass obj=new MyClass();
[Link](15,12);
[Link](19,5);
[Link](5);
TEKZUNE TECHNOLOGIES 167

}
}

E:\>javac [Link]

E:\ >java InterfaceExtended1


Max value is = 15
Min value is = 5
Square value = 25

/*87. An interface can be created within a class such an


interface is called ‘Nested Interface’. */

/*An interface can be declared a member of a class or another


interface. Sucn an interface iscalled a member interface or a
nested interface. A nested interface can be declared as public,
private or protected. This differs from a top-level interface, which
must eiher be declared as public or use the default acccess level.
When a nested interface is used outside of its enclising scope, it
must be qualified by the name of the class or interface is used
outside of its enclosing scope, it must be qualified by the name of
the class or interce of which it is a member. Thus, outside of the
class or interface in which a nested interface is declared, its name
must be fully qualified.*/

//[Link]
class Sample
{
//This is a nested interface
public interface NestedInter
{
void max(int x,int y);
}
}

class InterfaceDemo implements [Link]


{
public void max(int x,int y)
TEKZUNE TECHNOLOGIES 168

{
if(x>y)
{
[Link]("Largest value = " + x);
}
else
{
[Link]("Largest value = " + y);
}

}
}

class NestedInterFaces
{
public static void main(String args[])
{
[Link] nif=new InterfaceDemo();

[Link](10,20);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java NestedInterFaces
Largest value = 20

/*An interface can be declared as a member of another


interface. Such an interface is called a member interface
or a nested interface. */

//[Link]
public interface Sample1
{
void add(int a,int b);
//This is a nested interface
TEKZUNE TECHNOLOGIES 169

public interface NestedInter1


{
public void sub(int x,int y);
}
}

//[Link]
class InterfaceDemo1 implements Sample1.NestedInter1
{
public void add(int x,int y)
{
[Link]("Sum value = " + (x+y));
}

public void sub(int m,int n)


{
[Link]("Sub value = " + (m+n));
}
}

//[Link]
class NestedInterFaces1
{
public static void main(String args[])
{

InterfaceDemo1 obj=new InterfaceDemo1();


[Link](10,20);
[Link](7,3);
}
}
OUTPUT:
E:\>javac [Link]
E:\>javac [Link]
E:\>javac [Link]

E:\>java NestedInterFaces1
Sum value = 30
Sub value = 10
TEKZUNE TECHNOLOGIES 170
TEKZUNE TECHNOLOGIES 171

PACKAGES
Packages: A package represents a directory that contains
related group of classes and interfaces.
For example, when we write statements like:

import [Link].*;

In the above statement, we are importing all the classes and


interfaces of [Link] package.
Here, java is a directory and io is another sub directory within it.
And the '*' represents all the classes and interfaces of that io sub
directory.

Advantages of packages are:

1) Packages are useful to arrange related classes and intefaces


into a [Link] makes all the classes and interfaces performing
the same task to put together in the same package.
For example, for input and output operations we are using
[Link] package.

2) Packages hide the classes and intefaces in a separate sub


directory, so that accidental deletion of classes and interfaces will
not take place.

3) The classes and interfaces of one package are isolated from


the classes and intefaces of another package. This means we can
give same name for two classes in different packages.

4) A group of packages is called library. The classes and


interfaces of a package are like books in a library and can be
reused several times.

Different types of Packages:

1) Built-in packages: These are the packages which are already


available in Java programming. These packages provide all most
all necessary classes, interfaces and methods for the programmer
to perform any task in his programs.
TEKZUNE TECHNOLOGIES 172

Some of the important packages of Java SE are:


--> [Link]: It is stands for the language. It provides all most all
necessary classes, interfaces and methods for the programmer to
perform any task in his programs.

--> [Link]:Stands for utility. It is used for handling date and time
like operations
--> [Link]: Stands for Input Output which is necessary for input
and output operations
2) User-Defined Packages: The users of Java language can also
create their own packages. They are called user-defined
packages. The user-defined packages can also be imported into
other classes and used exactly in the same way as the Built-in
packages.

To create a package keyword 'package' is used as:


package package-name;
ex: package pack;

We can create sub packages within main package. Like below:


package [Link]-name;

import [Link];

Here 'pack' is the name of the package and 'Addition' is the sub
package name.

To compile package program we use the following command:

javac -d . [Link]

In the above command -d option tells the compiler to create a


separate sub directory and place the .class file there. The dot (.)
after -d indicates that the package should be created in the
current directory.

Access-Specifiers in Java
-------------------------------
TEKZUNE TECHNOLOGIES 173

An access specifier is a key word that is used to specify how to


access a member of a class or the class itself. It means, we can
use access specifier with the members of a class or with the class
also. Thre are four access specifiers in Java: private, public,
protected and default. We do not use 'default' key word for
specifying the default access specifier. If no other access specifier
is used, then Java compiler will take it as default access specifier.

Let's take three classes that is FIRST,SECOND and THIRD, where


as class FIRST and SECOND exists in the same package (SAME)
and class THIRD exists in the package (ANOTHER) as shown
below:

package SAME;
public FIRST
{
private int a=1;
public int b=2;
protected int c=3;
int d=4; //default
}

package SAME;
import [Link];
public class SECOND
{
public static void main(String args[])
{
FIRST obj=new FIRST();
[Link](obj.a);
[Link](obj.b);
[Link](obj.c);
[Link](obj.d);
}
}

package ANOTHER;
import [Link];
TEKZUNE TECHNOLOGIES 174

public class THIRD


{
public static void main(String args[])
{
FIRST obj=new FIRST();
[Link](obj.a);
[Link](obj.b);
[Link](obj.c);
[Link](obj.d);
}
}

//Creating sub class 'THIRD' from class 'FIRST'


package ANOTHER;
import [Link];
public class THIRD extends FIRST
{
public static void main(String args[])
{
FIRST obj=new FIRST();
[Link](obj.a);
[Link](obj.b);
[Link](obj.c);
[Link](obj.d);
}
}

Some important points about above classes


-----------------------------------------------------
->private members of class FIRST are not available to class
SECOND or class THIRD in any case. This means , any private
member's scope is limited only to that class where it is defined.
So the scope of private access specifier is class scope.

->public members of class FIRST are available to class SECOND


and also to class THIRD. This means, public members are
available every where and their scope is global.
TEKZUNE TECHNOLOGIES 175

->protected members of class FIRST are available to class


SECOND, but not in class THIRD. But if, class THIRD is a sub class
of FIRST class then protected members of class FIRST are
available to class THIRD. So, protected access specifier acts as
public with respect to sub classes.

->When no access specifier is used, it is taken as default


specifier. Default members of class FIRST are accessible to class
SECOND which is within the same package. They are not available
to class THIRD. This means, the scope of default members is
package scope.

/*88. Program for Creating a package with Addition class*/


package Arithmetic; //Arithmetic is the packagename
public class Addition
{
//Instance variables
private double d1,d2;

public Addition(double a,double b)


{
d1=a;
d2=b;
}

//Method to find sum of two numbers


public void sum()
{
[Link]("Sum=" +(d1+d2));
} }
//Compile the above program with the following command

E:\>javac -d . [Link]

//Adding another class to the package : Arithmetic


package Arithmetic;
public class Subtraction
{
TEKZUNE TECHNOLOGIES 176

//A static method to return result of subtraction


public static double sub(double a,double b)
{
return(a-b);
}
}
E:\>javac -d . [Link]

import Arithmetic.*;
import [Link];
import [Link];
public class Use2{
public static void main(String args[])
{

//Creates Addition class object


Addition obj=new Addition(15,15.5);

//call the sum() method


[Link]();

//call the sub() method and pass values


double res=[Link](15,13.5);
[Link]("Result of Subtraction=" + res);
}
} OUTPUT :

Javac [Link]
Java Use2

/*89. Program for creating an ‘INTERFACE’ in a package */

/*Interfaces In Package
---------------------
It is also possible to write interfaces in a package. But whenever,
we create an interface the implementation classes are also should
be created. We cannot create an object to the interface but we
can create objects or implementation classes and use them.*/
TEKZUNE TECHNOLOGIES 177

//Create MyDate interface in package mypack


package mypack;
public interface MyDate
{
void showDate();
}

Javac –d . [Link]

/*Write a program to create an implementation class or the


MyDate interface with the name DateImpl and storing it in the
same package mypack.*/

package mypack;
import [Link];
import [Link].*;

public class DateImpl implements MyDate


{
public void showDate()
{
Date d=new Date();
[Link](d);
}
}

Javac –d . [Link]

/*Write a program which shows how to use the DateImpl which is


an implementation class of MyDate interface.*/

import [Link];

class DateDisplay
{
public static void main(String args[])
{
DateImpl obj=new DateImpl();
[Link]();
TEKZUNE TECHNOLOGIES 178

}
}

OUTPUT:
Javac [Link]
Java DateDisplay

/*90. Program for creating a sub package within a


package*/

//Creating a sub package 'Courses' in the package 'Orbit'.


package [Link];
public class Sample
{
public void show()
{
[Link]("Welcome to Orbit Technology");
}
}

Javac –d . [Link]

/*Make a program using Sample class of [Link] package*/

import [Link];

class Use
{
public static void main(String args[])
{
Sample s=new Sample();
[Link]();
}
}
TEKZUNE TECHNOLOGIES 179

OUTPUT:
Javac [Link]
Java Use

Java Archive(JAR) file:


A jar file is a file that contains compressed version of (.class) files,
audio files, image iles or directories. We can imagine a .jar file as
a zipped ile(.zip) that is crated by using WinZip software. Even,
WinZip software can be used to extract the contents o a .jar file.
The difference is that a .jar file can be used as it is but where as
the .zip file can not be used directly. The should be extracted first
rom a .zi file and then used.

To create .jar file, JavaSoft people have provided jar command,


which can be used in the following way:

jar cf jarfilename inputfiles


In the above code 'cf' represents create file. For example,
assuming our package 'pack' is available in C:\ directory, to
convert it into a jar file with the name [Link], we can give the
command as:

C:\jar cf [Link] Arithmetic

To view the contents of a .jar file, we can use the jar command as:
jar tf jarfilename
Here, itf represents table view o file contents. For example, to
view the contents of our [Link] file, we can give the command:

jar tf [Link]

-->To extract the files from a .jar file. For example, to extract the
contents of our [Link], we can write

-->c\jar xf jarfilename
Here, xf represents extract files from the jar file.
Example: c:\jar xf [Link]
TEKZUNE TECHNOLOGIES 180

Creating and Executing Jar file:

In order to create and execute jar file, make a directory(folder)


having sub folders such as classes(.class file) and source(.java
files).

We start by saving our source code (.java files) into the source
directory. Then the trick is to compile your code is such a way
that the output (the .class files) ends up in the classes directory.

E:\cd Orbit/source

javac -d ../classes *.java

By using the -d flag, you get to decode which directory the


compiled code lands in, rather than acepting he default of class
files landing in he same directory as the source code.

Making an executable JAR


-------------------------------
1. Make sure all of your class files are in the classes directory

2. Create a [Link] file that states which class has the


main() method and this file must include line

Main-Class: Conversion
Press the enter key after typing the Main Clas line, or your
manifest may not work correctly. Put the manifest file into the
"classes" folder.

3. Run the jar tool to create a JAR file hat contains everything in
the classes directory, plus the manifest.

cd Orbit/classes
jar -cvmf [Link] [Link] [Link]
TEKZUNE TECHNOLOGIES 181

4. Running (executing) the JAR


java -jar [Link]

/*91. Program for creating ‘Executable Jar File’ */

/*Save this file in CreditCard\Source package(folder) and make


sure that all *.class files should land up in classes folder */
public interface creditcard {
double dollars(double d);
double pounds(double p);
double rial(double r);
}

Javac [Link]

public class Bank implements creditcard{

public double dollars(double d)


{
return (d*48.43);
}

public double pounds(double d)


{
return (d*73.82);
}

public double rial(double r)


{
return (r*14.0);
}
}
Javac [Link]

import [Link].*;
TEKZUNE TECHNOLOGIES 182

public class Conversion


{
public static void main(String[] args) throws IOException{

Bank r=new Bank();


Bank d=new Bank();
Bank p=new Bank();
int option;
double amount;
double n;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
[Link]("Following are Currency Coversion
options");

[Link]("1. Dollars");
[Link]("2. Pounds");
[Link]("3. Rial");
[Link]();
[Link]("Please enter your choice ?: ");
option=[Link]([Link]());
[Link]("Please enter the amount: ");
n=[Link]([Link]());
switch(option)
{
case 1:
amount=[Link](n);
[Link]("The equivalent dollars amount in rupees" +
amount );
break;

case 2:
amount=[Link](n);
[Link]("The equivalent pounds amount in rupees" +
amount );
break;

case 3:
amount=[Link](n);
TEKZUNE TECHNOLOGIES 183

[Link]("The equivalent rial amount in rupees " +


amount );
break;

default:
[Link]("Invalid choice! Try between (1..3) ?");

}
}
}
OUTPUT:

Javac [Link]
Java Conversion

Create [Link] file and put that file in the classes folder
which represents the main class file with the following code.

Main-Class: Conversion

API DOCUMENT
Application Programming Interface (API) document is a
hypertext markup language (html) file that contains description of
all the features of a software, a product or a technology. API
document is like a reference manual that is useful to all the users
o the product to understand all the features and how to use them.

For example:
JavaSoft people have created API document separately for the
three parts, Java SE, Java EE and Java ME after they created java
language.

-->Every feature of Java language is described in API document.


We can select any package, any class in that package and the
description of the calss along with the fields, contructors,
methods will appear. When we click on any of these features, a
detailed description of the feature is displayed.
TEKZUNE TECHNOLOGIES 184

There are three important uses of API document:


1. API document is useful or the user to understand all the
features of the product. The user can understand how to create
an object to a class, which fields and methods are available in the
class and how to use them.

2. API document makes programming easy. By understanding the


methods of the API, the programmer will be able touse those
methods and contruct his programs easily.

3. Any third party vendor can provide implementation classes


for the interfaces depending on the information available on
the interfaces in the API.

/*92. Write a program for creating documentation file for


‘[Link]’ program*/

//Creating a package with Addition class

/** This package is useful to perform some arithmetic


calculations. It has two classes by the name Addition and
Subtraction*/

package pack; //pack is the packagename


/** This class is useful to find sum o two numbers. It has a
parameterized constructor and a method to find sum */

public class Addition


{
//Instance variables
private double d1,d2;
/** This is a parameterized constructor to initialize the instance
variables of the class*/
public Addition(double a,double b)
{
TEKZUNE TECHNOLOGIES 185

d1=a;
d2=b;
}
/** This method is useful to find sum of two numbers. It does not
accept any parameters.
<br>Parameters: nil
<br>Return type: void
<br>Exceptions: nil
*/
//Method to find sum of two numbers
public void sum()
{
[Link]("Sum=" +(d1+d2));
}
}
//COMPILE AS
javadoc [Link]
//Adding another class to the package : pack

/** This package is useful to perform some arithmetic


calculations. It has two classes by the name Addition and
Subtraction*/

package pack;

/** This class is useful to find subtraction of two numbers. */


public class Subtraction
{

/** This method is useful to subtract a number from another and


return the result
<br>Parameters: double x,double y
<br>Return type: double
<br>Exceptions: nil
*/
//A static method to return result of subtraction
public static double sub(double a,double b)
{
return(a-b);
TEKZUNE TECHNOLOGIES 186

}
}
//COMPILE AS
javadoc [Link]

import pack.*;
import [Link];
import [Link];
public class Use2{
public static void main(String args[])
{

//Creates Addition class object


Addition obj=new Addition(15,15.5);

//call the sum() method


[Link]();

//call the sub() method and pass values


double res=[Link](15,13.5);
[Link]("Result of Subtraction=" + res);
}
}

javac [Link]
java Use2

/*93. Another example program for creating a package.*/

//[Link]
package college;
import [Link].*;
public class Teacher
{
private int idno;
private String name;
BufferedReader br= new BufferedReader(new
InputStreamReader([Link]));
TEKZUNE TECHNOLOGIES 187

public void read() throws IOException


{
[Link]("Enter idno,name");
idno=[Link]([Link]());
name=[Link]();
}
public void display()
{
[Link]("idno"+idno);
[Link]("Name"+name);
}
}

javac –d . [Link]

//[Link]
package college;
import [Link].*;
public class Student
{
private int rno;
private String name,course;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
public void read() throws IOException
{
[Link]("[Link],name,course,");
rno=[Link]([Link]());
name=[Link]();
course=[Link]();
}
public void display()
{
[Link]("Rno"+rno);
[Link]("Name"+name);
[Link]("Course"+course);
}
}
TEKZUNE TECHNOLOGIES 188

javac –d . [Link]

//[Link]
package [Link];
import [Link].*;
public class SportsBlock
{
private float percent;
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
public void read() throws IOException
{
[Link]("Enter the Sports Quota percentage :");
percent=[Link]([Link]());
}
public void display()
{
[Link]("Percentage is "+percent);
}
}

//[Link]
import [Link];
import [Link].*;
class TeacherDemo
{
public static void main(String args[]) throws IOException
{
Teacher t=new Teacher();
[Link]();
[Link]();
}
}
javac [Link]
java TeacherDemo

//[Link]
import [Link];
import [Link].*;
TEKZUNE TECHNOLOGIES 189

class StudentDemo
{
public static void main(String args[]) throws IOException
{
Student s=new Student();
[Link]();
[Link]();
}
}
javac [Link]
java StudentDemo

//[Link]
import [Link];
import [Link].*;
class SubPackDemo
{
public static void main(String args[]) throws IOException
{
SportsBlock sb = new SportsBlock();
[Link]();
[Link]();
}
}

javac [Link]
java SubPackDemo
TEKZUNE TECHNOLOGIES 190

Exceptional Handling

Programs generate run-time exception that halts (terminates) the


programs.
so when ever a run time error occurs then the programs exists
specifying the exception that has occured in the program to make
a program run even in a case where in run time exceptions occurs
we must use exceptional handling mechanism java provides
exceptional handling mechanism with the use of try/catch block

Examples of run time exceptions are :


1) division by zero
2)trying to access an array value beyond its size
3)trying to access a file that is not existent, etc

So when exceptions occurs they need to be caught so that the


program excution does not stop.
java provides 5 keywords using which exceptions can be handled.
They are

try , catch , finally , throw , throws.

try: The code which might throw an exception needs to included


in the try block when ever an exception occurs try bock will throw
an exception which needs to be caught by any of the catch
blocks.
eg:
try{int i=10/0;
}
catch :
Each try block should have atleast one catch block which will be
responsible for catching the thrown exception.
eg:
try{
//code here
}
catch(Exceptionclass ee){
//code here
}
TEKZUNE TECHNOLOGIES 191

package name is
[Link]
Exception class is the super class of all the exception classes. all
the exception classes inherit or are sublcass to the 'Exception'
class subclasses are
ArithmeticException,ArrayIndexOutOfBoundsException
FileNotFoundException,IOException ,SQLException etc....

finally
this block will be executed compulsorily even if an exception
occurs or not.
normally it is used to include code which is to be executed
compulsorily.
syntax :
try{
//code here
}
catch(){
//code here
}
finally{
//code here ....
}

throws key word


A method which donot handle an exception using try/catch will
use 'throws' keyword to throw an exeption when occured.
syntax
public void add () throws ArithmeticException{
int i =10/j;
}
So when a method do-not handle try/catch block to catch an
exception then it uses 'throws' key word.

throw:
run time exceptions are thrown by JVM but 'throw'
is used to throw an exception explicitly.
throw format :
TEKZUNE TECHNOLOGIES 192

throw new ArithmeticException();

format of try catch block


When an exception occurs in a try block the control comes out of
the try block and will search for the catch block(appropriate catch
block) and when it is found will execute the code present in it.
catch(Exception2 ee){
/// code here
}
finally{
//code here...
}
what happens in the try/catch block
when ever an exception occurs in an try block then the try block
will throw the appropriate exception so the control comes out of
the try block and searches for the apprpraite catch block if it finds
an apppraite exception class then it wil execute the code present
in the catch block.

Using the super class 'Exception' to catch an exception


Multiple catch blocks can be defined after an try block so when an
exception occurs so JVM will search for the appropriate exception
catch block and then exceute it.
Exception class is the super class of all the Exceptions. So if a
catch block with Exception class is defined then it will catch all
the exceptions that are generated try block.
eg:
catch(Exception ee){

}
toString() method
Exception class contains toString() method that returns the type
of exception that has occured in the try block

printStackTrace() Method
When ever an exception occurs then all the errors associated with
it like type of Exception ,
TEKZUNE TECHNOLOGIES 193

line that generated exception , system defined class used in the


class is stored in a stack which will be displayed when this
mehtod is used.

multiple try/catch blocks


a program can contian more than one try catch in it each try
block should have it own catch block or else the program will not
compile

finally block
this block is placed at the end of a try catch block
this block is executed whether or not an exception has occured
the code that needs to be compulsorily executed is written in this
block.
multiple try/catch block
try{
}
catch (){
}
try{
}
catch(){
}

nested try catch block:


try{
try{

}
catch(){
}
}
catch()
{
}
/*94. Program to check, what happens when an exception
is taking place in a program. */

class Exp
TEKZUNE TECHNOLOGIES 194

{
public static void main(String args[])
{
//Open the files
[Link]("Open files");

//Do some processing


int n=[Link];
[Link]("n=" +n);
int a=45/n;
[Link]("a=" + a);

//Close the files


[Link]("Close the files");
}
}

OUTPUT
E:\>javac [Link]

E:\>java Exp 3 5 6
Open files
n=3
a=15
Close the files

E:\>java Exp
Open files
n=0
Exception in thread "main" [Link]: / by
zero
at [Link]([Link])

/*95. Program to check, what happens when we include


‘try’ ,’catch’ and ‘finally’ keywords in the program */
//Exception handling using try, catch and finally blocks

class Exp1
TEKZUNE TECHNOLOGIES 195

{
public static void main(String args[])
{
try
{
//Open the files
[Link]("Open files");

//Do some processing


int n=[Link];
[Link]("n=" +n);
int a=45/n;
[Link]("a=" + a);
}

catch(ArithmeticException ae)
{
//Display the excetion details
[Link](ae);

//Display any message to the user


[Link]("Please pass data while running this
program");
}

finally
{
//Close the files
[Link]("Close files");
}

}
}

OUTPUT
E:\>javac [Link]

E:\>java Exp1 2 3
Open files
TEKZUNE TECHNOLOGIES 196

n=2
a=22
Close the files
Close files

E:\>javac [Link]

E:\>java Exp1
Open files
n=0
[Link]: / by zero
Please pass data while running this program
Close files

/*96. Write a program where a single ‘try’ block has more


than one ‘catc’ block*/

import [Link].*;
import [Link].*;
class Exp2
{
public static void main(String args[])
{

try
{
//Open the files
[Link]("Open files");

//Do some processing


int n=[Link];
[Link]("n=" +n);
int a=45/n;
[Link]("a=" + a);

int b[]={10,20,30};
b[50]=100;
//Close the files
TEKZUNE TECHNOLOGIES 197

[Link]("Close the files");


}
catch(ArithmeticException ae)
{

//Display exception details


[Link](ae);

//Display any message to the user


[Link]("Please pass data while running this
program");
}
catch(ArrayIndexOutOfBoundsException aie)
{
//Display exception details
[Link]();

//Display a message to user


[Link]("Please see that the array index is
within the range");
}
finally
{
//close the files
[Link]("Close files");
}

}
}

OUTPUT

E:\>javac [Link]
E:\>java Exp2
Open files
n=0
[Link]: / by zero
Please pass data while running this program
TEKZUNE TECHNOLOGIES 198

Close files

E:\>java Exp2 11 22
Open files
n=2
a=22
[Link]: 50
at [Link]([Link])
Please see that the array index is within the range
Close files

/*97. Write a program where user is not handling the


exception nor throwing the exception*/

//Not handling the exception


import [Link].*;

class Sample
{
//Instance variable
private String name;

//Method to accept name


void accept()
{
//To accept data from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter name");
name=[Link]();
}

//Method to display name


void display()
{
[Link]("Name" + name);
}
TEKZUNE TECHNOLOGIES 199

class Exp3
{
public static void main(String args[])
{
Sample s=new Sample();
[Link]();
[Link]();
}
}

OUTPUT
E:\>javac [Link]
[Link]: unreported exception [Link]; must be
caught or declar
ed to be thrown
name=[Link]();
^
1 error

/*98. Write a program where user doesn’t want to handle


the exception but wants to throw an exception out of the
program. */
import [Link].*;

class Sample1
{
//Instance variable
private String name;

//Method to accept name


void accept() throws IOException
{
//To accept data from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter name");
TEKZUNE TECHNOLOGIES 200

name=[Link]();
}

//Method to display name


void display()
{
[Link]("Name" + name);
}

class Exp4
{
public static void main(String args[]) throws IOException
{
Sample1 s=new Sample1();
[Link]();
[Link]();
}
}

OUTPUT

E:\>javac [Link]

E:\>java Exp4
Enter name Sami
Name Sami

/*99. Program to calculate Intrest on money and to display


use of Exception Class */

public class Account


{
public static void main(String aa[])
{
int amount =1000;
int intrest;
int totalamount;
TEKZUNE TECHNOLOGIES 201

[Link]("Calculating Intrest for the amounts : ");

try
{
for(int month=5;month>=0;month--)
{
intrest = amount/month;
totalamount =amount+ intrest;
[Link]("Total Amount is : "+totalamount );
}
}
catch(Exception ee)
{
[Link]();
//[Link]("Error in calculating Intrest : "+
[Link]());
}
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Account
Calculating Intrest for the amounts :
Total Amount is : 1200
Total Amount is : 1250
Total Amount is : 1333
Total Amount is : 1500
Total Amount is : 2000
[Link]: / by zero
at [Link]([Link])

/*100. Write a program on ‘finally’ block example */


public class Bank
{
int totalbal [] = new int[4];
int profit =0;
int accbal;
TEKZUNE TECHNOLOGIES 202

String cust_name;
public Bank(String name ,int acc_bal)
{
[Link]= acc_bal;
this.cust_name = name;
}

public void accbal ( )


{
totalbal[0]=2000;
try
{
for(int i =0;i<=2;i++)
{
profit = accbal / (i+1);
totalbal[i] = accbal + profit;
}
}
catch(ArithmeticException ee )
{
[Link]("Exception occured ..... " + [Link]());
}

try
{
[Link]("New Account balance is : ");
for(int i=0;i<=5;i++)
{
[Link]("balance is : " + totalbal[i]);
}
}
catch(ArrayIndexOutOfBoundsException ee)
{
[Link]("Exception occured "+ [Link]());
}
finally
{
[Link](cust_name +" Account information
successfully updated ... ");
TEKZUNE TECHNOLOGIES 203

}
}
public static void main(String args[])
{
Bank bankobj = new Bank("kumar", 1000);
[Link]("Calling acc bal for Kumar");
[Link]();
Bank bankobj1 = new Bank("Abed",2000);
[Link]("Calling acc bal for Abed");
[Link]();
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Bank
Calling acc bal for Kumar
New Account balance is :
balance is : 2000
balance is : 1500
balance is : 1333
balance is : 0
Exception occured [Link]: 4
kumar Account information successfully updated ...
Calling acc bal for Abed
New Account balance is :
balance is : 4000
balance is : 3000
balance is : 2666
balance is : 0
Exception occured [Link]: 4
Abed Account information successfully updated ...

/*101. Program Using ‘throw’ keyword */

class Sample2
{
static void demo()
TEKZUNE TECHNOLOGIES 204

{
try {
[Link]("Inside demo()");
throw new NullPointerException("Exception data");
}
catch(NullPointerException ne)
{
[Link](ne);
}
}
}

class ThrowDemo
{
public static void main(String args[])
{
[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java ThrowDemo
Inside demo()
[Link]: Exception data

/*102. Program for developing User defined exception


to throw whenever balance amount is below Rs. 1000 */
class MyException extends Exception
{
//Store account information
private static int accno[]={1001,1002,1003,1004,1005};
TEKZUNE TECHNOLOGIES 205

private static String name[]={"Syed Hashim","Mohammad


Hafeez","Abdul Kareem","Mirza Sami","Abu Baker"};

private static double


bal[]={10000.00,1200.00,5600.50,3000.50,999.00};

//default constructor
MyException()
{
}

//parameterized constructor
MyException(String str)
{
super(str);
}

//write main()
public static void main(String args[])
{
try{
//Display the heading for the table
[Link]("ACCNO" + "\t" + "CUSTOER" + "\t" +
"BALANCE");

//Display actual account information


for(int i=0;i<5;i++)
{
[Link](accno[i]+ "\t" + name [i]+ "\t" + bal[i]);

//Display own exception if balance < 1000


if(bal[i]<1000)
{
MyException me =new MyException("Balance amount is
lessthan 1000");
throw me;
}

} //End of for
TEKZUNE TECHNOLOGIES 206

} //End of try

catch(MyException me) {
[Link]();
}
} //End of main
} //End of MyException class

OUTPUT
E:\>javac [Link]

E:\>java MyException
ACCNO CUSTOER BALANCE
1001 Syed Hashim 10000.0
1002 Mohammad Hafeez 1200.0
1003 Abdul Kareem 5600.5
1004 Mirza Sami 3000.5
1005 Abu Baker 999.0
MyException: Balance amount is lessthan 1000
at [Link]([Link])

/*103. Program to display use of multiple and nested


try/catch blocks*/
public class Multipletry
{
public static void main(String aa[])
{

try
{
[Link]("In First Try Block");
int i =12/0;
}
catch(ArithmeticException ee)
{
[Link]("In First catch Block");
}

try
TEKZUNE TECHNOLOGIES 207

{
[Link]("In second try Block");
try
{
int a[] = new int[3];
[Link]("In inner Try Block");
a[4]= 20;
[Link]("Error before this line ");
}
catch(ArrayIndexOutOfBoundsException ee)
{
[Link]("In inner catch Block");
}
}

catch(ArrayIndexOutOfBoundsException ee)
{
[Link]("Array Out of Bunds ");
}
catch(ArithmeticException ee)
{
[Link]("In First catch Block");
}
catch(Exception ee)
{
[Link]("In second catch Block");
}

} //Main

} //class

OUTPUT:

E:\>javac [Link]

E:\>java Multipletry
In First Try Block
TEKZUNE TECHNOLOGIES 208

In First catch Block


In second try Block
In inner Try Block
In inner catch Block

/*104. Program to demonstarte user defined exception */

//[Link]
public class maxamountException extends Exception
{
maxamountException(String cust_name, int amount)
{
super(cust_name+" is withdrawing Money exceeded ... the
limits of 200 and the withdrawn amt is : "+ amount );
}
}

//[Link]
class user
{
public static void main(String a[])
{
user use = new user();
try
{
[Link]("kumar",20);
[Link]("Ashraf",400);
}
catch(Exception ee )
{
[Link]("Error "+ ee);
}
}

public void withDraw(String customer_name,int amount) throws


maxamountException
{
TEKZUNE TECHNOLOGIES 209

if(amount>200)
{
throw new maxamountException (customer_name,amount);
}
else
{
[Link](customer_name+" has specified amount
with in limits.. withdrawn amount is : "+ amount );
}
}
}
OUTPUT

E:\>javac [Link]
E:\>javac [Link]

E:\Exception>java user
kumar has specified amount with in limits.. withdrawn amount
is : 20
Error maxamountException: Ashraf is withdrawing Money
exceeded ... the limits
of 200 and the withdrawn amt is : 400

/*105. Another example program on ‘throw’ keyword */


import [Link].*;
class ExcepHandling
{
public static int quotient(int n1,int n2)
{
if(n2==0)
throw new ArithmeticException("Divisor cannot be zero");
return n1/n2;
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
TEKZUNE TECHNOLOGIES 210

[Link]("Enter any two numbers");


int n1=[Link]([Link]());
int n2=[Link]([Link]());

try
{
int result=quotient(n1,n2);
[Link](n1 + "/" + n2 + " is " + result);
}catch(ArithmeticException ex)
{
[Link]("Exception: an integer " + "cannot be
divided by zero");
}
[Link]("Execution continues.....");
}
}
OUTPUT:
E:\>javac [Link]

E:\>java ExcepHandling
Enter any two numbers
10
3
10/3 is 3
Execution continues.....

E:\>java ExcepHandling
Enter any two numbers
10
0
Exception: an integer cannot be divided by zero
Execution continues.....
TEKZUNE TECHNOLOGIES 211

WRAPPER CLASSES
Since OOPS is all about objects it is necessary to convert every
thing into objects. Wrapper classes are useful to convert primitive
data types into objects. Moreover, they contain methods to
reconvert an object into primitive data. The methods of a wrapper
class facilitate a programmer to work with objects easily and
effectively.

Wrapper Classes: A wrapper class contains a field where it stores


the primitive datatype. When we create an object to a wrapper
class, it carries the primitive data type within it and hence the
object can be sent to the server. The server can retrieve the
primitive data type from the object and use it.

->A wrapper class is a class whose object wraps or contains a


primitive data type. When we create an object to a wrapper class,
it contains a primitive data type. When we create an object to a
wrapper class, it contains a field and in this field, we can store a
primitive data type. In other words, we can wrap a primitive value
into a wrapper class object.

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


contains a single field char and it is possible to store a character
like A there. So Character is a wrapper class of char data type.

->There is another reason why we need wrapper classes. In Java,


collection classes are defined in [Link] package which hangle
only objects, not the primitives. Hence, if we want to use
collection classes on primitives, we should convert them into
objects. Here, also we need the help of wrapper classes.

List of Wrapper Classes:


TEKZUNE TECHNOLOGIES 212

------------------------------

-------------------------------------------------------------------
Primitive Data type | Corresponding Wrapper class
---------------------------|---------------------------------------------
1. char | Character
---------------------------|---------------------------------------------
2. byte | Byte
---------------------------|---------------------------------------------
3. short | Short
---------------------------|---------------------------------------------
4. int | Integer
---------------------------|---------------------------------------------
5. long | Long
---------------------------|---------------------------------------------
6. float | Float
---------------------------|---------------------------------------------
7. double | Double
---------------------------|---------------------------------------------
8. boolean | Boolean
-------------------------------------------------------------------------

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

Number class Methods:

[]byte byteValue(): This method converts the calling object into


byte value. The calling object can be an object of Byte,
Short ,Integer, Long, Float, or Double class.

[]short shortValue(): This method converts the calling object into


short value.

[]int intValue() : This method converts the calling object into int
value.
TEKZUNE TECHNOLOGIES 213

[]long longValue() : This method converts the calling object into


long value.

[]float floatValue(): This method converts the calling object into


loat value.

[]double doubleValue(): This method converts the calling object


into double value.

Note: All these methods are available to Byte, Short, Integer,


Long, Float and Double classes.

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

Important Methods of Character class are:


[]char charValue():This method is useful to convert Character
class object again into primitive char value and returns that value.
For example, we can use it as:
Character obj=new Character('A');
char ch=[Link]();
Now, ch contains 'A'

[]int compareTo(Character obj): This method is useful to compare


two Character objects. It is called as:
int x=[Link](obj2);
where obj1 and obj2 are Character class objects
If obj1==obj2, then this method returns 0.

[]String toString(): This method converts Character object into


String object and returns that String object.
TEKZUNE TECHNOLOGIES 214

[]static Character valueOf(char ch): This method converts a single


character ch into Character object and returns that object.

[]static boolean isDigit(char ch): THis method returns true if ch is


a digit (0 to 9) other wise returns false.

[]static boolean isLetter(char ch): This method returns true if ch is


a letter (A to Z or a to z).

[]static boolean isUpperCase(char ch): This method returns true if


ch is an uppercase letter(A to Z).

[]static boolean isLowerCase(char ch): This method returns true if


ch is an lowercase letter(a to z).

[]static boolean isSpaceChar(char ch): THis method returns true if


ch represents a space which is coming from spacebar.

[]static boolean isWhitespace(char ch): This method returns true if


ch represents white space. White space is a space that comes on
pressing tab, enter, or backspace buttons.

[]static boolean isLetterOrDigit(char ch): This method returns ture


if ch is either a letter or digit.

[]static char toUpperCase(char ch): This method converts ch into


uppercase and returns that upper case letter.

[]static char toLowerCase(char ch): This method converts ch into


lowercase and returns that lower case letter.

Integer Class

The Integer class wraps a value of the primitive type 'int' in an


object. The Integer class object contains an 'int' type field. In this
field, we can store a primitive 'int' number.
TEKZUNE TECHNOLOGIES 215

Constructors
Integer class hws two constructors. The first one takes 'int'
number as its parameter and converts it into Integer class object
and the next one takes a String type parameter and converts that
string into Integer class object.

[]Integer(int num): This means Integer object can be created as:

Integer obj=new Integer(123000);


Here we are converting a primitive 'int' value into Integer object
which is called as 'Boxing'.

[]Integer9String str): This constructor sugests that we can create


an Integer object by converting a string that cntains an 'int'
number as
Integer obj=new Integer("198663");

Important Methods of Integer class


[]int compareTo(Integer obj): This method compares the
numerical value of two Integer class objects and returns
0,negative or positive value.

[]boolean equals(Objects obj): This method cmpares the Integer


object with any other object obj. If both have the same content,
thenit returns true otherwise false.

[]static int parseInt(String str): This method returns 'int'


equivalent of the string str.

[]String toString(): This method returns a string formof the Integer


object.

[]static Integer valueOf(String str): This method converts a string


str that contains some int number into Integer class object and
returns that object.

[]static String toBinaryString(int i): This method converts decimal


integer number i into binary number system and returns that
binary number as a string.
TEKZUNE TECHNOLOGIES 216

[]static String toHexString(int i): This method converts decimal


integer number i into hexadecimal number system and returns
that hexadecimal number as a string.

[]static String toOctalString(int i): This method converts decimal


integer number i into octal number system and returns that octal
number as a string.

[]int intValue(): This method converts Integer object into primitive


int type value. This is called 'unboxing'.

/*106. Write a program to accept an integer number from


keyboard and convert it into other number systems
format.
*/

import [Link].*;

class Convert
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter any integer value");


String str=[Link]();

//convert string value into int value


int i=[Link](str);
[Link]("In decimal form : " + i);

//convert string value into Binary format


str=[Link](i);
[Link]("In Binary form : " + str);
TEKZUNE TECHNOLOGIES 217

//convert string value into Hexadecimal format


str=[Link](i);
[Link]("In hexadecimal form : " + str);

//convert string value into Octal format


str=[Link](i);
[Link]("In Octal form : " + str);

}
}

OUTPUT:

E:\>javac [Link]

E:\>java Convert
Enter any integer value
15
In decimal form : 15
In Binary form : 1111
In hexadecimal form : f
In Octal form : 17

/*107. Write a program that accepts the character from


the keyboard and displayes its type. This program
executes till the user presses the Enter button.*/

import [Link].*;

class CharTest
{
public static void main(String args[]) throws IOException
{
char ch;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

while(true)
{
TEKZUNE TECHNOLOGIES 218

[Link]("Enter a character: ");


ch=(char)[Link]();

//test and display the type of character


[Link]("You Entered: ");

if([Link](ch))
[Link]("You press a digit");

else if([Link](ch))
[Link]("You press uppercase letter");

else if([Link](ch))
[Link]("You press lowercase letter");

else if([Link](ch))
[Link]("You press space bar key");

else if([Link](ch))
{
[Link]("You press white space character");
return;
}

else
[Link]("You pressed any special symbol");
[Link](2); //to skip \n code from br
}
}
}
OUTPUT

E:\>javac [Link]

E:\>java CharTest
Enter a character:
m
You Entered:
You press lowercase letter
TEKZUNE TECHNOLOGIES 219

Enter a character:
H
You Entered:
You press uppercase letter
Enter a character:
5
You Entered:
You press a digit
Enter a character:

You Entered:
You press space bar key
Enter a character:

You Entered:
You press white space character

/*108. Write a program that generates random numbers


repeatedly between 0 and 10 and also ensure that i the
generated number is 0 then program gets terminated.*/

class Random
{
public static void main(String args[]) throws Exception
{
[Link]("Printing Random numbers between 0 and
10 :");
int counter=0;
while(true)
{
/*random() returns double type between 0 and 1. But we
want the no. as integer and between 0 and 10. So multiply it by
10 and convert into int. */

double d=100*[Link]();

int i=(int)d;
[Link]("Random number = " + i);
TEKZUNE TECHNOLOGIES 220

counter++;
[Link]("Counter = " + counter);

//Let the execution wait till 2000 mili seconds


[Link](20);
if(i==0)
[Link](0);
}
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Random
Printing Random numbers between 0 and 10 :
Random number = 84
Counter = 1
Random number = 17
Counter = 2
Random number = 21
Counter = 3
Random number = 97
Counter = 4
Random number = 6
Counter = 5
Random number = 0
Counter = 6
/*109. Write a program that generates random numbers
repeatedly between 0 and 10 and also ensure that i the
generated number is 0 then program gets terminated.*/

import [Link].*;

class Random1
{
public static void main(String args[]) throws Exception
{
TEKZUNE TECHNOLOGIES 221

BufferedReader br=new BufferedReader(new


InputStreamReader([Link]));

[Link]("Printing Random numbers of a given range");


[Link]();

[Link]("Enter any number");


int n=[Link]([Link]());
int counter=0;
while(true)
{
/*random() returns double type between 0 and 1. But we
want the no. as integer and between 0 and 10. So multiply it by
10 and convert into int. */

//int d=n*[Link]();
double d=n*[Link]();

int i=(int)d;
[Link]("Random number = " + i);

counter++;
[Link]("Counter = " + counter);

//Let the execution wait till 2000 mili seconds


[Link](20);
if(i==0)
[Link](0);
}
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Random1
Printing Random numbers of a given range
Enter any number
TEKZUNE TECHNOLOGIES 222

100
Random number = 41
Counter = 1
Random number = 5
Counter = 2
Random number = 76
Counter = 3
Random number = 82
Counter = 4
Random number = 79
Counter = 5
Random number = 1
Counter = 6
Random number = 55
Counter = 7
Random number = 9
Counter = 8
Random number = 13
Counter = 9
Random number = 76
Counter = 10
Random number = 52
Counter = 11
Random number = 0
Counter = 12
Byte Class
-------------
The Byte class wraps a value of the primitive type 'byte' in an
object. The Byte class object contains a byte type field. In this
field, we can store a primitive byte number. Remember byte
number ranges from -128 to +127.

Constructors
Byte class has two constructors.

[] Byte(byte num)
It takes byte number as its parameter and convert it into Byte
class object.
We can create Byte object as
TEKZUNE TECHNOLOGIES 223

Byte obj=new Byte(120);

[]Byte(String str)
It takes a String type parameter and converts that string into
Byte class object.
Byte obj=new Byte("120");

Important Methods of Byte class


[] int compareTo(Byte b)
This method is useful to compare the contents of two objects. It is
called as:
int x=[Link](obj2);

where, obj1 and obj2 are Byte class objects.

If obj1==obj2 then this method returns 0.

If obj1<obj2 then it returns negative value.

If obj1>obj2 then it returns positive value.

boolean equals(Object obj)


This method compares the Byte object with any other object obj.
If both have same conten, then it returns true otherwise false.

[]static byte parseByte(String str): This method returns the


primitive byte number contained in the string str.

[]String toString(): This method converts Byte object into String


object and returns that String object.

[]static Byte valueOf(String str) : This method converts a string str


that contains some byte number into Byte class object and
returns that object.

[]static Byte valueOf(byte b): This method cnoverts the primitive


byte b into Byte object.
TEKZUNE TECHNOLOGIES 224

/*110. Write a program to create Byte class objects and


then compare them to see which objecthas less or more
contents when compared to another. */

import [Link].*;

class ByteDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter a byte number 1 : ");


String s1=[Link]();
Byte b1=new Byte(s1);

[Link]("Enter a byte number 2 : ");


String s2=[Link]();
Byte b2=new Byte(s2);

int n=[Link](b2);

if(n==0)
[Link]("Both bytes are same");
else if(n<0)
[Link](b1 + " is less");
else
[Link](b2 + " is less");
}
}

OUTPUT:
E:\>javac [Link]

E:\>java ByteDemo
Enter a byte number 1 :
9
Enter a byte number 2 :
TEKZUNE TECHNOLOGIES 225

7
7 is less
TEKZUNE TECHNOLOGIES 226

COLLECTION FRAMEWORK

->The Java 2 platform includes a new collections framework. A


collection is an object that represents a group of objects (such as
the Vector class).

->A collections framework is a unified architecture for


representing and manipulating collections, allowing them to be
manipulated independently of the details of their representation.

COLLECTIONS: A collection object or a container object is an


object which can store a group of objects. A collection object has
a class called as 'collection class' or 'container class'.
All the collection classes are available in the [Link]
(stands for utility). A group of collection of classes is called a
'collection framework'.

Advantages of collections framework :


-----------------------------------------------
[]It reduces programming effort by providing useful data
structures and algorithms so you don't have to write them
yourself.
[] It increases performance.
[]Collection frame is a very good concept similar to the Data
Structures in 'C' [Link] is used to store different data types
in it
it's size dynamically increases and shrinks.

Collection Interfaces:
There are six collection interfaces. The most basic interface is
Collection.

Three interfaces extend Collection: Set, List, and SortedSet.


The other two collection interfaces, Map and SortedMap, do not
extend Collection, as they represent mappings.

Interface Description
----------------- --------------------------
TEKZUNE TECHNOLOGIES 227

Collection - A group of objects. No assumptions are


made about the order of the collection (if
any), or whether it may contain duplicate
elements.
It is the foundation upon which the collections
framework is built. It declares core methods that
all collections will have.

List - Ordered collection, also known as a sequence.


Duplicates are generally permitted. Allows
positional access. Extends the Collection interface.

Set - No duplicate elements permitted. May or may not


be ordered. Extends the Collection interface.

SortedSet- Extends 'Set' to handle sorted sets

Map - A mapping from keys to values. Each key can map to at


most one value.

All the collection classes in [Link] package are the


implementation classes of different
interfaces. As shown

Interface type Implementation classes


-------------------------------------------------------------------------
Collection<T>
Set<T> HashSet<T>
LinkedHashSet<T>

List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>

Queue<T> LinkedList<T>

Map<K,V> HashMap<K,V>
TEKZUNE TECHNOLOGIES 228

HashTable<K,V)

Sets:
A set represents a group of elements arranged just like an
array. The set will grow dynamically when the elements are
stored into it. A set will not allow duplicate elements.
If we try to pass the same element that is already
available in the set, then it is not stored into the set.

Lists:
Lists are like sets. They store a group of elements. But lists
allow duplicate values to be stored.

Queue:
A queue represents arrangement of elements in FIFO(First
In First Out) order. This means that an element that is stored as a
first element into the queue will be removed first from the queue.

Maps:
Maps store elements in the form of key and value pairs. If
the key is provided then its value can be obtained.
The keys should have unique values.

Retrieving Elements from Collections

Following are the 4 ways to retrieve any element from a collection


object:

1) Using for-each loop


2) Using Iterator interface
3) Using ListIterator interface
4) Using Enumeration interface

1) for-each Loop
for-each loop is like for loop which are peatedly executes a group
of statements for each element of the collection. The format is:
TEKZUNE TECHNOLOGIES 229

for(variable:collection-object)
{
Statements;
}
2) Iterator Interface
Iterator is an interface that contains methods to retrieve the
elements one by one from a collection object. It has 3 methods.

--> boolean hasNext(): This method returns true if the iterator has
more elements.

--> element next(): This method returns next element in the


iterator.

--> void remove(): This method removes from the collection the
last element returned by the iterator.

3) ListIterator Interface
ListIterator is an interface that contains methods to retrieve the
elements from a collection object, both in forward and reverse
directions. The methods are:

-->boolean hasNext(): This return true if the ListIterator has more


elements when traversing the list in the forward direction.

-->boolean hasPrevious(): This return true if the ListIterator has


ore eleents when traversing the list in the reverse direction.

-->element next(): This return the next element in the list.

--> element previous(): This returns the previous element in the


list.

-->void remove(): This removes from the list the last element that
was returned by the next() or previous() method.

4) Enumeration Interface
TEKZUNE TECHNOLOGIES 230

This interface is useful to retrieve elements like the Iterator. It has


2 methods:

--> boolean hasMoreElements(): This method tests if the


Enumeration has any more elements or not.

 element nextElement(): This returns the next element that


is available in Enumeration.

/* ARRAYLIST Class
ArrayList Class: An ArrayList is like an array, which can grow in
memory dynamically. It means that when we store
elements into the ArrayList, depeinding on the number of
elements, the memory is dynamically allotted and re-allotted
to accommodate all the elements. ArrayList is not synchronized.
This means that when more than one thread acts
simultaneously on the ArrayList object, the results may be
incorrect in some cases.

The ArrayList class can be written as:

class ArrayList<E>

where E represents the type of elements to be stored into the


ArrayList.

ArrayList<String> arl=new ArrayList<String>();

Some methods of ArrayList are:

--> boolean add(element obj): This method appends the specified


element to the end of the ArrayList.
--> boolean remove(Object obj): This method removes the first
occurrence of the specified element obj from the ArrayList, if it is
present.
--> void clear(): This method removes all the elements from the
ArrayList.

*/
TEKZUNE TECHNOLOGIES 231

/*111. Write a program for performing operations using


ArrayList with String objects */

import [Link].*;
import [Link].*;
class ArrListDemo
{
public static void main(String args[]) throws IOException
{
//Create ArrayList
ArrayList arl=new ArrayList<String>();

//Add four objects


[Link]("Apple");
[Link]("Mango");
[Link]("Grapes");
[Link]("Guava");

//Display contents
[Link]("Contents:"+ arl);

//Remove two objects


[Link](3);
[Link]("Apple");

//Display again
[Link]("Contents after removing:" + arl);

//Display again
[Link]("Size of ArrayList:" +[Link]());

//Extract elements using Iterator


[Link]("Extracting using Iterator:");

//Add an Iterator to ArrayList to retrieve elements


Iterator it=[Link]();

while([Link]())
TEKZUNE TECHNOLOGIES 232

{
[Link]([Link]());
}
}
}

OUTPUT:
E:\>javac [Link]

E:\>java ArrListDemo
Contents:[Apple, Mango, Grapes, Guava]
Contents after removing:[Mango, Grapes]
Size of ArrayList:2
Extracting using Iterator:
Mango
Grapes

/* HASHSET CLASS
A HashSet represents a set of elements(objects). It does not
guarantee the order of elements. Also it does not allow the
duplicate elements to be stored.

We can write HashSet class as:

class HashSet<T>

Here T represents the generic type parameter. It represents which


type of elements are being stored into the HashSet.

HashSet Class Methods:

--> boolean add(obj): This method adds an element to the


HashSet. It returns true if the element is added to the HashSet,
else it returns false.

-->boolean remove(obj): This method removes the element obj


from the HashSet, if it is present. Otherwise it returns false.
TEKZUNE TECHNOLOGIES 233

-->void clear(): This removes all the elements from the HashSet.

-->void contains(obj): This returns true if the HashSet contains


the specified elements obj.

/*112. PROGRAM ON HASHSET*/


import [Link].*;
import [Link].*;

class HashSets
{
public static void main(String args[])
{
//Create Hashset to store strings
HashSet<String> hs=new HashSet<String>();

//To store some string elements


[Link]("India");
[Link]("China");
[Link]("Japan");
[Link]("Switzerland");
[Link]("New Zealand");

//View the HashSet


[Link]("Hash set=" +hs);

//Add an Iterator to hs
Iterator it=[Link]();

//display element by element using Iterator


[Link]("Elements using Iterator");
while([Link]())
{
String s=(String)[Link]();
[Link](s);
}
}
}
OUTPUT
TEKZUNE TECHNOLOGIES 234

E:\>javac [Link]

E:\>java HashSets
Hash set=[India, New Zealand, Switzerland, China, Japan]
Elements using Iterator
India
New Zealand
Switzerland
China
Japan

Arrays Class
Arrays class provides methods to perfom certain operations on
any one dimensional array. All
the methods of the arrays class are static, so they can be called in
the form of [Link]().

Some of the methods Arrays Class are:

--> static void sort(array): This method sorts all the elements of
an array into ascending order.

-->static void sort(array,int start,int end): This method sorts the


elements in the range from
'start' to 'end' within an array into ascending order This method
uses QuickSort algorithm.

-->static int binarySearch(array,element): This method searches


for an element in the array
and returns its positoin number. This method uses BinarySearch
algorithm.

/*113. Program for Sorting and Searching of an Array */


import [Link].*;
import [Link].*;
class ArraysDemo
{
public static void main(String args[]) throws IOException
TEKZUNE TECHNOLOGIES 235

{
//To accept data from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Create an array
int arr[]=new int[5];

//Store elements into arr[]


for(int i=0;i<5;i++)
{
[Link]("Enter an integer:");
arr[i]=[Link]([Link]());
}

//Display the arr[] contents


[Link]("Contents of the array");
display(arr);

//Sort the arr[] into ascending order


[Link](arr);

//Display the sorted contents


[Link]("The sorted array:");
display(arr);

//Now searches for an element


[Link]("which element to search?");
int element=[Link]([Link]());
int index=[Link](arr,element);
if(index<0)
[Link]("Element not found");
else
[Link]("Element found at location:" +
(index+1));

}
//Display ethod- uses for each loop
static void display(int arr[])
TEKZUNE TECHNOLOGIES 236

{
for(int i:arr)
[Link](i);
} //End of ArraysDemo class
}

OUTPUT
E:\>javac [Link]

E:\>java ArraysDemo
Enter an integer:
99
Enter an integer:
88
Enter an integer:
44
Enter an integer:
33
Enter an integer:
11
Contents of the array
99
88
44
33
11
The sorted array:
11
33
44
88
99
which element to search?
44
Element found at location:3

Comparator Interface:

Using Comparator to Sort an Array


TEKZUNE TECHNOLOGIES 237

[Link] package offers an interface, called Comparator thatis


useful to impose a total ordering
on a collection of elements. It can be used to sort the eleents of
an array into ascending order or
descending order.

It is written as:
interface Comparator<T>
where T represents the type of elements(objects) compared by
the Comparator.

/*114. Sorting an array with a group of Integer objects */


import [Link].*;
import [Link].*;

//To sort into ascending order


class Ascend implements Comparator<Integer>
{
public int compare(Integer i1,Integer i2)
{
return [Link](i2);
}
}

//To serot into descending order


class Descend implements Comparator<Integer>
{
public int compare(Integer i1,Integer i2)
{
return [Link](i1);
}
}

class Arrays1
{
public static void main(String args[]) throws IOException
{
TEKZUNE TECHNOLOGIES 238

//To accept array elements fro keyboard


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("How many elements?");


int size=[Link]([Link]());

//Create an array to store Integer type objects


Integer arr[]=new Integer[size];

//Below, we pass int values to the array but they are


converted into Integer objects and then stored
for(int i=0;i<size;i++)
{
[Link]("Enter int:");
arr[i]=[Link]([Link]());
}

//Sort the array in ascending order


[Link](arr,new Ascend());

//Display the display the sorted array


[Link]("\n Sorted in Ascending order:");
display(arr);

//In descending order


[Link](arr, new Descend());
[Link]("\n Sorted in Descending order:");
display(arr);
} //End of main
static void display(Integer arr[])
{
for(Integer i: arr)
[Link](i+ "\t");
}

}
TEKZUNE TECHNOLOGIES 239

OUTPUT
E:\>javac [Link]

E:\>java Arrays1
How many elements?
5
Enter int:
22
Enter int:
44
Enter int:
67
Enter int:
75
Enter int:
78

Sorted in Ascending order:


22
44
67
75
78

Sorted in Descending order:


78
75
67
44
22

Calendar Class
It helps in knowing the sstem date and time. It helps in storing a
dat4e and time value so that it can be transported to some other
application.

Some of the methods of Calendar Class are:


--> int get(int field): This method returns the value of the given
Calendar field.
TEKZUNE TECHNOLOGIES 240

-->[Link] gives the date number from 1 to 31.


-->[Link] gives the month number from 0 to 11.
(January is taken as 0)
-->[Link] gives the year number

/*115. Write a programto display System date and time */


import [Link].*;
import [Link].*;
class CalendarDemo
{
public static void main(String args[]) throws IOException
{
//Create Calendar class object.
Calendar cl=[Link]();

//Display date seperately


[Link]("Current date:");
int dd=[Link]([Link]);
int mm=[Link]([Link]);
++mm;
int yy=[Link]([Link]);
[Link](dd+"=" +mm+ "-" + yy);

//Display time alone


[Link]("Current time:");
int h=[Link]([Link]);
int m=[Link]([Link]);
int s=[Link]([Link]);
[Link](h+ ":"+ m+ ":"+s);

int x=[Link](Calendar.AM_PM);
if(x==0)
[Link]("Good morning");
else
[Link]("Good evening");
}
}

OUTPUT
TEKZUNE TECHNOLOGIES 241

E:\>javac [Link]

E:\>java CalendarDemo
Current date:
2=2-2009
Current time:
6:31:54
Good evening

Date Class
It is useful to display the date and time at a particular moment.
When an object to Date class is created, it contains the system
date and time by default.

Some of the methods of the Date class are:

-->DateFormat
fmt=[Link](formatconst,region);
This method is useful to store format information for date value
into DateFormat object fmt.

-->DateFormat
fmt=[Link](formatconst,region);
This method is useful to store format information for time value
into DateFormat object fmt.

/*116. Display system date and time using Date class */


import [Link].*;
import [Link].*;
class MyDate
{
public static void main(String args[])
{
//Create Date class object- this contains system date and
time
Date d=new Date();

//Format the date to medium format and time to short


format
TEKZUNE TECHNOLOGIES 242

DateFormat
fmt=[Link]([Link],Date
[Link],[Link]);

//Apply the above format to the Date object


String str=[Link](d);

//Now display the formatted date and time


[Link](str);
}
}

OUTPUT

E:\>javac [Link]

E:\>java MyDate
02-Feb-2009 19:07

StringTokenizer Class
This class is useful to break a string into pieces, called 'tokens'.
These tokens are then stored in the StringTokenizer object from
where they can be retrieved.
/*117. Program to broke string into pieces whenever space
is found */
import [Link].*;
import [Link].*;
class STDemo
{
public static void main(String args[]) throws IOException
{
//Take a string
String str="He is a gentle man";

//Break into tokens at spaces. Here delimeter is a space


StringTokenizer st=new StringTokenizer(str," ");

//Retrieve tokens fro st and display


TEKZUNE TECHNOLOGIES 243

[Link]("The tokens are:");


while([Link]())
{
String one=[Link]();
[Link](one);
}
}
}

OUTPUT
E:\>javac [Link]

E:\>java STDemo
The tokens are:
He
is
a
gentle
man
LINKED LIST Class
Linked List Class:A linked list contains a group of elements in the
form of nodes. Each node will have three fields- the data field
contains data and the link fields contains references to previous
and next nodes.

It is very convenient to store data. Inserting the elements into the


linked list and removing the elements from the linked list is done
quicky and takes the same amount of time.

A linked list is written in the form:


class LinkedList<E>

We can create an empty linked list for storing String type


elements(objects) as:
LinkedList<String> ll=new LinkedList<String>();

LinkedList Class Methods


TEKZUNE TECHNOLOGIES 244

--> boolean add(element obj): This method adds an element to


the linked list. It returns true if the element is added successfully.

--> void addFirst(element obj): This method adds the element obj
at the first position of the linked list.

-->void clear(): This method removes the all the elements


fromthe linked list.

/*118. Write a program to perform operation on a Linked


List with strings */

import [Link].*;
import [Link].*;
class LLDemo
{
public static void main(String args[]) throws IOException
{
//Create an empty linked list to store strings
LinkedList<String> ll=new LinkedList<String>();

//Add some names to linked list


[Link]("America");
[Link]("India");
[Link]("Japan");

//display the elements in the linked list


[Link]("List = " + ll);

BufferedReader br=new BufferedReader(new


InputStreamReader([Link]));
String element;
int position,choice=0;

while(choice<4)
{
[Link]("LINKED LIST OPERATIONS \n ");
[Link]("1. Add an element ");
[Link]("2. Remove an element ");
TEKZUNE TECHNOLOGIES 245

[Link]("3. Change an element ");


[Link]("4. Exit ");

[Link]("Enter your choice: ? ");


choice=[Link]([Link]());

switch(choice)
{
case 1:
[Link]("Enter an element: ");
element =[Link]();
[Link]("At what position ? ");
position = [Link]([Link]());
[Link](position-1,element);
break;

case 2:
[Link]("Enter position: ");
position=[Link]([Link]());
[Link](position-1);
break;

case 3:
[Link]("Enter position");
position=[Link]([Link]());
[Link]("Enter new element: ");
element = [Link]();
[Link](position-1,element);
break;

default: return;
}
//Use iterator to retrieve the elements
[Link]("List = ");
Iterator it=[Link]();
while([Link]())
[Link]([Link]() + " ");
} //while loop
} // main()
TEKZUNE TECHNOLOGIES 246

} //class

OUTPUT :

E:\>javac [Link]

E:\>java LLDemo
List = [America, India, Japan]
LINKED LIST OPERATIONS

1. Add an element
2. Remove an element
3. Change an element
4. Exit
Enter your choice: ?
1
Enter an element:
Spain
At what position ?
1
List =
Spain
America
India
Japan
LINKED LIST OPERATIONS

1. Add an element
2. Remove an element
3. Change an element
4. Exit
Enter your choice: ?
2
Enter position:
2
List =
Spain
India
Japan
TEKZUNE TECHNOLOGIES 247

LINKED LIST OPERATIONS

1. Add an element
2. Remove an element
3. Change an element
4. Exit
Enter your choice: ?
4

/* STACK CLASS
Stack Class: A stack represents a group of elements stored in LIFO
(Last In First Out) order. This means that the element which is
stored as a last element into the stack will be the first eleent tobe
reoved from the stack. Inserting elements(objects) into the stack
is called 'push' operation and removing elements from stack is
called 'pop' operation. Searching for an element inthe stack is
called 'peep' operation. Insertion and deletion of elements take
place only from one side of the stack, called 'top' of the stack.

We can write a Stack class as:

class Stack<E>

where E stands for element type. Suppose, we want to create a


Stack object that contains Integer objects, we can do so as shown
here:

Stack<Integer> obj=new Stack<Integer>();

Stack Class Methods

--> boolean empty(): This method tests whether the stack is


empty or not. If the stack is empty then true otherwise false will
returned.

-->element peek(): This method returns top-most object from the


stack without removing it.
TEKZUNE TECHNOLOGIES 248

-->element pop(): This method pop the top-most element from


the stack and returns it.

-->element push(element obj): This method pushes an element


obj onto the top of the stack and returns that element.

-->int search(Object obj): Searches an element.

/*119. Pushing, poping and searching elements in a stack*/


import [Link].*;
import [Link].*;

class StackDemo
{
public static void main(String args[]) throws IOException
{
//Create an empty stack to contain Integer objects
Stack<Integer> st=new Stack<Integer>();

//Take vars
int choice=0;
int position,element;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//Display the menu as long as user choice < 4


while(choice<5)
{
[Link]("STACK OPERATIONS");
[Link]("1 Push an element");
[Link]("2 Pop an element");
[Link]("3 Search an element");
[Link]("4 Peek an element");
[Link]("5 Exit");

choice=[Link]([Link]());

//Perform a task depending on user choice


switch(choice)
TEKZUNE TECHNOLOGIES 249

{
case 1: [Link]("Enter the element:");
element=[Link]([Link]());
[Link](element);
break;

case 2: //The top-most Integer object is popped


Integer obj=[Link]();
[Link]("popped=" + obj);
break;

case 3: [Link]("which element?");


element=[Link]([Link]());
position=[Link](element);
if(position==-1)
[Link]("Element not found");
[Link]("Element at Position:"
+position);
break;

case 4: //The top-most Integer object is popped


Integer obj1=[Link]();
[Link]("Peek element=" + obj1);
break;

default: //come out if user choice is other than 1,2,


or 3
return;
}
//view the contents of stack
[Link]("Stack contents:" +st);
}
}
}

OUTPUT

E:\>javac [Link]
E:\>java StackDemo
TEKZUNE TECHNOLOGIES 250

STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
1
Enter the element:
11
Stack contents:[11]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
1
Enter the element:
22
Stack contents:[11, 22]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
1
Enter the element:
33
Stack contents:[11, 22, 33]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
1
Enter the element:
44
Stack contents:[11, 22, 33, 44]
STACK OPERATIONS
1 Push an element
2 Pop an element
TEKZUNE TECHNOLOGIES 251

3 Search an element
4 Exit
1
Enter the element:
55
Stack contents:[11, 22, 33, 44, 55]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
2
popped=55
Stack contents:[11, 22, 33, 44]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
2
popped=44
Stack contents:[11, 22, 33]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
3
which element?
11
Element at Position:3
Stack contents:[11, 22, 33]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
3
which element?
TEKZUNE TECHNOLOGIES 252

33
Element at Position:1
Stack contents:[11, 22, 33]
STACK OPERATIONS
1 Push an element
2 Pop an element
3 Search an element
4 Exit
4
VECTOR CLASS
Vector: A vector also stores elements(objects) similar to ArrayList,
but vector is synchronized. It means evenif several threads act on
vectro object simultaneusly, the results will be reliable.

We can write a Vector class as:


class Vector<E>
Here E, represents the type of elements stored into the vector.

Some of the Vector Class Methods are:


-->boolean add(element obj): This methods appends the specified
element to the end of
the vector.

-->int indexOf(Object obj): This method returns the position of the


first occurrence
of the specified element obj in the vector, or -1 if the element in
not found in the
list.

/*120. Creating a vector with Integer elements*/

import [Link].*;
class VectorDemo
{
public static void main(String args[])
{
//Take a vector to store Integer objects
Vector<Integer> v=new Vector<Integer>();
TEKZUNE TECHNOLOGIES 253

//Take an int type array


int x[]={22,20,10,15,60};

//when x[i] is stored into v below. x[i] values are converted


into
//Integer objects and stored into v. This is auto boxing
for(int i=0;i<[Link];i++)
{
[Link](x[i]);
}

//Retrieve the elements using get()


[Link]("Vector elements:");
for(int i=0;i<[Link]();i++)
{
[Link]([Link](i));
}

//Retrieve using ListIterator


[Link]("Elements using ListIterator:");
ListIterator lit=[Link]();

[Link]("In forward direction");


while([Link]())
[Link]([Link]()+"\t");

[Link]("\n In backward direction:");


while([Link]())
[Link]([Link]()+"\t");
}
}

OUTPUT
E:\>javac [Link]

E:\>java VectorDemo
Vector elements:
22
20
TEKZUNE TECHNOLOGIES 254

10
15
60
Elements using ListIterator:
In forward direction
22
20
10
15
60

In backward direction:
60
15
10
20
22

/*121. Sorted Set Example which is used to insert unique


objects and the objects (Elements ) are automatically
sorted after they are stored in it... */

import [Link];
import [Link];
import [Link];
public class sorted_set {
public static void main(String[] args) {
SortedSet sortedset_data =new TreeSet ();
SortedSet sortedset_number =new TreeSet ();

[Link](" Adding ");


sortedset_data.add(new String("zamaray"));
sortedset_data.add(new String("Abed"));
sortedset_data.add(new String("Anil"));
sortedset_data.add(new String("Kumar"));
sortedset_data.add(new String("Anil"));
sortedset_data.add(new String("Kumar"));
sortedset_data.add(new String("Ashraf"));
sortedset_data.add(new String("Bharath"));
TEKZUNE TECHNOLOGIES 255

sortedset_data.add(new String("India"));
sortedset_number.add(new Integer(33));
sortedset_number.add(new Integer(3));
sortedset_number.add(new Integer(393));
sortedset_number.add(new Integer(1999));
sortedset_number.add(new Integer(02));
sortedset_number.add(new Integer(3448));
[Link](" Displaying data in Data Set ");
Iterator ii = sortedset_data.iterator();
while([Link]()){
[Link](" "+ [Link]());
}
[Link](" Displaying data in Number Set ");
ii = sortedset_number.iterator();
while([Link]()){
[Link](" "+ [Link]());
} }}

OUTPUT :
E:\>javac sorted_set.java

E:\>java sorted_set
Adding
Displaying data in Data Set
Abed
Anil
Ashraf
Bharath
India
Kumar
zamaray
Displaying data in Number Set
2
3
33
393
1999
3448
TEKZUNE TECHNOLOGIES 256

/*122. To create an ArrayList of Employee objects and


search for a particular employee*/
//object based on id number
import [Link].*;
import [Link].*;
class Employee
{
//Take variables
int id;
String name;
String address;

//Initialize variables using constructor


Employee(int i,String n,String a)
{
id=i;
name=n;
address=a;
}

void display()
{
[Link]("Id : " + id);
[Link]("Name : " + name);
[Link]("Address : " + address);
}

class EmpList
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
int id;
String name,address;

//create an ArrayList arl to store Employee objects


TEKZUNE TECHNOLOGIES 257

ArrayList<Employee> arl = new ArrayList<Employee>();

for(int i=0;i<4;i++)
{
[Link]("Enter Id : ");
id=[Link]([Link]());

[Link]("Enter name : ");


name=[Link]();

[Link]("Enter address : ");


address=[Link]();

//creating Employee object


Employee obj=new Employee(id,name,address);

//store Employee object into arl


[Link](obj);
}

//Searching for an Employee id


[Link]("Enter Employee Id for searching " );
id=[Link]([Link]());

boolean found=false;

for(int i=0;i<[Link]();i++)
{
//get() method of ArrayList will return i-th Employee object
Employee obj=[Link](i);

//check if given id is equal to id of Employee object


if(id==[Link])
{
[Link]();
[Link]("Employee found at location = " + (i+1));

[Link]();
found=true;
TEKZUNE TECHNOLOGIES 258

}
}
if(!found)
[Link]("Employee not found");
}
}

OUTPUT :
E:\>javac [Link]

E:\>java EmpList
Enter Id :
1
Enter name :
SURESH
Enter address :
MIDHANI
Enter Id :
2
Enter name :
JUNAID
Enter address :
MOGHALPURA
Enter Id :
3
Enter name :
FARID
Enter address :
SALIM NAGAR
Enter Id :
4
Enter name :
ASHRAF
Enter address :
MKS COLONY
Enter Employee Id for searching
3
TEKZUNE TECHNOLOGIES 259

Employee found at location = 3


Id : 3
Name : FARID
Address : SALIM NAGAR

HashMap Class
HashMap:It is a collection that stores elements in the form of key-
value pairs. If key
is provided later, its corresponding value can be easily retrieved
fro the HashMap.
Keys should be unique. This means we cannot use duplicate data
for keys in the HashMap.
However, HashMap is not synchronized and hence while using
multiple threads on Hashap
object, we get unreliable results.

We can write HashMap class as:

class HashMap<K,V>
where K represents the type of ky element and V represents the
type of value elements.

Some of the HashMap Class Methods are:


--> value put(key, value): This method stores key-value pair into
the HashMap.

-->value get(Object key): This method returns the corresponding


value when key is
given. If the key does not have a value associated with it, then it
returns null.

-->Set<K> keySet(): This method on applied on a HashMap


converts it into a Set where
only key will be stored.

-->Collection<V> values(): This method, when applied on a


HashMap object returns
all the values of the HashMap into a Collection object.
TEKZUNE TECHNOLOGIES 260

/*123. HashMap used as Telephone Book*/

import [Link].*;
import [Link].*;

class HashMapDemo
{
public static void main(String args[]) throws IOException
{
//create HashMap
HashMap<String, Long> hm=new HashMap<String,Long>();

//variables
String name,str;
Long phone;
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//menu
while(true)
{
[Link]("1. Enter phone entries");
[Link]("2. Lookup in the book");
[Link]("3. Display names in book");
[Link]("[Link]:");

[Link]("Your choice:");
int n=[Link]([Link]());

switch(n)
{
case 1: [Link]("Enter name:");
name=[Link]();
[Link]("Enter phone no:");
str=[Link]();
phone=new Long(str);
//store name and phone into HashMap
[Link](name,phone);
TEKZUNE TECHNOLOGIES 261

break;

case 2: [Link]("Enter name:");


name=[Link]();
name=[Link](); //remove unnecessary spaces
//pass name and get phone
phone=[Link](name);
[Link]("phone: " +phone);
break;
case 3: //use keySet() to display the names
//create HashSet object to store names and refer it
by Set reference
Set<String> set=new HashSet<String>();
set=[Link]();
[Link](set);
break;

case 4: return;
}

}
}
}

OUTPUT
E:\>javac [Link]

E:\>java HashMapDemo
1. Enter phone entries
2. Lookup in the book
3. Display names in book
[Link]:
Your choice:
1
Enter name:
SOHAIL
Enter phone no:
9392447892
1. Enter phone entries
TEKZUNE TECHNOLOGIES 262

2. Lookup in the book


3. Display names in book
[Link]:
Your choice:
1
Enter name:
MAJEED
Enter phone no:
9824987130
1. Enter phone entries
2. Lookup in the book
3. Display names in book
[Link]:
Your choice:
2
Enter name:
SOHAIL
phone: 9392447892
1. Enter phone entries
2. Lookup in the book
3. Display names in book
[Link]:
Your choice:
3
[SOHAIL, MAJEED]
1. Enter phone entries
2. Lookup in the book
3. Display names in book
[Link]:
Your choice:
4

Hashtable Class
Hashtable: Hashtable is similar to HashMap which can store
elements in the form of key-value
pairs. But Hashtable is synchronized assuring proper results even
if multiple threads act on
TEKZUNE TECHNOLOGIES 263

it simultaneously.

We can write Hashtable class as:


Class Hashtable <K,V>
where K represents the type of key element and V represents the
type of value element.

Some of the Hashtable Methods are:

-->Set<K> keySet(): This method, when applied on a Hashtable


converts it into a Set where only
keys will be stored.

/*124. Hashtable with cricket players names and scores */


import [Link].*;
import [Link].*;
class HashTableDemo
{
public static void main(String args[]) throws IOException
{
//Create Hashtable with names and scores
Hashtable<String, Integer> ht=new Hashtable<String,
Integer>();
[Link]("Ganguly",183);
[Link]("Sachin",186);
[Link]("Anwar",194);
[Link]("Azharuddin",199);
[Link]("Gavaskar",236);
[Link]("[Link]",186);

//Display all player names using enumerator


[Link]("The player names:");
Enumeration e=[Link]();
while([Link]())
[Link]([Link]());

//Accept player names from keyboard


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
TEKZUNE TECHNOLOGIES 264

[Link]("Enter player name:");


String name=[Link]();
name=[Link](); //Remove unnecessary spaces

//Get score of the player


Integer score=[Link](name);
if(score!=null)
{
//Converts score from Integer objects to int value
int sc=[Link]();
[Link](name+ "Highest Scored:" + sc);
}

else
[Link]("Player not found");
}
}

OUTPUT
E>javac [Link]

E:\>java HashTableDemo
The player names:
Anwar
Ganguly
[Link]
Azharuddin
Sachin
Gavaskar
Enter player name:
Anwar
AnwarHighest Scored:194

/*125. Hashtable to store Employee inforamtion.. */


import [Link];
import [Link];
import [Link];
public class hashtableex {
public hashtableex() { }
TEKZUNE TECHNOLOGIES 265

public static void main(String args[]){


BufferedReader br =null;
Hashtable employee = new Hashtable();
[Link]("1","Abed");
[Link]("2","Azam");
[Link]("3","Ashraf");
[Link]("4","Kumar");
[Link]("5","Anil");
[Link](" Data Added in the List ");
[Link](" Retrieving data now .... ");
for(int i = 1;i<=[Link]();i++) {
String key = i+"";
[Link]([Link](key)); }
[Link](" Enter Employee ID to see Employee Name :
");
try {
br =new BufferedReader(new InputStreamReader([Link]));
String ID = [Link]();
if([Link](ID))
[Link]("Employee Name is:"+[Link](ID));
else
[Link]("Employee Name not found");
} catch (Exception ex) {
[Link]();
} finally {
try{
[Link]();
}
catch (Exception ex) {
[Link](" Exception " + [Link]());
} } } }

OUTPUT:

E:\>javac [Link]

E:\>java hashtableex
Data Added in the List
Retrieving data now ....
TEKZUNE TECHNOLOGIES 266

Abed
Azam
Ashraf
Kumar
Anil
Enter Employee ID to see Employee Name :
1
Employee Name is:Abed

Properties: Properties is a sub class of HashTable. It is used to


maintain lists of values in which the key is a String and the value
is also a String. The 'Properties' class is used by many other Java
classes.

For example, it is the type of object returned by


[Link]() whn obtaining environmental values.

Properties defines the following instance variable:

Properties defaults;
This variable holds a default property list associated with a
Properties object.

In addition to the methods that 'Properties' inherits from


Hashtable, Properties defines the mehods such as:

1. String getProperty(String key) :Returns the value associated


with key. A null object is
returned if key is neither in the
list nor in the default property
list.

2. String getProperty(String key,


String defaultProperty) :Returns the value associated
with key. defaultProperty is
returned if key is neither in the
list nor in the default property list.

3. void list(PrintStream
TEKZUNE TECHNOLOGIES 267

streamOut) :Sends the property list to the


output stream linked to streamOut.

4. void list(PrintWriter
streamOut) :Sends the property list to the
output stream linked to streamOut.

5. void load(InputStream
streamIn) throws
IOException : Inputs a property list from the
input stream linked to streamIn.

->One useful capability of the Properties class is that you can


speciy a deffault property that will be returned if no value is
associated with a certain key.
For example, a default value can be specified along with the key
in the getProperty() method -- such as
getProperty("name","default value"). IF the "name" value isnot
found, then "default value" is returned.
*/

/*126. The following example program demonstrate


'Properties'. It creates a property list in which the keys are
the names of states and the values are the names of their
capitals. Notice that the attempt ot find the capitalfor
Florida includes a default value. */

import [Link].*;

class PropertyDemo
{
public static void main(String args[])
{
Properties capitals=new Properties();
Set states;
String str;

[Link]("Andhra Pradesh","Hyderabad");
[Link]("Himachal Pradesh","Shimla");
TEKZUNE TECHNOLOGIES 268

[Link]("Arunachal Pradesh","Itanagar");
[Link]("Uttar Pradesh","Luckhnow");
[Link]("Madhya Pradesh","Bhopal");

//Show all states and capitals in hashtable


states =[Link](); //get set-view of keys
Iterator itr=[Link]();

while([Link]())
{
str=(String) [Link]();
[Link]("The capital of " + str + " is "
+[Link](str));
}
[Link]();

//look for state not in the list ---- specifies default value
str=[Link]("Karnataka" , "Not Found");
[Link]("The capital of Karnataka is" + str + " . ");

}
}

OUTPUT:
E:\>javac [Link]

E:\>java PropertyDemo
The capital of Uttar Pradesh is Luckhnow
The capital of Himachal Pradesh is Shimla
The capital of Arunachal Pradesh is Itanagar
The capital of Madhya Pradesh is Bhopal
The capital of Andhra Pradesh is Hyderabad

The capital of Karnataka isNot Found .


TEKZUNE TECHNOLOGIES 269

STREAMS AND FILES


Stream: Stream facilitate transporting data from one place to
another. Different streams are needed to send or receive data
through different sources, such as to receive data from keyboard,
we need a stram annd to send data to a file, we need another
stream.

Streams can be categorized as 'input streams' and 'output


streams'. Input streams are the streams which receive or read
data while output streams are the streams which send or write
data. All streams are represented by classes in [Link] package.

InputStreams: We know that an input stream reads data. So, to


read data from keyboard, we can attach the keyboard to an input
stream,so that the data can be read from the keyboard.

The System class has the following 3 fields:


1) [Link]: represents InputStream object. This object
represents the standard input device that is keyboard.

2)[Link]: represents PrintStream object. This object the


standard output decvice that is monitor.

3) [Link]: represents PrintStream object. This is used to print


some error messages.

Classification

for example:
DataInputStream dis=new DataInputStream([Link]);

In the above statement, we are attaching the keyboard to


DataInputStream object. The keyboard is represented by
[Link].

__________________________________________________
TEKZUNE TECHNOLOGIES 270

Another classification of streams is 'byte streams' and 'text


streams'.

Byte streams represent data in the form of individual bytes.


If a class name ends with a word 'Stream', then it comes under
byte streams. InputStream reads bytes and OutputStream writes
bytes. For example:

FileInputStream
FileOutputStream
BufferedInputStream
BufferedOutputStream

Text steams represent data as characters of each 2 bytes.


If a class name ends with the word 'Reader' or 'Writer' then it is
etaken as a text stream. Reader reads text and Writer writes text.
For example:

FileReader
FileWriter
BufferedReader
BufferedWriter

/*FileOutputStream class belongs to byte stream and stores the


data inthe form of individual bytes It can be used to create text
file.*/

/*127. Creating a file using FileOutputStream*/

import [Link].*;
class CreateFile
{
public static void main(String args[]) throws IOException
{
//Attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream([Link]);
TEKZUNE TECHNOLOGIES 271

//Attach myfile to FileOutputStream


FileOutputStream fout=new FileOutputStream("[Link]");

[Link]("Enter text (@ the end):");

char ch;

//Read characters from dis into ch. Then write them into
fout.
//Repeat this as long as the read character is not @
while((ch=(char)[Link]())!='@')
[Link](ch);

//Close the file


[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java CreateFile
Enter text (@ the end):
Hello Everybody, I am ORBIT
This is my first text file
@

E:\>type [Link]
Hello Everybody, I am ORBIT
This is my first text file

/*128. Creating a file using BufferedOutputStream*/

import [Link].*;

class CreateFile1
{
public static void main(String args[]) throws IOException
TEKZUNE TECHNOLOGIES 272

{
//Attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream([Link]);

//Attach myfile to FileOutputStream in append mode


FileOutputStream fout=new
FileOutputStream("[Link]",true);

//Attach FileOutputStream to BufferedOutputStream


BufferedOutputStream bout=new
BufferedOutputStream(fout,1024);

[Link]("Enter text @ at the end): ");

char ch;

//Read characters from dis into ch. Then write them into bout
//Repeat this as long as the read character is not @
while((ch=(char)[Link]())!='@')
[Link](ch);

//closing the file


[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java CreateFile1
Enter text @ at the end):
Hello Everybody
This file is created using BufferedOutputStream
@

E:\>type [Link]
Hello Everybody
This file is created using BufferedOutputStream
TEKZUNE TECHNOLOGIES 273

/*129. Write a program to read data from [Link] using


FileInputStream and display it on the monitor.*/

import [Link].*;

class ReadFile
{
public static void main(String args[]) throws IOException
{
//Attach the file to FileInputStream
FileInputStream fin=new FileInputStream("[Link]");
[Link]("File contents:");

//Read characters from FileInputStream and write them to


monitor.
int ch;
while((ch=[Link]())!=-1) //Upto last character
[Link]((char)ch);

//close the file


[Link]();
}
}

OUTPUT
E:\>javac [Link]

E:\>java ReadFile
File contents:
Hello Everybody, I am Sohail
This is my first text file

/*FileWriter is useful to ctreate a file by writing characters into it.

130. Write a program to create a text file using


TextWriter.
*/
TEKZUNE TECHNOLOGIES 274

import [Link].*;

class CreateFileFW
{
public static void main(String args[]) throws IOException
{
//Take a string
String str="Hyderbad is one of the beautiful city in

India."+"\n I very much like city Hyderabad.";

//Attach a file to FileWriter


FileWriter fw=new FileWriter("[Link]");

//Read character wise from string and write into FileWriter


for(int i=0;i<[Link]();i++)
[Link]([Link](i));

//close the file


[Link]();
}
}

/*131. Write a program to show how to read data from the


'text' file using FileReader*/

import [Link].*;

class ReadFile1
{
public static void main(String args[]) throws IOException
{
int ch;

FileReader fr=null;

try
{
fr=new FileReader("[Link]");
TEKZUNE TECHNOLOGIES 275

}
catch(FileNotFoundException fe)
{
[Link]("File not found");
}

while((ch=[Link]())!=-1)
{
[Link]((char)ch);

[Link]();

}
}

OUTPUT:
E:\>javac [Link]

E:\>java ReadFile1
Hyderbad is one of the beautiful city in India.
I very much like city Hyderabad.

Zipping and Unzipping Files

In zipping the file contents, following two things could happen:

[] The file contents are compressed and hence the size will be

reduced.
[] The format of data will be changed making it unreadable.

While zipping a file content, a zipping algorithm (logic) is used in


such a way that the algorithm first finds out which bit pattern is
most often repeated in the original file and replaces that bit
pattern with a 0.
TEKZUNE TECHNOLOGIES 276

Then the algorithm searches for the next bit pattern which is most
often repeated in the input file. In its place, a 1 is substituted .
The third repeated bit patern will be replaced by 01, the fourth by
10, the fifth by 100, and so on. In this way, the original bit
patterns are replaced by lesser bumber of bits. This file with
lesser number of bits is called 'zipped file ' or 'compressed file'.

To get back the original data from the zipped file, we can follow a
reverse algorithm, which substitutes the original bit pattern
wherever particular bits are found.

In Java, classes are provided to zip and unzip the file contents. We
can use DeflaterOutputStream class for zipping a file content and
InflaterInputStream class for unzipping he file contents. These
classes found in [Link] package.

Zipping a File using DeflaterOutputStream


---------------------------------------------------
Let us now learn how to compress data in a file, say 'file’ by

following these steps:

[] Attach the input file 'file' to FileInputStream for reading data.


[] Take the output file 'file2' and attach it to FileOutputStream.

This will help to write data into 'file2'.


[] Attach FileOutputStream to DeflaterOutputStream for

compressing the data.


[] Now, read data from FileInputStream and write it into

DeflaterOutputStream. It will compress the data and send it to


FileOutputStream which stores the compressed data into the
output file.

/*132. Program to compress the data contained in a file


using DeflaterOutputStream class.
TEKZUNE TECHNOLOGIES 277

Note : Before running this program, create '[Link]' with some


data
*/

import [Link].*;
import [Link].*;

class Zip
{
public static void main(String args[]) throws Exception
{
//Attach the original file:file1 to File InputStream for //reading

data
FileInputStream fis=new FileInputStream("[Link]");

//Attach compressed file:file2 to FileOutputStream


FileOutputStream fos=new FileOutputStream("[Link]");

//Atach FileOutpuStream to DeflaterOutputStream


DeflaterOutputStream dos=new DeflaterOutputStream(fos);

//read data from FileInputStream and write it into

//DeflaterOutputStream
int data;
while((data=[Link]()) !=-1)
[Link](data);

//close the files


[Link]();
[Link]();
}
}

Unzipping a File using InflaterInputStream

Now, the file with the name 'file2' contains compressed data and
TEKZUNE TECHNOLOGIES 278

suppose we want to obtain original uncmopressed data from this


file.
Let us follow these steps to uncompress data from this file.

[] Attach the compressed file 'file2' to FileInputStream. This helps


to read data from 'file2'.

[] Attach the output file 'file3' to [Link] helps to


write uncompressed data into 'file3'.

[] Attach FileInputStream to InflaterInputStream so that the data

read from FileInputStream goes into InlaterInputStream. Now

InflaterInputStream uncompressed that data.

[] Now, read uncompressed data from InflaterInputStream and


write it into FileOutputStream. This will write the uncompressed
data to 'file3'.

133. Write a program to uncompress data from a


compressed file by using InflaterInputStream.

import [Link].*;
import [Link].*;

class UnZip
{
public static void main(String args[]) throws Exception
{
//Attach input file: file2 to FileInputStream for reading data
FileInputStream fis=new FileInputStream("[Link]");

//Attach ouput file: file3 to FileOutputStream for writing data into


it.
FileOutputStream fos=new FileOutputStream("[Link]");

//Attach InflaterInputStram to FileInputStream for uncompressing


TEKZUNE TECHNOLOGIES 279

//data
InflaterInputStream iis=new InflaterInputStream(fis);

//read data from InflaterInputStream and write it into

//FileOutputStream
int data;
while((data=[Link]()) !=-1)
[Link](data);

[Link]();
[Link]();

}
}
TEKZUNE TECHNOLOGIES 280

Serialization of Objects

Serialization is the process of storing object contents into a ile.


The class whose objects are stored in the file should implement
'Serializable' interface of [Link] package.

So far, we wrote sme programs where we stored only text into the
files and retrieved same text from the files. These text files are
useful when we do not want to perorm any calculations on the
data. What happens if wen want to store some structured data in
the files? For example, we want to store some employee details
like employee indentification number (int type), name (String
type), salary (float type() and data of joning the job (Date type ) in
a file. This data is well structered and got different types. To
store such data, we need to create a class Employee wih the
instance vaiables id, name sal, doj as shown here.

class Employee implements Serializable


{
//instance variables
private int id;
private String name;
private float sal;
private Date doj;
}
Then create an object to this class and store actual data into that
object. Later, this object should be stored intoa file using
ObjectOutputStream. Please observe that the Serializable
interface should be implementedby the class whose objects are to
be stored into the file. This is the reason why Employee class
implements Serializable interface.

To store the Employee class objects into a file, follow hese steps:
[] First, attach objfile to FileOutputStream. This helps to write
data into objfile.
FileOutputStream fos=new FileOutputStream("objfile");
[]Then, attach FileOutputStream to ObjectOutputStream
ObjectOutputStream oos=new ObjectOutputStream(fos);
TEKZUNE TECHNOLOGIES 281

[] Now, ObjectOutputStream can write objects using writeObject()


mehod to FilOutputStream, which stores them intothe objfile.
Storing objects into a file like this is 'serialization'.
The reverse process where objects can be retrieved back from a
file is called 'de-serialization'.

Serializable interface is an empty interace without an members in


it. It does not containany methords also. Such an interface is
called 'marking interface' or 'tagging interface'. Marking interface
is usefil to mark the objects of a class for a special purpose. For
example, 'Serializable' interface makrs the class objects as
'serializable' so that they cane written into a file. If Serializable
interface is not implemented by the classs, then writing that class
objects into a file will lead to NotSerializableExceptiono. However,
any static and transient variables of the class cannot be
serialized. Suppose, we declare variable in the class as:
static int x =15;
tranient String str="mypassword";
Now, these variables cannot be written into the file. Such
variables are useful when the programmer wants to restrain from
storing some sensitive data into the file.

//Program Description that is [Link]


To read Employee class objects from objfile, flollow these steps:
[] Attach objfile to FileInputStream. This helps to read objects
from objfile.
FileInputStream fis =new FileInputStream("objfile");

[] Attach FileInputStream to ObjectInputStream. This


ObjectInputStream gets the objects form FileInputStream.
ObjectInputStream ois=new ObjectInputStream(fis);

[]Now, read objects form ObjectInputStream using readObject()


method as
Emloyee e=(Employee) [Link]();
TEKZUNE TECHNOLOGIES 282

134. Write a rpogram to create Employee class whose


objects are to be stored in to a file. */

import [Link].*;
import [Link];

class Employee implements Serializable


{
private int id;
private String name;
private float sal;
private Date doj;

Employee(int i,String n, float s,Date d)


{
id=i;
name=n;
sal=s;
doj=d;
}

//To display employee details


void display()
{
[Link](id + " \t" +name + "\t" +sal + "\t" + doj);
}

//To accept data from keyboard and store into Empoyee object
static Employee getData() throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

//accept employee id number, name and salary


[Link]("Enter employee id:");
int id=[Link]([Link]());

[Link]("Enter name: ");


String name=[Link]();
TEKZUNE TECHNOLOGIES 283

[Link]("Enter salary ");


float sal=[Link]([Link]());

//Take current system date and time as for joining


Date d=new Date();

//create Employee object with the accepted data


Employee e=new Employee(id,name,sal,d);

return e;
}

javac [Link] //Only compile this program

/*Write a program to show serialization of objects*/

import [Link].*;
import [Link].*;

class StoreObj
{
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader(new

InputStreamReader([Link]));

//To store objects into objfile


FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);

//ask how many objects to store


[Link]("How many objects ?");
int n=[Link]([Link]());

//store n objects into objfile


TEKZUNE TECHNOLOGIES 284

for(int i=0;i<n;i++)
{
//create Employee object with data from keyboard
Employee e1= [Link]();

//store Employee object intio ObjectOUtputStream

[Link](e1);
}

[Link]();
}
}

javac [Link]
java StoreObj

/*135. Write a program to show de-serialization of


objects*/

//ObjectOutputStream is used to read objects from a file


import [Link].*;
import [Link].*;

class GetObj
{
public static void main(String args[]) throws Exception
{
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);

//read objects and display till a nulll object is read


try{
Employee e;
while((e=(Employee) [Link]())!=null)
{
[Link]();
}
TEKZUNE TECHNOLOGIES 285

}catch(EOFException ee)
{
[Link]("End of file reached");
}
finally
{
[Link]();
}
}
}

javac [Link]
java GetObj

/*136. Write a program which accepts a filename from


commandline argument and displays the number of
characters, words, and lines inthe file. */

import [Link].*;

class Count
{
public static void main(String args[]) throws IOException
{
int ch;
boolean prev=true;

//counters
int char_count=0,word_count=0,line_count=0;

//Attach the: args[0] to FileInputStream to read data


FileInputStream fin=new FileInputStream(args[0]);

//read cahracters from the file till the end


while((ch=[Link]()) !=-1)
{
if(ch!=' ') ++char_count;
if(!prev && ch==' ') ++word_count;
TEKZUNE TECHNOLOGIES 286

//Don't count if previous char isspace


if(ch==' ')
prev=true;
else
prev=false;

if(ch== '\n')
++line_count;
}

//Display the count of characters, workds and lines


char_count-=line_count*2;
word_count+=line_count;
[Link]("[Link] chars = " + char_count);
[Link]("[Link] words = " + word_count);
[Link]("[Link] lines = " + line_count);

//close file
[Link]();

}
}
OUTPUT:
E:\>javac [Link]

E:\>java Count [Link]


[Link] chars = 2301
[Link] words = 429
[Link] lines = 54

/*Sometimes we need to copy the entire data of a text file into


another text file,. Streams are useful in this case.

[]For reading data fromthe input file, attach it to FileInputStream


[]For writing data into the output file, which is to be created,
attach it to FileOutputStream.
TEKZUNE TECHNOLOGIES 287

/*137. Program to read data from FileInputStream and


write into FileOutputStream. This means, the data is read
from the input file and send to output file. */

import [Link].*;

class CopyFile
{
public static void main(String args[]) throws IOException
{
int ch;
//For reading data from args[0]
FileInputStream fin=new FileInputStream(args[0]);

//For writing data into args[1]


FileOutputStream fout=new FileOutputStream(args[1]);

//read from FileInputStream and write into FileOutputStream


while((ch=[Link]()) !=-1)
[Link](ch);

//close files
[Link]();
[Link]();
[Link](" 1 file copied");
}
} OUTPUT:
E:\ \Serialization>javac [Link]

E:\>java CopyFile [Link] [Link]


1 file copied

File class: File class of [Link] package provides ssome mehods to


know the properties of a file or a directory. First of all, we should
create the File class object by passing the filename or directory
name to it.
TEKZUNE TECHNOLOGIES 288

/*138. Program that accepts a file or directory name from


command line arguments. Then the program checks I that
ile or directory physically exists or not and it displays the
properties of tha ile or directory */
import [Link].*;

class FileProperties
{
public static void main(String args[])
{
//accept file name or directory name through command line
args
String fname=args[0];

//pass the filename or directory name to File object


File f=new File(fname);

//Apply File class methods on File object


[Link](" File name : " + [Link]());

/*getPath(): this method gives the name directory path of a file


or directory */
[Link](" File path : " + [Link]());

/*getAbsolutePath(): this method gives the absolute directory


path of a file or directory location. Absolute path is mentioned
starting from the root directory */
[Link](" Absolute Path : " + [Link]());

[Link](" Parent : " + [Link]());


[Link](" Exists : " + [Link]());
if([Link]())
{
[Link](" Is Writeable : " + [Link]());
[Link](" Is Readable : " + [Link]());
[Link](" Is Directory : " + [Link]());
[Link](" File length in bytes : " + [Link]());
}
}
TEKZUNE TECHNOLOGIES 289

}
OUTPUT:
E:\>javac [Link]

E:\>java FileProperties [Link]


File name : [Link]
File path : [Link]
Absolute Path : E:\STREAMS AND FILES\Serialization\[Link]
Parent : null
Exists : true
Is Writeable : true
Is Readable : true
Is Directory : false
File length in bytes : 1112

/*139. Program to accept a directory name and display its


contents into an array */

import [Link].*;

class Contents
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link](" Enter directory path: " );


String dirpath=[Link]();

[Link]("Enter directory name: ");


String dname=[Link]();

//Create File object with dirpath and dname


File f=new File(dirpath,dname);

//if directory exists, then


if([Link]())
{
TEKZUNE TECHNOLOGIES 290

/*Get the contents into arr[], now arr{i} represents either a file
or sub directory */
String arr[]=[Link]();

//Find no. of entries in the directory


int n=[Link];

//display the entries


for(int i=0;i<n;i++)
{
[Link](arr[i]);

//create File object with the entry and test if its is a file or
directory
File f1=new File(arr[i]);
if([Link]())
[Link](": is a file");
//[Link]();

if([Link]())
[Link](": is a directory");
[Link]();
}

[Link]("No of entries in this directory : " + n);


}
else

[Link]("Directory does not exists");


}
}
OUTPUT:
E:\>javac [Link]

E:\>java Contents
Enter directory path:
E:\
Enter directory name:
Sohail
TEKZUNE TECHNOLOGIES 291

ABS
[Link]
ORACLE
SOHAIL_DOCS
SOHAIL_Updated.doc
No of entries in this directory : 5
TEKZUNE TECHNOLOGIES 292

NETWORKING
Network: A network represents interconnection of computers
either by using a cable or a satellite where no cable is needed. In
a network, there may be several computers--some of them
receiving the services and some providing the services to others.
The computer which receives service is called a 'client' and the
computer which provicdes the service is called a 'server'.

There are 3 requirement to establish a network:

i. Hardware: Includes the computers, cables, modems, hubs etc.


ii. Software: Includes programs to communicate between servers
and clients.
iii. Protocol: Represents a way to establish connection and helps
insending and receiving data in a standard format.

TCP/IP Protocol
-----------
A protocol represents a set of rules to be followed by every
computer on the network. Protocol is useful to physically move
data from one place to another place on a network.
TCP(Transmission Control Protocol) / IP (Internet Protocol) is the
standart protocol model used on any network, including Internet.

IP address: An IP address is a unique identification number


allotted toevery computer on a network or Internet. IP address
contains some bytes which identity the network and the actual
computer inside the network.

DNS(Domain Naming Service) is a service on Internet that maps


IP addresses with corresponding website names.

User Data Protocol (UDP)


-----------------
UDP is another protocol that transfers data in a connection less
and unreliable manner. It will not check how many bits are sent or
how many bits are actually received at the other side. During
transmission of data, there may be loss of some bits. Hence, UDP
is used to send images, audio files and video iles. Even if some
TEKZUNE TECHNOLOGIES 293

bits are lost, still the image or audio file can be composed with a
slight variation that will not disturb the original image or audio.

Sockets: It is possible toa establish a logical connecting point


between a server and a client so that communication can be done
through that point. This point is called 'Socket'.
Each Socket is given an identiication number, which is called 'port
number'. Port number takes 2 bytes and can be from 0 to 65, 535.
Establishing communication between a server and a client using
sockets is called 'Socket Programming'.

-->A socket, at server side is called 'server socket' and is created


using ServerSocket class in Java. A socket, at client side is called
'Socket' and is created using Socket class. Both these classes are
available in package caled "[Link]" package.

/*140. Program to accept a website name and return its


IPAddress, after checking it on Internet. */

//Knowing the IP address of a website


import [Link].*;
import [Link].*;

class Address
{
public static void main(String args[]) throws IOException
{
//accept the name of website from keyboard
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter a website name: ");


String site=[Link]();

try
{
//getByname() method accepts site name and returns its IP
Address
InetAddress ip=[Link](site);
TEKZUNE TECHNOLOGIES 294

[Link]("The IP Address is: " + ip);


} catch(UnknownHostException ue)
{
[Link]("Website not found");
}
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Address
Enter a website name: [Link]
The IP Address is: [Link]/[Link]

E:\>java Address
Enter a website name: [Link]
The IP Address is: [Link]/[Link]

E:\>java Address
Enter a website name: [Link]
The IP Address is: [Link]/[Link]

E:\>java Address
Enter a website name: [Link]
The IP Address is: [Link]/[Link]

URLConnection: It is a class which is actually useful to connect


to a website or resource on a network and get all the details of
the website.
For example, to know the details of [Link], we should
pass its URL to the object of URL class. Then using
openConnection() method, we should establish a contact with the
site on Internet. This method returns URLConnection object. Then
using URLConnection class methods, we can display all the details
of the website and also content of the webpage whose name is
given in URL.
TEKZUNE TECHNOLOGIES 295

Note: The below program will be executed on a system which is


having internet connection

/*[Link] to display the details and the [Link]


page contents of [Link] */

import [Link].*;
import [Link].*;
import [Link].*;

class Details
{
public static void main(String args[]) throws Exception
{
//pass the site url to URL object
URL obj=new URL("[Link]

//open a connection with the site on Internet


URLConnection conn=[Link]();

//display the date


[Link]("Date: " + new Date([Link]()));

//display the content type whether text or html


[Link]("Content-type: " + [Link]());

//display the expire date


[Link]("Expiry date: " + [Link]());

//display last modified date


[Link]("Last modified: " + new
Date([Link]()));

//display how many bytes the [Link] page has


int l=[Link]();
[Link]("Length of content " + l);

if(l==0)
{
TEKZUNE TECHNOLOGIES 296

[Link]("Content not available" );


return;
}

else
{
int ch;
InputStream in=[Link]();
//display the content of the [Link] page
while((ch=[Link]())!=-1)
[Link]((char)ch);
}
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Details
Date: Thu Mar 08 11:01:56 IST 2012
Content-type: text/html;charset=utf-8
Expiry date: 0
Last modified: Thu Jan 01 05:30:00 IST 1970
Length of content -1
<!DOCTYPE html>
<html lang="en-IN" class="y-fp-bg y-fp-pg-grad bkt704"
style="">
<!-- m2 template -->
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8">

<title>Yahoo! India</title>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
URL(Uniform Resource Locator) represents the address that
is specified to access some information or resource on Internet.
Example: [Link]

The URL contains 4 parts:


-----------------
TEKZUNE TECHNOLOGIES 297

-The protocol to use ([Link]


-The server name or IP address of the server ([Link]).
-The third part represents port number, which is optional (:80).
-The last part is the file that is referred. This would be generally
[Link] or [Link] file.

/*142. Program to retrieve different parts of a URL


supplied to URL class object. */

import [Link].*;
class MyURL
{
public static void main(String args[]) throws Exception
{
URL obj=new URL("[Link]

[Link](" Protocol: " + [Link]());


[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Path: " + [Link]());
[Link]("External form: " + [Link]());
}
}

OUTPUT:

E:\>javac [Link]

E:\>java MyURL
Protocol: http
Host: [Link]
File: /[Link]
TEKZUNE TECHNOLOGIES 298

Port: -1
Path: /[Link]
External form: [Link]

/*143. Program to create a server for the purpose of


sending some strings to the client. */

import [Link].*;
import [Link].*;

//[Link]
class Server1
{
public static void main(String args[]) throws Exception
{
//Create a server socket with some port number
ServerSocket ss=new ServerSocket(777);

//let the server wait till a client accepts connection


Socket s=[Link]();
[Link]("Connection established");

//attach output stream to the server socket


OutputStream obj=[Link]();

//attach print stream to send data to the socket


PrintStream ps=new PrintStream(obj);

//sending 2 strings to the client


String str="Hello Client how are you ?";
[Link](str);
[Link]();
[Link]();
[Link]();
}
}

//Program to create client side program, which accepts all the


strings sent by the server.
TEKZUNE TECHNOLOGIES 299

import [Link].*;
import [Link].*;

class Client1
{
public static void main(String args[]) throws Exception
{
//create client socket with same port number
Socket s=new Socket("localhost", 777);

//to read data coming from server, attach InputStream to the


socket
InputStream obj=[Link]();

//to read data from the socket into the client, use
BufferedReader
BufferedReader br=new BufferedReader(new
InputStreamReader(obj));

//receive strings
String str;
while((str=[Link]()) != null)
[Link]("From server: " + str);

//close connection by closing the streams and sockets


[Link]();
[Link]();
}
}
OUTPUT:
E:\>javac [Link]
E:\>javac [Link]

E:\>java Server1
TEKZUNE TECHNOLOGIES 300

//Note: Open another command prompt to execute the client


program
TEKZUNE TECHNOLOGIES 301

//In another command prompt, type the command as

java Client1
TEKZUNE TECHNOLOGIES 302

/*144. Program to create a server such that the server


receives data the server from the client using
BuffreredReader and then sends reply to the client using
PrintStream*/

import [Link].*;
import [Link].*;

class Server2
{
public static void main(String args[]) throws Exception
{
//Create Server socket
ServerSocket ss=new ServerSocket(888);

//connect it to client socket


Socket s=[Link]();
[Link]("Connection established");

//To send data to the client


PrintStream ps=new PrintStream([Link]());

//To read data coming from the client


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));

//To read data from the key board


BufferedReader kb=new BufferedReader(new
InputStreamReader([Link]));

while(true) //server executes continuously


{
String str1,str2;

//repeat as long as client does not send null string


while((str1=[Link]())!=null) //read from client
{
[Link](str1);
str2=[Link]();
TEKZUNE TECHNOLOGIES 303

[Link](str2); //send to cllient


}

//close connection
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](0); //terminate application
}
}
}

/*Program to create a client which first connects to a server, then


starts the communication by sending a string to the server. The
server sends response to the lcient. When 'exit'
is typed at client side, the program terminates. */

import [Link].*;
import [Link].*;

class Client2
{
public static void main(String args[]) throws Exception
{
//Create client socket
Socket s=new Socket("localhost",888);

//To send data to the server


DataOutputStream dos=new
DataOutputStream([Link]());

//To read data coming from the server


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));

//To read data from keyboard


TEKZUNE TECHNOLOGIES 304

BufferedReader kb=new BufferedReader(new


InputStreamReader([Link]));

String str1,str2;

//repeat as long as exit is not typed at client


while(!(str1=[Link]()).equals("exit"))
{
[Link](str1 + "\n"); //send to server
str2=[Link](); //receive from server
[Link](str2);
}

//close connection
[Link]();
[Link]();
[Link]();
[Link]();
}
}

E:\>javac [Link]
E:\>javac [Link]

E:\>java Client2
TEKZUNE TECHNOLOGIES 305

//In another command prompt execute the client program as

java Client2
TEKZUNE TECHNOLOGIES 306
TEKZUNE TECHNOLOGIES 307
TEKZUNE TECHNOLOGIES 308
TEKZUNE TECHNOLOGIES 309

//Note: To end chatting type ‘exit’ at client prompt


TEKZUNE TECHNOLOGIES 310
TEKZUNE TECHNOLOGIES 311

THREADS
Thread: A thread represents a separate path o execution of group
of statements. In a Java program, if we write a group of
statements, then these statements are executed by JVM one by
one. This execution is called a ‘Thread’, because JVM uses a
thread to these statements. This thread is used by JVM internally
to execute the program statements.

• Main is also a thread. By default ‘main’ thread is always runs


in a java program.
• The way the statements are executed is of two types.
• 1) Single tasking
• 2) Multi tasking

Task: A task means doing some calculation, processing etc.


Generally, a task involves execution of a group of statements, for
example executing a program.

• Single Tasking: In ‘single tasking’ environment, only one task


is given to the processor at a time.

• Multi Tasking: Executing several task at a time is called


‘multi tasking’. With multi tasking we can save processor’s
time. To use processor’s time in an optimum way, we can
give several jobs at a time.

Multi Tasking using Threads


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

Uses of Threads
TEKZUNE TECHNOLOGIES 312

 Threads are mainly used in server-side programs to serve


the needs of multiple clients on a network or internet.
 Threads are also used to create games and animation.
Animation means moving the objects from one place to
another.

/*145. Write a program to find the thread used by JVM to


execute the statements.*/
//To find currently running thread in a program.

import [Link].*;
class Current
{
public static void main(String args[])
{
[Link]("Let us find current thread");
Thread t=[Link]();
[Link]("Current thread=" + t);
[Link]("Its name " + [Link]());
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Current
Let us find current thread
Current thread=Thread[main,5,main]
Its name main

/*146. Write a program to create MyThread class with


run() method and then attach a thread to this MyThread
class object.*/

//[Link]
class MyThread extends Thread
{
//write run method inside this class
public void run()
{
TEKZUNE TECHNOLOGIES 313

//only this code is executed by the thread


for(int i=1;i<=100000;i++)
{
[Link](i);
}
}
}

//[Link]
class Demo
{
public static void main(String args[])
{
//create an object to MyThread class.
MyThread obj=new MyThread();

//create a thread and attach it to the object of MyThread


class
Thread t=new Thread(obj);

//Now run the thread on the object.


[Link](); //Now this thread will execute the code inside run()
//method of MyThread object
}
}
OUTPUT:
E:\THREAD>javac [Link]
E:\THREAD>javac [Link]

E:\THREAD>java Demo
1
2
3
4
//Note : To end program press ‘CTRL+C’
/*147. Write a program showing two threads working
simultaneously upon two objects*/

//[Link]
TEKZUNE TECHNOLOGIES 314

class MyThread1 implements Runnable


{
//declaring string to represent the task
String str;

MyThread1(String str)
{
[Link]=str;
}

public void run()


{
for(int i=1;i<=10;i++)
{
[Link](str+ " : " +i);
try
{
//cease thread execution for 2000 m/sec
[Link](2000);

} catch(InterruptedException ie)
{
[Link]();
}
} //end of for loop
} //end of run()
}

//[Link]
class Multi
{
public static void main(String args[])
{
//create two objects to represent two tasks
MyThread1 obj1=new MyThread1("Cut the tickets");
MyThread1 obj2=new MyThread1("Show the seat");

//create two thread and attach them to the two objects


Thread t1=new Thread(obj1);
TEKZUNE TECHNOLOGIES 315

Thread t2=new Thread(obj2);

//start the threads


[Link]();
[Link]();
}
}
OUTPUT:
E:\THREAD>javac [Link]

E:\THREAD>java Multi
Cut the tickets : 1
Show the seat : 1
Show the seat : 2
Cut the tickets : 2
Show the seat : 3
Cut the tickets : 3
Cut the tickets : 4
Show the seat : 4
Show the seat : 5
Cut the tickets : 5
Cut the tickets : 6
Show the seat : 6
Show the seat : 7
Cut the tickets : 7
Show the seat : 8
Cut the tickets : 8
Show the seat : 9
Cut the tickets : 9
Show the seat : 10
Cut the tickets : 10
TEKZUNE TECHNOLOGIES 316

/*148. Write a program showing two threads acting upon a


single object.*/
//Thread unsafe - Two hteads acting on same object

//[Link]
class Reserve implements Runnable
{
//available berths are
int available=1;
int wanted;

//accept wanted berths at run time


Reserve(int i)
{
wanted=i;
}

public void run()


{
//display available berths
[Link]("Availble berths =" +available);
//if available berths are more than wanted berths
if(available>=wanted)
{
//get the name of passenger
String name=[Link]().getName();
//allot the berth to him
[Link](wanted+ "Berths reserved for "
+ name);
try
{
[Link](1500); //wait for printing the
ticket
available=available-wanted;
//update the [Link] available berths
}catch(InterruptedException ie){}
}
//if available berths are less, display sorry
else
TEKZUNE TECHNOLOGIES 317

[Link]("Sorry, no berths");
}
}

//[Link]
class Fight
{
public static void main(String args[])
{
//tell that 1 bertht is needed
Reserve obj=new Reserve(1);

//attach first thread to the object


Thread t1=new Thread(obj);

//attach second thread to the object


Thread t2=new Thread(obj);

//take the thread names as persons names


[Link]("First person");
[Link]("Second person");

//send the request for berth


[Link]();
[Link]();
}
}
OUTPUT:
E:\>javac [Link]
E:\>javac [Link]

E:\>java Fight
Availble berths =1
1Berths reserved for First person
Availble berths =1
1Berths reserved for Second person
TEKZUNE TECHNOLOGIES 318

/*149. Write a program to synchronize the threads acting


onthe same object. The synchronized block in the
program can be executed by only one thread at a time.*/

//[Link]
class Safe implements Runnable
{
//available berths are a1
int available=1;
int wanted;

//accept wanted berths at run time


Safe(int i)
{
wanted=i;
}

public void run()


{
synchronized(this) //synchronize the current object
{
//display available berths
[Link]("Available berths=" +available);
//if available berths are more than wanted berths
if(available>=wanted)
{
//get the name of the processor
String name=[Link]().getName();
//allot the berth to him
[Link](wanted + "Berths reserved for" +name);
try
{
[Link](1500); //wait for printing the ticket
available=available-wanted;
//update the no. of available berths
}catch(InterruptedException ie){}
}
//if available berths are less, display sorry
else
TEKZUNE TECHNOLOGIES 319

[Link]("Sorry no berths");
} //end of synchronized block
}

public static void main(String args[])


{
//tell that 1 bertht is needed
Safe obj=new Safe(1);

//attach first thread to the object


Thread t1=new Thread(obj);

//attach second thread to the object


Thread t2=new Thread(obj);

//take the thread names as persons names


[Link]("First person");
[Link]("Second person");

//send the request for berth


[Link]();
[Link]();
}
}
OUTPUT:
E:\>javac [Link]

E:\THREAD>java Safe
Available berths=1
1Berths reserved forFirst person
Available berths=0
Sorry no berths

/*Thread DeadLock: When a thread has locked anobject and


waiting for another object ot be released by another thread, and
TEKZUNE TECHNOLOGIES 320

the other thread is also waiting or the first thread to release the
first object, both the threads will continue waiting forever. This is
called 'Thread Deadlock'. */

/*150. Example program for ‘DEADLOCK’ */


class BookTicket extends Thread
{
//we are assuming train, compartment as objects
Object train,comp;

BookTicket(Object train, Object comp)


{
[Link]=train;
[Link]=comp;
}

public void run()


{
//lock on train
synchronized(train)
{
[Link]("BookTicket locked on train");
try
{
[Link](150);
} catch(InterruptedException e) {}

[Link]("BookTicket now waiting to lock


oncompartment....");

synchronized(comp)
{
[Link]("BookTicket locked on compartment");
}
}
}
}

class CancelTicket extends Thread


TEKZUNE TECHNOLOGIES 321

{
//We are assuming train, compartment as objects
Object train,comp;

CancelTicket(Object train,Object comp)


{
[Link]=train;
[Link]=comp;
}

public void run()


{
//lock on compartment
synchronized(comp)
{
[Link]("CancelTicket locked on compartment");
try {
[Link](200);
}catch(InterruptedException e) {}

[Link]("CancelTicket now waiting to lock on train...");


synchronized(train)
{
[Link]("CancelTicket locked on train");
}
}
}
}

public class DeadLock


{
public static void main(String args[]) throws Exception
{
//take train, compartment as objects of object class
Object train=new Object();
Object compartment=new Object();

//create objects to BookTicket, CancelTicket clases


TEKZUNE TECHNOLOGIES 322

BookTicket obj1=new BookTicket(train,compartment);


CancelTicket obj2=new CancelTicket(train,compartment);

//attach two threads to these objects


Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
//run the threads on the objects
[Link]();
[Link]();
}
}
OUTPUT

E:\>javac DeadLock
E:\>java DeadLock

BookTicket locked on train


CancelTicket locked on compartment
BookTicket now waiting to lock oncompartment....
CancelTicket now waiting to lock on train...

/*151. Example program for avoiding deadlock*/


In order to avoid 'DeadLock' in our program we need to make
some changes in our run() method of 'CancelTicket' class. This
'CancelTicket' class should follow the BookTicket class to avoid
DeadLock.

/*In order to avoid 'DeadLock' in our program we need to make


some
changes in our run() method of 'CancelTicket' class. This
'CancelTicket' class should follow the BookTicket class to avoid
DeadLock. */

class BookTicket1 extends Thread


{
//we are assuming train, compartment as objects
Object train,comp;
TEKZUNE TECHNOLOGIES 323

BookTicket1(Object train, Object comp)


{
[Link]=train;
[Link]=comp;
}

public void run()


{
//lock on train
synchronized(train)
{
[Link]("BookTicket locked on train");
try
{
[Link](150);
} catch(InterruptedException e) {}

[Link]("BookTicket now waiting to lock


oncompartment....");

synchronized(comp)
{
[Link]("BookTicket locked on compartment");
}
}
}
}

class CancelTicket1 extends Thread


{
//We are assuming train, compartment as objects
Object train,comp;

CancelTicket1(Object train,Object comp)


{
[Link]=train;
[Link]=comp;
}
TEKZUNE TECHNOLOGIES 324

public void run()


{
//lock on compartment
synchronized(train)
{
[Link]("CancelTicket locked on compartment");
try {
[Link](200);
}catch(InterruptedException e) {}

[Link]("CancelTicket now waiting to lock on train...");


synchronized(comp)
{
[Link]("CancelTicket locked on train");
}
}
}
}

public class DeadLock1


{
public static void main(String args[]) throws Exception
{
//take train, compartment as objects of object class
Object train=new Object();
Object compartment=new Object();

//create objects to BookTicket, CancelTicket clases


BookTicket1 obj1=new BookTicket1(train,compartment);
CancelTicket1 obj2=new CancelTicket1(train,compartment);

//attach two threads to these objects


Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
//run the threads on the objects
[Link]();
[Link]();
TEKZUNE TECHNOLOGIES 325

}
}
OUTPUT

E:\>javac [Link]
E:\>java DeadLock1

BookTicket locked on train


BookTicket now waiting to lock oncompartment....
BookTicket locked on compartment
CancelTicket locked on compartment
CancelTicket now waiting to lock on train...
CancelTicket locked on train

/*152 Write a program to create a server with 2 threads to


communicate with several clients. */

import [Link].*;
import [Link].*;
class MultiServe implements Runnable
{
static ServerSocket ss;
static Socket s;

public void run()


{
//find thread name
String name=[Link]().getName();
for(;;)
{
try {
[Link]("Thread " + name + " ready to accept ...");
s=[Link]();
[Link]("Thread " + name + " accepted a
connection");
//for sending message
PrintStream ps=new PrintStream([Link]());
TEKZUNE TECHNOLOGIES 326

[Link]("Thread " + name + "contacted you ");

//close the connection


[Link]();
[Link]();
}catch(Exception e) {}
}
}

public static void main(String args[]) throws Exception


{
MultiServe ms=new MultiServe();

//create server socket with 999 as port number


ss=new ServerSocket(999);

//create 2 threads
Thread t1=new Thread(ms,"One");
Thread t2=new Thread(ms,"Two");

//start the threads


[Link]();
[Link]();
}
}

/*Write a program to create a client that receives message from


the server*/

import [Link].*;
import [Link].*;

class MultiClient
{
public static void main(String args[]) throws Exception
{
TEKZUNE TECHNOLOGIES 327

//create Client socket with port number 999


Socket s =new Socket("localhost", 999);

//to accept data from server


BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));

//receive data as long as server does not close client socket


String str;
while((str=[Link]())!=null)
[Link](str);

//close connection
[Link]();
[Link]();
}
}

OUTPUT:
E:\THREAD>javac [Link]

E:\THREAD>javac [Link]

E:\THREAD>java MultiServe
Thread Two ready to accept ...
Thread One ready to accept ...
TEKZUNE TECHNOLOGIES 328

//In another command prompt, execute client application

java MultiClient
TEKZUNE TECHNOLOGIES 329

/*Thread Communication:
----------------------------
In some cases, wo or more threads should communicate with
each other. For example, a Consumer thread is waiting for a
Producer to produce the data (or some goods). When the
Producer thread completes production of data, then he Consumer
thread should take that data and use it.

In the Producer class, we take a StringBuffer object to store data;


in this case, we take some numbers from 1 to 10. These numbers
are added to StringBuffer object. We take another boolean
variable datapordover, and initialize it to alse. The idea is to make
this dataprodover true when the production of numbers is
completed. Producing data is done by appending numbers to
StringBuffer using a for loop. This may take some time. When
TEKZUNE TECHNOLOGIES 330

appending is over, we come out of for loop and then store true
into dataprodover. */

/*Program where the Consumer thread checks whether the data


production is over or not every 10 milliseconds*/

/*153. This program hsows how two hreads can


communicate with each other. This is inefficient way of
communication*/

class Communicate
{
public static void main(String args[])
{
//Producer produces some data which Consumer consumes
Producer obj1=new Producer();

//Pass producer object to Consumer so that it is then available


to Consumer
Consumer obj2=new Consumer(obj1);

Thread t1=new Thread(obj1);


Thread t2=new Thread(obj2);

[Link](); //Consumer waits


[Link](); //Producer starts production
}
}

class Producer extends Thread


{
StringBuffer sb;

//This variable will be true when data production is over


boolean dataprodover = false;
TEKZUNE TECHNOLOGIES 331

Producer()
{
sb=new StringBuffer(); //allot memory
}

public void run()


{
//Go on appending data (numbers) to string buffer
for(int i=1;i<=10;i++)
{
try
{
[Link](i+":");
[Link](100);
[Link]("appending");
}catch(Exception e) {}
}
//Data production is over, now 'dataprodover' is set to
true
dataprodover=true;
}
}

class Consumer extends Thread


{
//Create Producer reference to refer to Producer object from
Consumer class
Producer prod;

Consumer(Producer prod)
{
[Link]=prod;
}

public void run()


{
/*If data production is not over, then sleep ofr 10
milliseconds and check again. Here thre is atime delay of
several milliseconds to receive data */
TEKZUNE TECHNOLOGIES 332

try
{
while(![Link])
[Link](10);
}catch(Exception e) {}

//When data production is over, display data of StringBuffer


[Link]([Link]);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Communicate
appending
appending
appending
appending
appending
appending
appending
appending
appending
appending
1:2:3:4:5:6:7:8:9:10:

/*154. Program where Consumer thread is informed


immediately when the data production is over*/

/*This program show how to use wait and notify.


This is the most efficient way of thread communication*/

class Communicate1
{
public static void main(String args[])
{
//Producer produces some data which Consumer consumes
Producer1 obj1=new Producer1();
TEKZUNE TECHNOLOGIES 333

//Pass producer object to Consumer so that it is then available


to Consumer
Consumer1 obj2=new Consumer1(obj1);

Thread t1=new Thread(obj1);


Thread t2=new Thread(obj2);

[Link](); //Consumer waits


[Link](); //Producer starts production
}
}

class Producer1 extends Thread


{
StringBuffer sb;

Producer1()
{
sb=new StringBuffer(); //allot memory
}

public void run()


{
synchronized(sb)
{
//Go on appending data (numbers) to string buffer
for(int i=1;i<=10;i++)
{
try
{
[Link](i+":");
[Link](100);
[Link]("appending");
}catch(Exception e) {}
}
//Data production is over, so notify to Consumer Thread
[Link]();
TEKZUNE TECHNOLOGIES 334

}
}
}

class Consumer1 extends Thread


{
//Create Producer reference to refer to Producer object from
Consumer class
Producer1 prod;

Consumer1(Producer1 prod)
{
[Link]=prod;
}

public void run()


{
synchronized([Link])
{
/*Wait till a notification is received from Producer thread. Here
there is no wastage of time of even a single millisecond */
try
{
[Link]();
}catch(Exception e) {}

//When data production is over, display data of StringBuffer


[Link]([Link]);
}
}
}

OUTPUT:
E:\>javac [Link]

E:\>java Communicate1
appending
appending
TEKZUNE TECHNOLOGIES 335

appending
appending
appending
appending
appending
appending
appending
appending
1:2:3:4:5:6:7:8:9:10:

/*155. Program to understand the thread priorities. */

class MyClass extends Thread


{
int count=0;
public void run()
{
for(int i=1;i<=10000;i++)
count++;

//Display which thread has completed counting and its priority


[Link]("Completed thread: " +
[Link]().getName());
[Link]("Its priority: " +
[Link]().getPriority());
}
}

class Priority
{
public static void main(String args[])
{
MyClass obj=new MyClass();

//create two threads


Thread t1=new Thread(obj, "One" );
Thread t2=new Thread(obj, "Two" );
TEKZUNE TECHNOLOGIES 336

//set priorities for them


[Link](2);
[Link](Thread.NORM_PRIORITY); // This means priority
will be 5

[Link]();
[Link]();

}
}

OUTPUT
E:\>javac [Link]

E:\>java Priority
Completed thread: Two
Its priority: 5
Completed thread: One
Its priority: 2

/*156 Program to show how to check whether a threAD IS


ALIVE OR NOT. Shows how to wait till other thread finishes
it's tasks */

class Thr4
{
static public void main(String[] args) throws Exception
{
Thread th1 = new MyThr4("thread one");
Thread th2 = new MyThr4("thread two");
Thread th3 = new MyThr4("thread three");

[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);

[Link]();
[Link]();
TEKZUNE TECHNOLOGIES 337

[Link]();
[Link](th2 + "is alive "+ [Link]());
// just sleep for some time till three threads finishes their tasks
[Link]().sleep(1000); // very bad technique
[Link](th2 + "is alive "+ [Link]());
[Link](); // we will be again into action after th2 finishes it's
action
//[Link](100); // I can wait only for 100 ms
[Link](th2 + "is alive "+ [Link]());
}
}

class MyThr4 extends Thread{


// we are using a constructor so that we can force to set the
name
// for thread
public MyThr4(String name){
setName(name);
}
public void run(){
for(int i= 0;i <10; i++){
[Link]([Link]());
try{
sleep(22);
}catch(Exception e){}
}
}
}

OUTPUT:
E:\THREAD>javac [Link]

E:\THREAD>java Thr4
Thread[thread two,10,main]is alive true
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread two,10,main]
TEKZUNE TECHNOLOGIES 338

Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,main]
Thread[thread one,1,main]
Thread[thread three,5,main]
Thread[thread two,10,]is alive false
Thread[thread two,10,]is alive false

/*157. Program to demonstrate how threads can beused to


animate the things. Here we animate a banner text.*/

import [Link].*;

class Banner extends Frame implements Runnable


{
String str=" ORBIT TECHNOLOGIES ITC PVT ";

Banner()
TEKZUNE TECHNOLOGIES 339

{
setLayout(null);
setBackground([Link]);
setForeground([Link]);
}

public void paint(Graphics g)


{
Font f=new Font("Courier", [Link], 40);
[Link](f);
[Link](str, 10,100);
}

public void run()


{
for(;;)
{
repaint();
try
{
[Link](400);

}catch(InterruptedException ie) {}
char ch=[Link](0); //Extract first character from string
str = [Link](1,[Link]()); //add to str from second
str=str+ch; //attach first character at the end of str
}
}

public static void main(String args[])


{
Banner b=new Banner();
[Link](400,400);
[Link]("My Banner");
[Link](true);
Thread t=new Thread(b);
[Link]();
}
}
TEKZUNE TECHNOLOGIES 340

GRAPHICS PROGRAMMING USING AWT

Abstract Window Toolkit(AWT):


This represents a class library to develop applications using GUI.
The [Link]. package got classes and interfaces to develop GUI
and let the user interact in a more friendly way with the
applications.

Component: A component represents an object which is


displayed pictorially on the screen.

For example, we create an object of Button class as:


TEKZUNE TECHNOLOGIES 341

Button b=new Button();

Now, b is the object of Button class. If we display this b on the


screen, it displays a push button. Therefore, the object b,on
going to the screen is becoming a component called 'push
button'.

CLASSES OF AWT

A Window and a Frame on Monitor

A window represents any imaginary rectangular area on the


screen without any borders or title bar.
TEKZUNE TECHNOLOGIES 342

Where as Frame represents a window with some title and


borders. Any application, we create frames to represent various
screen like input screens where the user can type some data
for the application and output screens where the result may be
displayed in a particular form. Such screens are nothing but
frames only.

Event Delegation Model:


When we create a component, generally the component is
displayed on the screen but is not capable of performing any
actions, even when someone clicks on it. But the user
expectations will be different. A user wants the push button to
perform some action. Hence, he clicks on the button. Clicking,
double clicking, typing data inside the component, mouse over
etc. are all examples of events.
TEKZUNE TECHNOLOGIES 343

Event delegation model represents that when an event is


generated by the user on a component, it is delegated to a
listener interface and the listener calls a method in response to
the event. Finally, the event is handled by the method.

The following steps are involved in event delegation model:

1) We should attach an appropriate listener to a component.


This is done using addxxxListener() method. Similarly, to
remove a listener from a component, we can use
removexxxListener() method.
2) Implement the methods of the listener, especially the
method which handles the event.

3) When an event is generated on the component, then the


method in step 2 will be executed and the event is handled.
TEKZUNE TECHNOLOGIES 344

Advantages of Event Delegation Model:

1) The component and the action parts can be developed in


two seperate environments.

For example, we can create the component in Java and the


action logic can be developed in VisualBasic.

2) We can modify the code for creating the component without


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

Uses of a Frame

Once, the frame is created, we can use it for any of the


purposes mentioned below:

1) To draw some graphical shapes like dots, lines, rectangles,


etc in the frame.
2) To display some text in the frame.
3) To display some text in the frame.
4) To display component like push buttons, radio buttons, etc.
in the frame.
TEKZUNE TECHNOLOGIES 345

A frame with initial size of 0 pixels width 0 and 0 pixels height


will be created, which is not visible on the screen.

Pixel: A pixel represents any single point or dot on the screen.


Any data or picture which are displayed on the screen are
composed of several dots called ‘pixels’.

Monitors can accommodate 800 pixels horizontally and 600


pixels vertically. So the total size on the screen is
800*600=480,000 pixels.
TEKZUNE TECHNOLOGIES 346
TEKZUNE TECHNOLOGIES 347

/*158. Program to create a simple 'Frame'*/


import [Link].*;
class MyFrame
{
public static void main(String args[])
{
//Create a frame
Frame f=new Frame("My Awt Frame");

//Set the size of the frame


[Link](300,250);

//Display the frame


[Link](true);
}}
TEKZUNE TECHNOLOGIES 348

OUTPUT:

/*159. Program to create a frame by creating an object to


the subclasses of Frame class.*/

import [Link].*;
class MyFrame1 extends Frame
{

//call super class constructor to store title


MyFrame1(String str)
{
super(str);
}

public static void main(String args[])


{
TEKZUNE TECHNOLOGIES 349

//Create a frame with title


MyFrame1 f=new MyFrame1("My Awt Frame");

//Set the size of the frame


[Link](300,250);

//Display the frame


[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 350

/*160. Program to first create a frame and then closes it


on clicking the close button*/

import [Link].*;
import [Link].*;
class MyFrame2 extends Frame
{
public static void main(String args[])
{
//Create a frame with title
MyFrame2 f=new MyFrame2();

//set the title


[Link]("My Awt Frame");

//set the size of the frame


[Link](300,250);

//Display the frame


[Link](true);

//close the frame


[Link](new Myclass());
}
}
class Myclass implements WindowListener
{
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e)
{
[Link](0);
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 351

WindowAdapter

WindowAdapter: It is a class in [Link] package,


package that contains all the methods of the WindowListener
interface with an empty implementation (body). If we can extend
Myclass from this WindowAdapter class, then we need not write
all the methods with empty implementation. We can write only
that method which interests us.

/*161. Program to close the frame using WindowAdapter


class*/

import [Link].*;
import [Link].*;
class MyFrame3 extends Frame
TEKZUNE TECHNOLOGIES 352

{
public static void main(String args[])
{
//create a frame with title
MyFrame3 f=new MyFrame3();

//set a title for the frame


[Link]("My Frame");

//set the size of the frame


[Link](300,250);

//display the frame


[Link](true);

//close the frame


[Link](new Myclass());
}
}

class Myclass extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 353

/*162. Program to display some text in the frame using


drawString*/
import [Link].*;
import [Link].*;
class Message extends Frame
{
//this is constructor
Message()
{
//close the frame when close button clicked
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
TEKZUNE TECHNOLOGIES 354

});
} //end of constructor

public void paint(Graphics g)


{
//set background color for frame
[Link](new Color(100,20,20));

//set font for the text


Font f=new Font("Arial",[Link]+[Link],30);
[Link](f);

//set foreground color


[Link]([Link]);

//display the message


[Link]("Hello, How are U?",100,100);
}
public static void main(String args[])
{
Message m=new Message();
[Link](400,300);
[Link]("This is my text");
[Link](true);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 355

/*
TextField: A TextField represents a long rectangular box where
the user can type a single line of text. We can also display a line
of text in the text field also.

TextArea: A TextArea is similar to a text field, but it can


accommodate several lines of text.

Label: A Label is a constant text that is generally displayed along


with a TextField or TextArea.
*/

/*163. Program to create two labels and two text fields for
entering name and passwords. The password typed by the
user in the text field is hidden*/
TEKZUNE TECHNOLOGIES 356

import [Link].*;
import [Link].*;

class MyText extends Frame implements ActionListener


{
//variables
TextField name,pass;

MyText()
{
//set layout to flow layout
setLayout(new FlowLayout());

//create 2 labels
Label n=new Label("Name:", [Link]);
Label p=new Label("Password:", [Link]);

//create text fields for name and password


name=new TextField(20);
pass=new TextField(20);

//hide the password by stars '******'


[Link]('*');

//use background,foreground colors and font for name textfield


[Link]([Link]);
[Link]([Link]);
Font f=new Font("Arial",[Link],25);
[Link](f);

//add the labels and textfields to frame


add(n);
add(name);
add(p);
add(pass);

//add action listener to textfield


[Link](this);
[Link](this);
TEKZUNE TECHNOLOGIES 357

//close the window


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});

} //end of constructor

//this method is executed when enter is clicked


//display the text entered into the text fields
public void actionPerformed(ActionEvent ae)
{
//create Graphics class object
Graphics g=[Link]();

[Link]("Name:" +[Link](),20,100);
[Link]("Password" +[Link](),30,150);
}

public static void main(String args[])


{
//create the frame
MyText mt=new MyText();
[Link]("My text field");
[Link](400,400);
[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 358

/*164. Program for creating 3 push buttons having names


of 3 colors. When a button is clicked, that particular color
is set as background color in the frame.*/

import [Link].*;
import [Link].*;
class Mybuttons extends Frame implements ActionListener
{
//variables
Button b1,b2,b3;

//constructor
Mybuttons()
{
//do not set any layout
[Link](null);
TEKZUNE TECHNOLOGIES 359

//create 3 push buttons


b1=new Button("Yellow");
b2=new Button("Blue");
b3=new Button("Cyan");

//set the locations of buttons in the frame


[Link](100,100,70,40);
[Link](100,160,70,40);
[Link](100,220,70,40);

//add the buttons to the frame


[Link](b1);
[Link](b2);
[Link](b3);

//add action listener to the buttons


[Link](this);
[Link](this);
[Link](this);

//close the frame


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});

} //end of constructor

//this method is called when a button is clicked


public void actionPerformed(ActionEvent ae)
{
//know the label of the button clicked by user
String str=[Link]();

//change the frame's background color depending on


the button clicked
TEKZUNE TECHNOLOGIES 360

if([Link]("Yellow"))
[Link]([Link]);
if([Link]("Blue")) [Link]([Link]);
if([Link]("Cyan")) [Link]([Link]);
}

public static void main(String args[])


{
//create the frame
Mybuttons mb=new Mybuttons();
[Link](400,400);
[Link]("My Buttons");
[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 361

/*setLayout(): This method is useful to set a layout for the


frame.

What is layout: A layout represents a manner of arranging


components in the frame. All are represented as implementation
classes of LayoutManager interface.

The following layouts are available in AWT:

1)FlowLayout
2)BorderLayout
3)GridLayout
4)CardLayout
5)GridBagLayout
6)BoxLayout

FlowLayout: We use FlowLayout manager to arrange the


components in the frame ina line one after the other. When a line
is filled with components, automatically the components are
arranged into the second line. When we use some layout manager
like this, there is no need to use setBounds() method to specify
the location of push buttons.
*/

/*165. Program to create push button, arrange them using


FlowLayout manager and setting the background color for
the frame depending on the button clicked by the user.*/

import [Link].*;
import [Link].*;
class Mybutton1 extends Frame implements ActionListener
{
//variables
Button b1,b2,b3;

//constructor
Mybutton1()
TEKZUNE TECHNOLOGIES 362

{
//do not set any layout
setLayout(new FlowLayout());

//create 3 push button


b1=new Button("Yellow");
b2=new Button("Blue");
b3=new Button("Green");

//add the button to the frame


add(b1);
add(b2);
add(b3);

//add action listener to the buttons


[Link](this);
[Link](this);
[Link](this);

//close the frame


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
} //end of contructor

//this method is called when a button is clicked


public void actionPerformed(ActionEvent ae)
{
//know the button clicked by user

if([Link]()==b1) setBackground([Link]);
if([Link]()==b2) setBackground([Link]);
if([Link]()==b3) setBackground([Link]);
}
TEKZUNE TECHNOLOGIES 363

public static void main(String args[])


{
//create the frame
Mybutton1 mb=new Mybutton1();
[Link](400,400);
[Link]("My buttons");
[Link](true);
}

OUTPUT:
TEKZUNE TECHNOLOGIES 364

Drawing in the Frame


Graphics class of [Link] package has the following methods
which help to draw various shapes.

1) drawLine(int x1,int y1,int x2,int y2)


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

2) drawRect(int x,int y,int w,int h)


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

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


method is same above with two additional features. Here
rounding is specified by arcw and arch. arcw represents
horizontal diameter of the arc at the corner and arch represents
vertical diameter of the arc at the corner.

4) drawOval(int x,int y,int w,int h):This method draws a circle or


ellipse bounded in the region of a rectangle staring at (x,y) with
width w and height h.

5) drawArc(int x,int y,int w,int h,int sangle,int aangle): Draws an


arc bounded by a rectangle region of (x,y), with width w and
height h. Here, sangle represents the arc angle relative to start
angle. sangle+aangle=end angle. If sangle is positive, the arc is
drawn counter clock wise and if it is negative, then it is drawn
clockwise.
*/

/*166. Program to draw smiling face */


import [Link].*;
import [Link].*;

class Draw1 extends Frame


{
Draw1()
{
TEKZUNE TECHNOLOGIES 365

//close the frame


[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}

});

//to refresh the frame contents


public void paint(Graphics g)
{
//set blue color for drawing
[Link]([Link]);

//display a rectangle to contain drawing


[Link](40,40,200,200);

//face
[Link](90,70,80,80);

//eyes
[Link](110,95,5,5);
[Link](145,95,5,5);

//nose
[Link](135,95,130,115);

//mouth
[Link](113,115,35,20,0,-180);
}

public static void main(String args[])


{
//create the frame
Draw1 d=new Draw1();
TEKZUNE TECHNOLOGIES 366

//set the size and title


[Link](400,400);
[Link]("My Drawing");

//display the frame


[Link](true);
}
}

OUTPUT

/* Filling with Colors


To fill any shape with a desire color, first of all we should set a
color using setColor() method. Then any of the following methods
will draw those respective shapes by filling with the color.
TEKZUNE TECHNOLOGIES 367

1) fillRect(int x,int y,int w,int h): This method draws a rectangle


and fills it with the specified color.

2)fillRoundRect(int x,int y,int w,int h,int arcw,int arch): This


method draws filled rectangle with rounded corners.

3)fillOval(int x,int y,int w,int h): This method is useful to create an


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

4)fillArc(int x,int y,int w,int h,int sangle,int aangle): This method is


useful to draw an arc and fills it with a specified color.

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


polygon with a specified color.
*/

/167. Program for drawing a smiling face in a frame with


filled colors */
import [Link].*;
import [Link].*;
class Draw2 extends Frame
{
Draw2()
{
//close the frame
[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}

public void paint(Graphics g)


{
//set blue color
[Link]([Link]);
TEKZUNE TECHNOLOGIES 368

//display a rectangle to contain drawing


[Link](40,40,200,200);

//set yellow color


[Link]([Link]);

//face
[Link](90,70,80,80);

//set black color


[Link]([Link]);

//eyes
[Link](110,95,5,5);
[Link](145,95,5,5);

//nose
[Link](130,95,130,115);

//set red color


[Link]([Link]);

//mouth
[Link](113,115,35,20,0,-180);
}

public static void main(String args[])


{
//create the frame
Draw2 d=new Draw2();

//set the size and title


[Link](300,250);
[Link]("MyDrawing");

//display the frame


[Link](true);
}
TEKZUNE TECHNOLOGIES 369

OUTPUT:

/*168. Program to create a polygon that is filled with


green color.*/
import [Link].*;
import [Link].*;
class DrawPoly extends Frame
{
DrawPoly()
{
TEKZUNE TECHNOLOGIES 370

//Close the frame


[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}

public void paint(Graphics g)


{
//set red color
[Link]([Link]);

//display a filled rounded rectangle


[Link](30,30,250,250,30,30);

//set green color


[Link]([Link]);

//take x and y coordinates in arrays


int x[]={40,200,40,100};
int y[]={40,40,200,200};

//there are 4 pairs of x,y coordinates


int num=4;

//create filled polygon connecting the coordinates


[Link](x,y,num);
}
public static void main(String args[])
{
//create the frame
DrawPoly d=new DrawPoly();

//set the size and title


[Link](400,400);
[Link]("My Polygon");
TEKZUNE TECHNOLOGIES 371

//display the frame


[Link](true);
}
}
OUTPUT:

/*[Link] to create HOME with moon at back ground*/


import [Link].*;
import [Link].*;

class Home extends Frame


{
Home()
{
[Link](new WindowAdapter()
{
TEKZUNE TECHNOLOGIES 372

public void windowClosing(WindowEvent e)


{
[Link](0);
}
});
}

public void paint(Graphics g)


{
//store x,y coordinates in x[] and y[]
int x[]={375,275,475};
int y[]={125,200,200};
int n=3; //no. of pairs

//set gray background for frame


[Link]([Link]);

//set yellow color for rectangle - house


[Link]([Link]);

//set color yellow for rectange- house


[Link]([Link]);
[Link](300,200,150,100);

//set blue color for another rectangle - door


[Link]([Link]);
[Link](350,210,50,60);

//draw a line - line below the door


[Link](350,280,400,280);

//set dark gray for polygon - roof


[Link]([Link]);
[Link](x,y,n);

//set cyan color for oval - moon


[Link]([Link]);
[Link](100,100,60,60);
TEKZUNE TECHNOLOGIES 373

//set green for arcs- grass


[Link]([Link]);
[Link](50,250,150,100,0,180);
[Link](150,250,150,100,0,180);
[Link](450,250,150,100,0,180);

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


[Link](50,300,600,300);

//display some text


[Link]("My Happy Home",275,350);
}

public static void main(String args[])


{
//create the frame
Home h=new Home();

//set the size and title


[Link](500,400);
[Link]("My Home");

//display the frame


[Link](true);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 374

/*170. Program to display all available fonts in the current


working system.*/

import [Link].*;
import [Link].*;

class Fonts
{
public static void main(String args[])
{
//get the local graphics environment information into
//GraphicsEnvironment object ge
GraphicsEnvironment
ge=[Link]();

//From ge, get available font family names into fonts[]


String fonts[]=[Link]();
TEKZUNE TECHNOLOGIES 375

[Link]("Available fonts on this system:");

//retrieve one by one the font names from fonts[] and display
for(int i=0;i<[Link];i++)
[Link](fonts[i]);

}
}
OUTPUT:

E:\>javac [Link]

E:\>java Fonts
Available fonts on this system:
Aharoni
Andalus
Angsana New
AngsanaUPC
Aparajita
Arabic Typesetting
Arial
Arial Black
…….

/*To know which key is pressed on the keyboard, we can take the
help of KeyListener interface.*/

/*171. Program to trap the key code and key name typed
by the user on the keyboard and display them in a text
area.*/

import [Link].*;
import [Link].*;

class Keys extends Frame implements KeyListener


TEKZUNE TECHNOLOGIES 376

{
//variables
TextArea ta;
String msg=" ";

Keys()
{
//set the flow layout
setLayout(new FlowLayout());

//create a text area to display the key code


ta=new TextArea(5,25);

//set some font and foreground color to text area


Font f=new Font("Sansserif",[Link],25);
[Link](f);
[Link]([Link]);

//add text area to frame


add(ta);

//add key listener to text area


[Link](this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});

} //End of constructor

public void keyPressed(KeyEvent ke)


{
//get the code of the key pressed
int keycode=[Link]();
msg+="\n Key code:" + keycode;
TEKZUNE TECHNOLOGIES 377

//get the name of the key from the code


String keyname=[Link](keycode);
msg+="\n key pressed:" + keyname;

//display the key code and key name in text area


[Link](msg);
msg="";
}

public void keyTyped(KeyEvent ke)


{}

public void keyReleased(KeyEvent ke)


{
//get the key code released
int keycode=[Link]();
msg+="\n Key code:" + keycode;

//get the name of the key from the code


String keyname=[Link](keycode);
msg+="\n key pressed:" + keyname;

//display the key code and key name in text area


[Link](msg);
msg="";
}

public static void main(String args[])


{
//create the frame
Keys ks=new Keys();
[Link]("Catch the keys");
[Link](400,400);
[Link](true);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 378

/*172. Program to display an Image in the frame and also


in the title bar of the frame*/
import [Link].*;
import [Link].*;
class Images extends Frame
{
//take a static type Image class object
static Image img;

//constructor
Images()
{
//load an image into Image object
img=[Link]().getImage("[Link]");
TEKZUNE TECHNOLOGIES 379

//wait till the image is loaded into img object for this purpose,
//create MediaTracker
MediaTracker track=new MediaTracker(this);

//add image to MediaTracker


[Link](img,0);
try
{
//let the JVM wait till the the image is loaded completely
[Link](0);
}catch(InterruptedException ie){}

//close the frame


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
public void paint(Graphics g)
{
//display the image in the frame at 50,50 pixels
[Link](img,50,50,null);
}

public static void main(String args[])


{
//create the frame
Images i=new Images();

//set the size and title


[Link](500,400);
[Link]("My images:");

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


[Link](img);
TEKZUNE TECHNOLOGIES 380

//display the frame


[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 381

List Class: This class is useful to create a list box which is similar
to choice menu. A list box presents the user with a scrolling of
text items. The user can select one or more items from the
list box*/

/*173. Program to create List box with names of some


languages from where the user can select one or more
items*/

import [Link].*;
import [Link].*;
class MyList extends Frame implements ItemListener
{
//variables
int[] msg;
List lst;

MyList()
{
//set flow layout manager
setLayout(new FlowLayout());

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


//and multiple selection is also enabled
lst=new List(4,true);

//add items to the list box


[Link]("English");
[Link]("Hindi");
[Link]("Telugu");
[Link]("Maths");
[Link]("Science");
[Link]("Social");

//add the list box to the frame


add(lst);

//add item listener to the list box


TEKZUNE TECHNOLOGIES 382

[Link](this);

//frame closing
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}

public void itemStateChanged(ItemEvent ie)


{
//call the paint method
repaint();
}

public void paint(Graphics g)


{
[Link]("Selected languages:",100,200);

//get the selected items position number into msg[]


msg=[Link]();

//know each selected item's name and display


for(int i=0;i<[Link];i++)
{
String item=[Link](msg[i]);
[Link](item,100,220+i*20);
}
}

public static void main(String args[])


{
//creat the frme
MyList ml=new MyList();
[Link]("My List Box");
[Link](400,400);
TEKZUNE TECHNOLOGIES 383

[Link](true);
}
}
OUTPUT:

/*Radio Button: A radio button represents a round shaped


button, such that only one can be selected from a group of
buttons. Radio buttons can be created using CheckboxGroup class
and Checkbox classes.*/

/*174. Example program on ‘Radio Button’. */


import [Link].*;
import [Link].*;

class MyRadio extends Frame implements ItemListener


{
TEKZUNE TECHNOLOGIES 384

//variables
String msg="";
CheckboxGroup cbg;
Checkbox y,n;

//constructor
MyRadio()
{
//set the layout to flow layout
setLayout(new FlowLayout());

//create CheckboxGroup object


cbg=new CheckboxGroup();

//create 2 radio buttons


y=new Checkbox("Yes",cbg,true);
n=new Checkbox("No",cbg,false);

//add the radio buttons to frame


add(y);
add(n);

//add item listener to the radio buttons


[Link](this);
[Link](this);

//close the frame


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
} //End of constructor

//this method is called when a radio button is clicked


public void itemStateChanged(ItemEvent ie)
{
TEKZUNE TECHNOLOGIES 385

repaint(); //call paint() method


}

//display the selected radio button


public void paint(Graphics g)
{
msg="Current Selection:";
msg+=[Link]().getLabel();
[Link](msg,10,100);
}

public static void main(String args[])


{
//create the frame
MyRadio mr=new MyRadio();
[Link]("My Radio Buttons");
[Link](400,400);
[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 386

/*Scrollbar class: It is useful to create scrolbars that can be


attached to a frame or text area.
Scrollbars are used to select continuous values between a
specified minimum and maximum.
Scrollbars can be arranged vertically or horizontally.
*/

/*175. Program to create a vertical scrollbar with scroll


button length 30 px and with the starting and ending
positions ranging from 0 to 400px.*/

import [Link].*;
import [Link].*;
TEKZUNE TECHNOLOGIES 387

class MyScroll extends Frame implements AdjustmentListener


{
//variables
String msg="";
Scrollbar s1;

MyScroll()
{
//do not set any layout
setLayout(null);

//create vertical scrollbar


s1=new Scrollbar([Link],0,30,50,400);

//set the location of scrollbar in the frame


[Link](250,50,30,200);

//add it to frame
add(s1);

//ad adjustment listenerto scrollbar


[Link](this);

//frame closing
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}

public void paint(Graphics g)


{
TEKZUNE TECHNOLOGIES 388

//display the position of scrollbar


[Link]("SCROLLBAR POSITION:",20,150);
msg+=[Link]();
[Link](msg,20,180);
msg="";
}
public static void main(String args[])
{
//create the frame
MyScroll ms=new MyScroll();
[Link]("My Scroll bar");
[Link](400,400);
[Link](true);
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 389

/*176. Program to perform addition of two numbers*/


import [Link];
import [Link].*;
import [Link].*;
/*
<APPLET
CODE=[Link]
WIDTH=290
HEIGHT=200 >
</APPLET>
*/
public class Add extends Applet implements ActionListener {
TextField text1, text2, text3;
Label addlabel;
Button b1;
public void init(){
text1 = new TextField(10);
add(text1);
addlabel = new Label("+");
add(addlabel);
text2 = new TextField(10);
add(text2);
b1 = new Button("=");
add(b1);
[Link](this);
text3 = new TextField(10);
add(text3);
}
public void actionPerformed(ActionEvent e) {
if([Link]() == b1){
int sum = [Link]([Link]()) +
[Link]([Link]());
[Link]([Link](sum));
}}}
OUTPUT:
TEKZUNE TECHNOLOGIES 390

/*177. Program to a frame 'Frame1' with Next and Close buttons.


Note: DO NOT COMPILE THIS CODE TILL FRAME2. JAVA IS
COMPILED.*/

import [Link].*;
import [Link].*;

class Frame1 extends Frame implements ActionListener


{
//variables
Button b1,b2;

Frame1()
{
setLayout(null);

//create two buttons


TEKZUNE TECHNOLOGIES 391

b1=new Button("Next");
b2=new Button("Close");

//set the location of buttons


[Link](100,100,70,40);
[Link](200,100,70,40);

//add them to frame


add(b1);
add(b2);

//add action listener to buttons


[Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent ae)


{
//if Next button is clicked, display Frame2
if([Link]()==b1)
{
//create Frame2 object and display
Frame2 f2=new Frame2(10,"Junaid");
[Link](400,400);
[Link](true);
}

else
{
//if closed button is clicked, then close application
[Link](0);
}
}

public static void main(String args[])


{
//create Fram1
Frame1 f1=new Frame1();
[Link](500,500);
TEKZUNE TECHNOLOGIES 392

[Link]("First frame");
[Link](true);
}
}

/*Program to create Frame2 with Back button, such that when


the user clicks Back button, Fram2 is closed.*/

import [Link].*;
import [Link].*;

class Frame2 extends Frame implements ActionListener


{

int rno;
String name;

//create a button
Button b;

Frame2(int rno,String name)


{
[Link]=rno;
[Link]=name;

//set layout to flow layout


setLayout(new FlowLayout());

//create the button


b=new Button("Back");

//add it to frame
add(b);

//add action listener to button


[Link](this);
}

public void actionPerformed(ActionEvent ae)


TEKZUNE TECHNOLOGIES 393

{
//remove this frame from memory
[Link]();
}
}
OUTPUT:

/*
Choice: Choice class is useful to display a choice menu. It is a
pop-up list of items and the user can select only one item from
the available items.
*/

/*178. Program to create a choice menu with names of some


languages from where the user has toselect any one item. The
selected item must also be displayed in the frame.*/
TEKZUNE TECHNOLOGIES 394

import [Link].*;
import [Link].*;
class MyChoice extends Frame implements ItemListener
{
//variables
String msg;
Choice ch;

MyChoice()
{
//set flow layout to frame
setLayout(new FlowLayout());

//create a new empty choice menu


ch=new Choice();

//add some items to choice menu, here we are adding items to choice class
[Link]("English");
[Link]("Hindi");
[Link]("Telugu");
[Link]("Sanskrit");
[Link]("French");

//add the choice menu to frame


add(ch);

//add item listener to choice menu


[Link](this);

//close the frame


addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
TEKZUNE TECHNOLOGIES 395

//this method is called when any item is clicked


public void itemStateChanged(ItemEvent ie)
{
//call paint() method
repaint();
}

//display selected item from the choice menu


public void paint(Graphics g)
{
[Link]("Selected language:",10,100);
msg=[Link]();
[Link](msg,10,120);
}

public static void main(String args[])


{
//create a frame
MyChoice mc=new MyChoice();
[Link]("My Choice box");
[Link](400,400);
[Link](true);
}
}

OUTPUT:
TEKZUNE TECHNOLOGIES 396

/*179. Program to develop login application using AWT*/

import [Link].*;
import [Link].*;

class MyFrame extends Frame implements ActionListener{


Button ok, close;
TextField name, password;

MyFrame(){
setLayout(new FlowLayout());
ok = new Button("Ok");
[Link](60,70);
close = new Button("Close");
TEKZUNE TECHNOLOGIES 397

[Link](70,70);
name = new TextField();
[Link](60,60);
password = new TextField();
[Link](60,60);
[Link]('*');

[Link](name);
[Link](password);
[Link](ok);
[Link](close);

[Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent ae){


if([Link]() == close){
[Link](0);
}
if([Link]().equals("orbit")&&
[Link]().equals("orbit")){
MyFrame2 frame2 = new MyFrame2([Link]());
[Link](300,400);
[Link](true);
}
else{
[Link]("invalid user name or password");
}

public static void main(String [] args){


MyFrame frame = new MyFrame();
[Link](300, 300);
[Link](true);

}
}
TEKZUNE TECHNOLOGIES 398

import [Link].*;
import [Link].*;

class MyFrame2 extends Frame implements ActionListener{


Label nLabel, aLabel, cLabel, gLabel, hLabel;
Label hcLabel, hbLabel, hsLabel, mLabel, fLabel;
TextField nTextField, aTextField;
Button back;
CheckboxGroup obj;
Checkbox cCheck, bCheck, sCheck, mCheck, fCheck;
List cityList;

MyFrame2(String name){
setLayout(new FlowLayout());

nLabel = new Label("name", [Link] );


aLabel = new Label("age", [Link]);
gLabel = new Label("gender", [Link]);
hLabel = new Label("hobbies", [Link]);
cLabel = new Label("city", [Link]);
hcLabel = new Label("cricket");
hbLabel = new Label("boxing");
hsLabel = new Label("swimming");
mLabel = new Label("male");
fLabel = new Label("female");

nTextField = new TextField(name);


aTextField = new TextField();

back = new Button("back");

cCheck = new Checkbox();


sCheck = new Checkbox();
bCheck = new Checkbox();

obj = new CheckboxGroup();


mCheck = new Checkbox("male", obj, true);
TEKZUNE TECHNOLOGIES 399

fCheck = new Checkbox("female", obj, false);

cityList = new List(1, true);


[Link]("Hyderabad");
[Link]("Banglore");
[Link]("Chennai");
[Link]("Mumbai");
[Link]("Mysore");

add(nLabel);
add(nTextField);
add(aLabel);
add(aTextField);

add(gLabel);
add(mCheck);
add(fCheck);

add(hLabel);
add(cCheck);
add(hcLabel);
add(bCheck);
add(hbLabel);
add(sCheck);
add(hsLabel);

add(cLabel);
add(cityList);

add(back);

[Link](this);
}

public void actionPerformed(ActionEvent ae){


[Link]();
}
}
OUTPUT:
TEKZUNE TECHNOLOGIES 400
TEKZUNE TECHNOLOGIES 401
TEKZUNE TECHNOLOGIES 402

APPLETS
APPLETS: When a HTML(Hyper Text Markup Language) page wants to
communicate with the user on Internet, it can use a special Java program,
called 'applet' to communicate and respond to the user. The user can
interact by typing some details or by clicking the components available in
the applet program. The program then processes and displays the results.

We can understand an applet as a Java byte code embedded in a HTML page,


generally for the purpose of achieving communication
with the user.
We can think of an applet as:

Applet= Java byte code + HTML page

Creation of Applet

To create an applet, we need to write a Java program and compile it to get


byte code. Then we should embed(include) it into a HTML page on a
particular location wherever we want it to be displayed. This page is then
stored in the web server. A client machine communicates with the web
server, the server then sends the HTMpage that contains the applet. The
page is then tranmitted to the client where the applet is executed on the
client's web browser. Thus applets are executed at client side by the web
browser.
Thus applets travel thousands of kilometers of distance on Internet and
reach the client mahcines before their execution on the client.

To create an applet, we have Applet class of [Link] package and JApplet


class of [Link] package. These classes user the
following methods, which are automatically run by any applet program.

1)public void init(): This method is the first method to be called by the
browser and it is executed only once. So, the pogamme can use this method
to initialize any variables, creating components and creating threads. ets.

2) public void start(): This method is called after init() mehtod and each time
the applet is revisited by the user.
For example, the user has minimized the web page that contains the applet
and moved to anther pae then this method's execution is stopped. When the
user comes back to view the web page again, start() method execution will
resume. Any calculations and processing of data should be done in this
method and the results are also displayed.
TEKZUNE TECHNOLOGIES 403

3)public void stop(): This method is called by the browser when the applet is
to be stopped. If the user minimizes the web page, then this method is
[Link] this way, start() and and stop() methods cab be called repeatedly.

4)public void destroy(): This method is called when the applet is being
terminated from memory. The stop() method will always be called before
destroy().

Executing init(), start(), stop() and destroy() methods in that sequence is


called 'life cycle of an applet'.

Note: Here 'public static void main(String args[])' method is not available in
case of applet. This means, we can compile the applet code but we can not
run it using a JVM.

Once the applet is created, we compile and obtain its byte code. This byte
code is embedded in HTML pae and the page is sent to the client compute.
The client machine browser like Internet explorer, Netscape Navigator or
Mozilla Firefox where the HTML page is viewed by the user. The browser will
execute the applet of the HTML page is viewed by the user. The browser
contains a small virtual machine called 'applet engine' which understands
and runs the applet code.

An applet can show images and animation, play sounds, take user input and
send it to the server, etc.
Applets cannot interact and spoil the resources of the client system and
hence they are harmless.

Uses of Applets:
1) Applets can be used on Internet for multiple purposes.
There are two types of web pages:
a) Static web pages: It provide some information to the user but the user
cannot interact with the web page other than viewing the information.
Dynamic webpages interact with the user at the runtime.
For example, a student can type his hall ticket number in a text field and
click the retrieve button to get back his results from his University
[Link] are useful to provide such interaction with the user at runtime

2) Another use of Applets is for creating animation and games where the
images can be displayed or moved giving a visulal impression that they are
alive.

<APPLET> tag
<APPLET> tag is useful to embed an applet intoan HTML page. It has the
following form:
TEKZUNE TECHNOLOGIES 404

<APPLET CODE="name of the applet class file" CODEBASE="path of the


applet class file" HEIGHT=maximum height of the applet in pixels
WIDTH=maximum width of the applet in pixels
ALIGN=(LEFT,RIGHT,TOP,BOTTOM,CENTER)
ALT=alternate text to be displayed>

<PARAM NAME=parameter name VALUE=its value>


</APPLET>
The <PARAM> tag is useful to define a variable (parameter) and its value
inside the HTML page which can be passed to the applet.

/*180. A program to create a simple Applet*/

import [Link].*;
import [Link].*;

public class MyApplet extends Applet


{
//Set the background color for the frame
public void init()
{
setBackground([Link]);
}
//Display message in applet window
public void paint(Graphics g)
{
[Link]("Hello Applets!", 50,50);
}
}

//[Link]
<! [Link] that embeds App1 applet>
<html>
<applet code="[Link]" height=300 width=400>
</applet>
</html>
OUTPUT:
TEKZUNE TECHNOLOGIES 405

/*181. Another example program on Applet creation */


import [Link].*;
import [Link].*;

public class MyApplet1 extends Applet


{
//variables
String msg="";

//This method is executed when an applet is loaded


public void init()
{
//set background color for applet frame
setBackground([Link]);

//Set foreground color for text in frame


TEKZUNE TECHNOLOGIES 406

setForeground([Link]);

//Set font for text in applet


Font f=new Font("Arial",[Link],20);
setFont(f);
//store method name in msg
msg+=" init ";
}

//This method is executed after init()


public void start()
{
//add this method name to msg
msg+=" start ";
}
//to stop applet
public void stop()
{
//Add this method name to msg
msg+=" stop ";
}

//To remove applet from memory


public void destroy()
{
//add this method name to msg
msg+= " destroy ";
}

public void paint(Graphics g)


{
[Link](msg, 50,50);
}
}
//[Link]
<html>
<applet code="[Link]" height=200 width=300>
</applet>
</html>
TEKZUNE TECHNOLOGIES 407

OUTPUT:

Passing parameters to Applet:


The APPLET tag in HTML allows you to pass parameters to your
applet.
To retrieve a parameter, use the getParameter() method. It
returns the value of the specified parameter in the form of a
String object.
Thus, for numeric and boolean value, you will beed to convert
their string representations into their internal formats.

/*182. Program to create an Applet using Parameter */


import [Link].*;
import [Link].*;

public class ParamDemo extends Applet


TEKZUNE TECHNOLOGIES 408

{
String fontName;
int fontSize;
float leading;
boolean active;

//Initialize the string to be displayed


public void start()
{
String param;

fontName=getParameter("fontName");
if(fontName==null)
fontName="Not Found";

param=getParameter("fontSize");
try
{
if( param!=null) //If not found
fontSize=[Link](param);
else
fontSize=0;
}
catch(NumberFormatException e)
{
fontSize=-1;
}
param=getParameter("leading");
try
{
if(param!=null) //if not found
leading=[Link](param).floatValue();

else
leading=0;
}
catch(NumberFormatException e)
{
leading=-1;
TEKZUNE TECHNOLOGIES 409

param=getParameter("accountEnabled");
if(param!=null)
active=[Link](param).booleanValue();
}

//Display parameters
public void paint(Graphics g)
{
[Link]("Font name:" +fontName,0,10);
[Link]("Font size:" +fontSize,0,26);
[Link]("Leading:" +leading,0,42);
[Link]("Account Active:" +active,0,58);
}
}

/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=New Times Roman>
<param name=fontSize value=30>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/

OUTPUT:
TEKZUNE TECHNOLOGIES 410

/*183. In this program, we create a form where the user can type
his details and select items according to his requirement.*/

import [Link].*;
import [Link].*;
import [Link].*;
public class MyForm extends JApplet implements ActionListener
{
//variables
String str="", str1="",str2="";
Object x[];
JLabel n,a,i,lbl;
JTextField name;
JTextArea addr;
JList lst;
TEKZUNE TECHNOLOGIES 411

JButton b1,b2;
Container c;

public void init()


{
//Create JFrame and container
JFrame jf=new JFrame();
c=[Link]();

//Display yellow background color in container


[Link]([Link]);

//Do not set any layout to c


[Link](null);

//Set the size and title for frame


[Link](500,400);
[Link]("My Form");

//Display the frame


[Link](true);

//Display heading in the frame using a label


Font f=new Font("Dialog",[Link],26);
lbl=new JLabel();
[Link](f);
[Link]([Link]);
[Link]("Z-ELECTRONIC ON LINE SHOP");
[Link](200,10,500,50);
[Link](lbl);

//TextField and a label for entering name


n=new JLabel("Name:",[Link]);
name=new JTextField(30);
[Link](50,100,100,30);
[Link](200,100,200,30);
[Link](n);
[Link](name);
TEKZUNE TECHNOLOGIES 412

//TextArea and a label for entering address


a=new JLabel("Address:",[Link]);
addr=new JTextArea(5,50);
[Link](50,150,100,30);
[Link](200,150,200,100);
[Link](a);
[Link](addr);

//List box for multiple selection


i=new JLabel("Select items:",[Link]);
String[] data={"TVs","washingmachines","DVD
players","Refrigerators"};
lst=new JList(data);
[Link](50,270,100,30);
[Link](200,270,200,100);
[Link](i);
[Link](lst);

//Adding two push buttons: Ok and cancel


b1=new JButton("OK");
b2=new JButton("Cancel");
[Link](200,400,100,30);
[Link](350,400,100,30);
[Link](b1);
[Link](b2);

//Add listeners interfaces to buttons


[Link](this);
[Link](this);
}

//This method is executed when the buttons are clicked


public void actionPerformed(ActionEvent ae)
{
//know which button is clicked
str=[Link]();

//if the button label is OK then


if([Link]("OK"))
TEKZUNE TECHNOLOGIES 413

{
//retrieve data from text field, text area and list boxes
str1=[Link]()+"\n";
str1+=[Link]()+"\n";
x=[Link]();
for(int i=0;i<[Link];i++)
str2+=(String)x[i]+"\n";

//display the data in text area


[Link](str1+str2);

//make the strings empty


str1="";
str2="";
}
else
{
//if cancel button isclicked, clear the data in the form
[Link]("");
[Link]("");
[Link]();
}
}
}
/*
<! This [Link] contains MyForm applet>
<html>
<applet code="[Link]" width=400 height=400>
</applet>
</html>

*/

OUTPUT:
javac [Link]
appletviewer [Link]
TEKZUNE TECHNOLOGIES 414

Using the Statuc Window:


In addition to displaying information in its window, an applet can
also output a message tothe 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. The status window is a
good place to give the user feedback about that is occuring in the
applet, suggest options, or possibly report some types or errors.

/*184. An applet can also output a message to the status


window of the browser */
import [Link].*;
import [Link].*;

/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
TEKZUNE TECHNOLOGIES 415

public class StatusWindow extends Applet


{
public void init()
{
setBackground([Link]);
}
//Display msg in applet window
public void paint(Graphics g)
{
[Link]("This is in the applet window.",10,20);
showStatus("This is shown in the status window.");
}
}
OUTPUT:

/*185. Program to animate an ‘Aeroplane’ image*/


import [Link].*;
import [Link].*;
import [Link].*;
TEKZUNE TECHNOLOGIES 416

public class Animate extends Applet


{
public void paint(Graphics g)
{
[Link](0,40,500,40);
Image img=getImage(getDocumentBase(),"[Link]");
[Link](0,100,500,100);
Thread t=new Thread();
for(int x=0;x<800;x++)
{
if(x==400)
{
try
{
[Link](2000);
}catch(InterruptedException ie){}
}
[Link](img,x,55,null);
try
{
[Link](20);
}catch(InterruptedException ie){}
}
}
}

//[Link]
/*
<html>
<applet code="[Link]"
width=400 height=400>
</applet>
</html>
*/

OUTPUT:
TEKZUNE TECHNOLOGIES 417
TEKZUNE TECHNOLOGIES 418

ANNOTATION
An Annotation are tags that provide additional information to the Java
compiler or Java Virtual Machine (JVM) regarding the declaration of a method,
a field, a class, or an interface.
We can also consider annotations as metadata since metadata represents
data about data. In this case, annotations represent data about classes,
methods, fields, and interfaces.

Another Definition for Annotation


-------------------------------------------
An Annotation is a tag attached to a programming element, such as a class,
interface, field, or a method to indicate some additional information about
that element, which can be verified and used by Java compiler or JVM.

While using an annotation, the @ symbol is used before it, such as


@Override, @Deprecated, or @SuppressWarnings. All annotations are
declared as the subtypes of of the Annotation interface, which is available in
the [Link] package.

The purpose of annotation is to provide additional information about the


programming elements that can be used to control the behavior of the
compiler or configuring the application at runtime by the JVM.

Consider the following Scenario:


----------------------------------------
Sometimes, while creating a program you need to provide additional
information regarding various programming elements, such as classes,
intefaces, fields, or methods.

Example:

class A
{
void method1()
{

}
}
Now, suppose that some other programmer needs to create a sub class, B, to
the A class and wants to override the method1() in the B class. Once, we
created the B class with amethod, we may want to check that this method is
really overriding the method of the A class or not, since it is posibble that the
method name in the B class might be misspelled. To check this, we needs to
attach additional information to the method in the B class as shown below
class B extends A
{
TEKZUNE TECHNOLOGIES 419

@Override
void method1()
{

}
}
In the above code, the @Override tag is used to tell the Java compiler that
the method of the B class should override the method of the A class. Now,
the compiler checks whether or not the method1() method is available in the
A class. If the method1() method is not available in the A class, then the
compiler displays an error saying that "This method is not overriding the
method of super class". Therefore, the @Override tag makes the Java
compiler check whether or not the method in B is really overriding the
method of A. This @Override tag is called an annotation.

Some of the built in Annotation are:


1. @Override
2. @SuppressWarning
3. @Deprecated
4. @Inherited
5. @Documented

@Override Annotation
The @Override annotation represents that method in the sub class should
override a method in its super class. If the sub class method does not
actually overrides the super class method, then the Java compiler displays an
error message. This annotation should be used only on methods.
To understand the @Override annotation, let's see an example program.
In this program, we create a class, named 'One' with the doSomething()
method. Another class, Two,is written as asubclass to the One class.
In class Two, we write another method called dosomething().

/*Write a program to use the @Override annotation to check whether the sub
class method really overrides the super class method or not */

class One
{
void doSomething()
{
[Link]("First Annotation Program");
}
}

class Two extends One


{
@Override
TEKZUNE TECHNOLOGIES 420

void dosomething()
{
[Link]("Always work hard ");
}
}

class Test
{
public static void main(String args[])
{
Two t=new Two();
[Link]();
}
}

@Inherited Annotation:
This annotation allows you to declare any annotation in asuper classs that
can be inherited into its sub class. It implies that once an annotation is
declared using he @Inherited annotationin the super class, the same
annotation also applies to its sub class automatically.

@Documented Annotation:
Normally annotations are not documented by the javadoc compiler; however,
if the @Documented tag is attached with an annotation, then that annotation
appears in the Application Programming Interface (API) document created by
the javadoc compiler, which then compiles the annotation.

Custom Annotation:
We can also create our own annotations in Java by using the @interface
keyword as shown below
@interface OrbitAnno
In this case, OrbitAnno is the name of the annotation that you created.
Defining an annotation is similar to defining a general interface in java. Since
an interface contains only abstract method, we can also write the values (or
members) of the annotation inthe orm of abstract methods as shown below

@interface OrbitAnno
{
int m1(); //methods
String m2();
}

In the above code, m1(),m2() are two methods which provide additional
informationto the compiler or JVM about a class, method, or interface.
TEKZUNE TECHNOLOGIES 421

To assign default values to the m1() and m2() members follow the code
below
@interface OrbitAnno
{
int m1() default 0; //methods
String m2() default "";
}

Followind code below shows how to use annotation


@OrbitAnno() //default values are used for members

@OrbitAnno(m1=10, m2="Hello") //Here we assign value

The allotted data for m1 is 10 and m2 is Hello, whcich can beretrieved later
by the Java compiler or JVM.

While writing values (abstract methods) of annotations, we should keep the


following rules in our mind:

[] Methods should no have any parameters


[] Methods should no have any throws clauses
[] Methods should return one of the following: primitive datatypes, String,
Class,enum or an array of these types

Types of Annotation
There are three types of annotation: Marker annotation, Single-value
annotation and Multi-value annotation.

Marker Annotation
-----------------------
A marker annotation is an annotation that only has a name. It does not have
any values or members associated with it. Marker annotation generally
specifies some inormaion about a class, interface,field or mehod. Example
for marker annotation

@interface MyMarker
{}
The @MyMarker tag is used to write the marker annotation.
The built-in annotation, such as @Override and @Deprecated are some of
the examples of marker annotations.

Single-Value Annotation
------------------------------
A single-value annotationis an annotation that contains only one value or
member. This member can be passed as a single value to a class, interface,
TEKZUNE TECHNOLOGIES 422

or a method. To carate a single-value annotation, we should use the


@interface tag and the annotation name, as shown

@interface MySingle
{
int m();
}
In the above code, no default value is allotted for the member m(0 of the
MySingle annotation. But we can allot some default value for the member, as
shown below
@interface MySingle
{
int m() default 1;
}

To use this annotation by providing 100 value, we can write @MySingle(100)


In this case, we are providing 100 as value for the m() member.

Another way to provide the value for the member is as follows:


@MySingle(m=100)
The built-in annotation @SuppressWarnings is an example for single-value
annotation.

Multi-Value Annotation
----------------------------
A multi-value annotation contains more than one member. The following
code shows an example

@interface MyMulti
{
int m1();
String m2();
String m3();
}

To assign default values follow the code such as shown below

@interface MyMulti
{
int m1() default 1;
String m2() default "";
String m3() default "abc" ;
}

Following is the code showing how to use this annotation


TEKZUNE TECHNOLOGIES 423

@MyMulti(m2="Sami", m3="Moghalpura, Hyderabad")


In the above code, values has been assign for m2() and m3() only but not for
m1().

The following code assign all values

@MyMulti(m1=10 , m2="Sami", m3="Moghalpura, Hyderabad")

Using the Annotations:


-----------------------------
We can use annotations for various types in a Java program, such as classes,
interface,field, or method. The built-in annotation @Target tag is used to
specify at which type the annotationis used. This annotation takes one or
more constants to specify the type at which the annotation is used. These
constants are specified as the element types of the [Link]
package.

Element Types to be used with Annotations:

-------------------------------------------------------------------------------------
Element Types | Where Annotation can be Applied
-------------------------------------------------------------------------------------
[Link] | Package
[Link] | Class, interface or enumeration
[Link] | Fields
[Link] |__ Methods
[Link] |_ Constructors
ElementType.LOCAL_VARIABLE | Local variables
-------------------------------------------------------------------------------------

For example, if we want to create the MyMulti annotation for a class, we can
write the code for it as:
@Target([Link])
@interface MyMulti
{
int m1();
String m2();
String m3();
}

Suppose, we want to create the MyMulti annotation for a class, field or a


method, then we should write these constants inside{} after @Target, as
shown below
TEKZUNE TECHNOLOGIES 424

@Target({[Link], [Link],[Link]} )
@interface MyMulti
{
int m1();
String m2();
String m3();
}

When using annotations, we can also specify at what level an annotation


should be available.
There are levels: source code level, class level, and runtime level. These
levels are indicated by the constants specified in the RetentionPolicy
enumeration of the [Link] package.

Retention Types to be used at Different Levels o a Program

-------------------------------------------------------------------------
Retention Type |Where the Annotation is Retained
--------------------------------------------------------------------------------
[Link] |Refers to the source code. This retention
|type is discarded during compilation
|
[Link] |Refers to the .class file. This retention
|type type is accessible to Java compiler,
|but not available to JVM
|
[Link] |Refers to the runtime file, which is a
|.class file. This retention type is
|accessible to Java compiler at
|compilation time and JVM at
runtime.
-------------------------------------------------------------------------------

The following code shows how to create the MyMulti annotation that is
available to the JVM at runtime and can also be used at the class level:

@Retention([Link])
@Target([Link])
@interface MyMulti
{
int m1();
String m2();
String m3();
}
TEKZUNE TECHNOLOGIES 425

/*186. Write a program to use the @Override annotation to check whether


the sub class method really overrides the super class method or not */

class One
{
void doSomething()
{
[Link]("First Annotation Program");
}
}

class Two extends One


{
@Override
void dosomething()
{
[Link]("Always work hard ");
}
}

class Test
{
public static void main(String args[])
{
Two t=new Two();
[Link]();
}
}
OUTPUT:
E:\>javac [Link]
[Link]: method does not override or implement a method from a
supertype
@Override
^
1 error

/*187. Write a program to use the @Override annotation to check


whether the sub class method really overrides the super class
method or not */
class One1
{
void doSomething()
{
[Link]("First Annotation Program");
TEKZUNE TECHNOLOGIES 426

}
}

class Two1 extends One1


{
@Override
void doSomething()
{
[Link]("Always work hard ");
}
}

class Test1
{
public static void main(String args[])
{
Two1 t=new Two1();
[Link]();
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Test1
Always work hard

/*188. Write a program to use the @Override annotation to check


whether the sub class method really overrides the super class
method or not */

class First
{
void process(int a,int b)
{
[Link]("Sum of two nos = " + (a+b));
}
}

class Second extends First


{
@Override
void process(int a,int b)
{
[Link]("Product of two nos = " + (a*b));
}
}
TEKZUNE TECHNOLOGIES 427

//[Link]
class TestOverride
{
public static void main(String args[])
{
Second s=new Second();
[Link](5,7);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java TestOverride
Product of two nos = 35

@SuppressWarnings Annotation
This annotation is used to suppress warnings issued by the compiler. This
annotation can be applied to a class, method or interface.

/*189. Write a program to crete a HashTable that stores roll number and
name of two students as key-value pairs using the put() method. */

import [Link].*;

class Sample
{
public static void main(String args[])
{
Hashtable hs=new Hashtable();
[Link](10,"Suresh");
[Link](11,"Kumar");
}
}
OUTPUT:
E:\>javac [Link]
Note: [Link] uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

/*190. Program to suppress unwanted warnings*/


import [Link].*;

class Sample1
TEKZUNE TECHNOLOGIES 428

{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
Hashtable hs=new Hashtable();
[Link](10,"Suresh");
[Link](11,"Kumar");
[Link]("Values are: " + hs);
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Sample1
values are: {10=Suresh, 11=Kumar}

The @Deprecated Annotation


This annotation indicates to the compiler that the methodis deprecated
andhence its use should be avoided. It is not recommended to use
deprecated methods, as they can be modified or removed from the future
versions of java.
When a programmer wants to mark a method as deprecated, then that
programmer can use the @Deprecated tag before that method. When this
tag is used, the java compiler displays a message that the method is
deprecated.

/*191. Write a program that uses a deprecated method in the


Myclass. When the user calls this method, the Java compiler should
show a warning message saying that the method is deprecated. */

class Myclass
{
@Deprecated
void M1()
{
[Link]("This is deprecated method");
}
}

class DeprecatedTest
{
public static void main(String args[])
{
Myclass obj=new Myclass();
obj.M1();
}
TEKZUNE TECHNOLOGIES 429

}
OUTPUT:
E:\>javac [Link]
Note: [Link] uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

E:\>java DeprecatedTest
This is deprecated method

/*192. Write a program to create a single-value annotation that


stores only one value and retrieve it during runtime by the JVM.*/

import [Link].*;
import [Link].*;

/*Creat a single value annotation which can be applied to a method. Make it


available to the JVM at runtime*/

@Retention([Link])
@Target([Link])
@interface MySingle
{
int value();
}

/*Now we will apply this annotation in the following class*/


class Myclass
{
/*annotate a method using MyZSingle annotation. Store value 100 into
MySingle annotation*/

@MySingle(value=100)
public void myMethod()
{
[Link]("Hello");
}
}

//Accessing MySingle annotation in other program


public class Demo
{
public static void main(String args[]) throws Exception
{
Myclass obj=new Myclass();

//getClass() method returns Class object and


TEKZUNE TECHNOLOGIES 430

//getMethod() returns the Method class object


Method m=[Link]().getMethod("myMethod");

//Now retriee the single annotation associated with the method


MySingle anno=[Link]([Link]);

//retrieve and display the value in the annotation


[Link]("The value is = " + [Link]());
}
}
OUTPUT:
E:\>javac [Link]

E:\>java Demo
The value is = 100
TEKZUNE TECHNOLOGIES 431

Java SE 8 was released on May 06 2014

What's New in JDK 8

Java Platform, Standard Edition 8 is a major feature release. This document


summarizes features and enhancements in Java SE 8 and in JDK 8, Oracle's
implementation of Java SE 8. Click the component name for a more detailed
description of the enhancements for that component.

 Java Programming Language


o Lambda Expressions, a new language feature, has been
introduced in this release. They enable you to treat functionality
as a method argument, or code as data. Lambda expressions let
you express instances of single-method interfaces (referred to as
functional interfaces) more compactly.

o Method references provide easy-to-read lambda expressions for


methods that already have a name.

o Default methods enable new functionality to be added to the


interfaces of libraries and ensure binary compatibility with code
written for older versions of those interfaces.

o Repeating Annotations provide the ability to apply the same


annotation type more than once to the same declaration or type
use.

o Type Annotations provide the ability to apply an annotation


anywhere a type is used, not just on a declaration. Used with a
pluggable type system, this feature enables improved type
checking of your code.

o Improved type inference.

o Method parameter reflection.

Features of Java SE 7
Code Name:Dolphin Released on: Jul 28,2011
----------------------- ---------------------------
i. Strings in Switch statement
ii. Type Inference for Generic Instance creation
iii. Multiple Exception Handling
iv. Support for Dynamic Languages
TEKZUNE TECHNOLOGIES 432

v. Try with Resources


vi. Java NIO package
vii. Diamond syntax
viii. Binary Literals, underscore in Literals
ix. Aumatic null handling

Features of Java SE 6
Code Name:Mustang (May be horse) Released on: Dec 11,2006
---------------------------------------------- ------------------------
i. Scripting Language Support
ii. JDBC 4.0 API
iii. Java Compiler API
iv. Pluggable Annotation
v. Integrated Web Services

Features of J2SE 5.0


Code Name:Tiger Released on: Sep 30, 2004
----------------------- ---------------------------
[Link]
ii. Enhanced for Loop (for-each)
[Link] / Unboxing
iv. Typsafe Enums
v. Varargs
vi. Static Import
vii. Medata (Annotation)

Features of J2SE 1.4


Code Name:Merlin (Owl or Bird) Released on: Feb 06,2002
--------------------------------------- ---------------------------
i. XML Processing
ii. Java Print Service
iii. Logging API
iv. Java Web Start
v. JDBC 3.0 API
vi. Assertions
vii. Preferences API
viii. Chained Exceptions

Features of J2SE 1.3


Code Name:Kestrel (Bird) Released on: May 08,2000
------------------------------ --------------------------
i. Java Sound
ii. Indexing
TEKZUNE TECHNOLOGIES 433

Features of J2SE 1.2


Code Name:Playground Released on: Dec 08,1998
----------------------- ---------------------------
i. Collection Framework
ii. Java String Memory map
iii. Just In Time (JIT) compiler
iv. Jar signer for signing JAR files
v. Policy Tool for granting access to system resources
vi. Audio support in Applets
vii. Java Plug-in
[Link], BLOB,CLOB,batchUpdate, User-defined types in
JDBC
ix. JFC (Swings)

Features of Jdk1.1 Released on: Feb 19, 1997


--------------------- ------------------------------
i. Support for JDBC
[Link] Classess
iii. Java Beans
iv. RMI(Remote Method Invocation)
v. Reflection

Features of Jdk 1.0


-------------------

Version: jdk1.0
Release on: 23 Jan 1996
Code Name: Oak

Distributed:Using Java we can develop remote or distributed application


which give service to remote system or users.

Portable or Independent: Java produces same output in all computers or OS.

Secure: Java applications are because intruders cannot break java


applications security.
TEKZUNE TECHNOLOGIES 434

Interpreted: Interpreter means it executes single statement at a time due to


which it program execution becomes very slow. But Java People introduces
JIT(Just In Time) compiler to increase the speed of execution.

High Performance: Using Java, we can develop application for all fields like
Education, Commerce, Scientific etc

Byte Code: After compilation source code will be converted to Byte Code
which is changeable code according to OS

Multithreaded: Several threads will be created to perform task of program.

You might also like