Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

JAVA

The document provides an introduction to the Java programming language. It discusses that Java is an object-oriented language developed by Sun Microsystems in 1991. It highlights the primary characteristics of Java including being compiled and interpreted, platform independent, object-oriented, robust, secure, distributed, simple, multithreaded, high performance, and dynamic. It then compares Java to C++, noting some key differences. Finally, it outlines the Java development kit and tools used for developing Java programs.

Uploaded by

Cynical dragon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

JAVA

The document provides an introduction to the Java programming language. It discusses that Java is an object-oriented language developed by Sun Microsystems in 1991. It highlights the primary characteristics of Java including being compiled and interpreted, platform independent, object-oriented, robust, secure, distributed, simple, multithreaded, high performance, and dynamic. It then compares Java to C++, noting some key differences. Finally, it outlines the Java development kit and tools used for developing Java programs.

Uploaded by

Cynical dragon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

EPITOME

STUDY MATERIAL

3
PREFACE
Dear Students,
Introduction to Java is a powerful programming language which
with the advent of World Wide Web and a massive software package, being used
by various types of trade & industry. To take advantage of the full potential of
Java the user has to understand its features, their implications and how to
implement them in a World Wide Web scenario.
This E-Book has been designed especially keeping in mind the
learners and we have tried our-best to make this E-Book simple as possible, to make
it easy for the learner and also elaborate the point to be handful for anyone using
the computer.
If this E-Book helps anyone to learn and to use the computer
effectively, it will be of great success.

EPITOME EDUCATIONAL SOCIETY


Chapter-I

Introduction to Java
ABOUT JAVA

Java is a general purpose, object-oriented programming language developed by Sun


Microsystems of USA in 1991. The first version of Java began in 1991 and was written in 18 months
at Sun Microsystems. In fact, it was not even called Java in those days; it was called Oak, and it was
used internally at Sun. Java is a pure object-oriented language and has a number of characteristics
that make it suitable for Internet programming. Java is both a compiled and an interpreted language.

PRIMARY CHARACTERISTICS OF JAVA


 Compiled and Interpreted
 Platform-Independent and Portable
 Object-Oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Small
 Multithreaded and Interactive
 High Performance
 Dynamic and Extensible

Compiled and Interpreted


Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system. First, Java compiler translates source code into
byte code instructions. Byte codes are not machine instructions and therefore, in the second stage,
Java interpreter generates machine code that can be directly executed by the machine that is running
the Java program. So, we can say Java is both a compiled and an interpreted language.

Platform-Independent and Portable


The most significant contribution of Java over other languages is its portability. Java programs
can be easily moved from one computer system to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will not force any changes in Java
programs. This is the reason why Java has become a popular language for programming on Internet,
which interconnects different kinds of systems worldwide. We can download a Java applet from a
remote computer onto our local system via Internet and execute it locally. This makes the Internet an
extension of the user‘s basic system providing practically unlimited number of accessible applets and
applications.
Java ensures portability in two ways. First, Java compiler generates byte code instructions that
can be implemented on any machine. Secondly, the size of the primitive data types is machine-
independent.
Object-Oriented
Java is a true object-oriented language. Almost everything in Java is an object. All program
code and data resides within objects and classes. Java comes with an extensive set of classes,
arranged in packages that we can use in our programs by inheritance. The object model in Java is
simple and easy to extend.

Robust and Secure


Java is a robust language. It provides many safeguards to ensure reliable code. It has strict
compile time and run time checking for data types. It is designed as a garbage-collected language
relieving the programmers virtually all memory management problems. Java also incorporates the
concept of exception handling, which captures series errors and eliminates any risk of crashing the
system.
Security becomes an important issue for a language that is used for programming on Internet.
Threat of viruses and abuse of resources is everywhere. Java systems not only verify all memory
access but also ensure that no viruses are communicated with an applet. The absence of pointers in
Java ensures that programs cannot gain access to memory locations without proper authorization.

Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects on
Internet as easily as they can do in a local system. This enables multiple programmers at multiple
remote locations to collaborate and work together on a single project.

Simple, Small and Familiar


Java is a small and simple language. Many features of C and C++ that are either redundant or
sources of unreliable code are not part of Java For example, Java does not use pointers, preprocessor
header files, goto statement and many others. It also eliminates operator overloading and multiple
inheritance.
Familiarity is another striking feature of Java. To make the language look familiar to the
existing programmers, it was modeled on C and C++ languages. Java uses many constructs of C and
C++ and therefore, Java code ―looks like a C++‖ code. In fact, Java is a simplified version of C++.

Multithreaded and Interactive


Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before beginning
another. For example, we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer. This feature greatly improves the interactive
performance of graphical applications.
The Java runtime comes with tools that support multiprocess synchronization and construct
smoothly running interactive systems.
High Performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code. Java architecture is also designed to reduce overheads during runtime.
Further, the incorporation of multithreading enhances the overall execution speed of Java programs.

Dynamic and Extensible


Java is a dynamic language. Java is capable dynamically linking in new class libraries, methods
and objects. Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.
Java programs support functions written in other languages such as C and C++. These
functions are known as native methods. This facility enables the programmers to use the efficient
functions available in these languages. Native methods are linked dynamically at runtime.

Java vs. C++


Java is a true object-oriented language while C++ is basically C with object-oriented extension.
Listed below are some major C++ features that were intentionally omitted from Java or
significantly modified.
  Java does not support operator overloading.
  Java does not have template classes as in C++.
 Java does not support multiple inheritances of classes. This is accomplished using a
 new feature called ―interface‖.
 Java does not support global variable. Every variable and method is declared within a
 class and forms part of that class.
  Java does not use pointers.
  Java has replaced the destructor function with a finalize () function.
  There are no header files in Java.
  No inline functions in Java.
  There is no scope resolution operator :: in Java.
  There is no virtual keyword in Java.
 There is no goto in Java.

Java Environment
Java environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development Kit (JDK) and
the classes and methods are part of the Java Standard Library (JSL), also known as the Application
Programming Interface. (API).
Java Development Kit
The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs. They include:
  Appletviewer (for viewing Java applets)
  Javac (Java compiler)
  Java (Java interpreter)
  Javap (Java disassembler)
  Javah (for C header files)
  Javadoc (for creating HTML documents)
 Jdb (Java debugger)

Java Development Tools


Tools Description
appletviewer Enables us to run Java applets (without actually using a Java-compatible browser).
Java interpreter, which runs applets and applications by reading and interpreting
java
byte code files.
The Java compiler, which translates Java source code to byte code files that the
javac
interpreter can understand.
javadoc Creates HTML-format documentation from Java source code files.
javah Produces header files for use with native methods.
Java disassembler, which enables us to covert byte code files into a program
javap
description.
jdb Java debugger, which helps us to find errors in our programs.

To create a Java program, we need to create a source code file using a text editor. The source code is
then compiled using the Java compiler javac and executed using the Java interpreter java. The Java
debugger jdb is used to find errors, if any, in the source code. A compiled Java program can be
converted into a source code with the help of Java disassembler javap.

A Simple Java Program


A Java program has two parts—a class definition that encloses the entire program and a method
called main that contains the body.
Once the program is typed in Notepad or DOS editor, it is saved as a file with an extension of
Java. Usually, Java files have the same name as their class definition. This file is then compiled using
javac. The javac program should be in the execution path for compilation of the Java code. Once
completed, a file by the same name, but with the class extension is created. This is the java byte
code file. The byte code is then run using the Java interpreter. In the JDK, the java interpreter is called
java. To execute this, java followed by the file name without the class extension is typed at the DOS
prompt. The above compilation and execution procedure works only if Sun‘s Java compiler is used.
The following example depicts the writing of a java program.
Example:
Open a new file in the editor and type the following script.

class hellojava
{
public static void main (String args [])
{
System.out.println (―Hello World‖);
}
}
  Save file as hellojava.java
  Compile by typing javac hellojava.java on the command line.
 On successful compilation execute the program by typing java hellojava, on the
 command line.
 The program will display Hello World on the screen.

Every java application program has a main() method. It is the first function run when the program is
executed. The void keyword preceding main() indicates that it does not return any values. public
indicates that the method is global, static denotes that main() is a class method and can be called
without creating an object.

JAVA VIRTUAL MACHINE (JVM)


All language compilers translate source code into machine code for a specific computer. Java
compiler also does the same thing. Then, how does Java achieve architecture neutrality? The answer
is that the Java compiler produces an intermedia code known as byte code for a machine that does
not exist. This machine is called the JVM and it exists only inside the computer memory. It is a
simulated computer within the computer and does all major functions of a real computer. Figure (a)
illustrates the process of compiling a Java program into byte code which is also referred to as virtual
machine code.

Java Program Java Compiler Virtual Machine

Byte code
Fig.1

The virtual machine code is not machine specific. The machine specific code (known as machine
code) is generated by the Java interpreter by acting as an intermediary between the virtual
machine and the real machine as shown in Fig.2.Remember that the interpreter is different for
different machines.

Bytecode Java Interpreter Machine Code

Virtual Machine Real Machine


Fig.2
Fig.3 illustrates how Java works on a typical computer. The Java object framework (Java API) acts
as the intermediary between the user programs and the virtual machine which in turn acts as the
Intermediary between the operating system and the Java object framework.

Real Machine
Operating System
Java Virtual Machine
Java Object Framework (API)
Compiler Interpreter
User Application Programs

User

Layers of interactions for java programs


Fig.3
Chapter – 2

Java Language Constructs


Comments
Java permits both the single-line comments and multi-line comments available in C++.The single-
line comments begin with // and end at the end of the line. For longer comments, we can create
long multi-line comments by starting with a /* and ending with a */.

Keywords
Keywords are essential part of a language definition. They implement specific features of
the language. Java language has reserved 60 words as keywords.

Some examples of Keywords:


abstract boolean break byte catch
case char class continue default
do double else extends final
finally float for if implements
import instanceof int interface long
native new package private protected

CONSTANTS:
Constants in Java refer to fixed values that do not change during the execution of a program. Java
supports several types of constants.

Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus sign.
Valid examples of decimal integer constants are:
345 -768 0 45676
embedded spaces, commas, and non-digit characters are not permitted between digits. For example,
12 456 23,786 $2900
are illegal numbers.
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading 0.Some examples of octal integer are:
045 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They
may also include alphabets. A through F or a through f.A letter A through F represents the
numbers 10 through 15.Following are the examples of valid hex integers.
0X2 0X9F 0xbcd 0x

Real Constants
Numbers containing fractional parts are called real (or floating point) constants. Examples of real
constants are:
0.0067 -0.45 345.78 -.89
Single Character Constants
A single character constant contains a single character enclosed within a pair of single quote marks.
Examples of character constants are:
‗5‘ ‗X‘ ‗;‘ ‗‗

String Constants
A string constant is a sequence of characters enclosed between double quotes. Examples are:
―Hello World‖ ―3456‖ ―?…..!‖ ―5+3‖ ―X‖

Backslash Character Constants


Java supports some special backslash character constants that are used in output methods. They are
also known as escape sequences. Examples:
Constant Meaning
‗\b‘ Back space
‗\f‘ Form feed
‗\n‘ New line
‗\r‘ Carriage return
‗\t‘ Horizontal tab
‗\‘ ‗ Single quote
‗\‖ ‗ Double quote
‗\\‘ backslash
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Unlike constants
that remain unchanged during the execution of a program, a variable may take different values at
different times during the execution of the program. Some examples of variable names are:
 average
 height
 total_height
 classStrength

Rules for variable naming:


  They must not begin with digit
 Uppercase and lowercase are distinct. This means that the variable Total is not the
same as total or TOTAL.
 It should not be a keyword
 White space is not allowed
 Variable names can be of any length.

DECLARATION OF VARIABLES
The declaration of variable tells the compiler what the variable name is. It specifies what type of data
the variable will hold. The place of declaration (in the program) decides the scope of the variable. A
variable must be declared before it is used in the program. The general form of declaration of a
variable is:
Type variable1, variable2, variableN;
Some valid declarations are:
int count;
float x, y;
char c1, c2, c3;

.INITIALIZATION OF VARIABLES
The process of giving initial values to variables is known as the initialization. The ones that are not
initialized are automatically set to zero.
The following are valid Java statements:
float x, y, z; //declares three float variables
int m=8, n=45; //declares and initializes two int variables
DATA TYPES
Data types specify the size and type of values that can be stored.

DATA TYPES IN JAVA

Primitive (Intrinsic)
Non-Primitive (Derived)

Non-numeric
Numeric Classes Arrays

Character
Boolean Interface
Integer

Floating-point

Fig. Data types in Java

Integer Types:
Integer types can hold whole numbers such as 123,-96 and 5639.We can make integers long
by appending the letter L or l at the end of the number. Example: 123L or 123l

Integer

Byte
Short
Long
Int
Integer data types

FLOATING POINT TYPES:


Floating point type can hold numbers containing fractional parts such as 23.78 and –4.768 (known as
floating point constants).

Floating Point

Float Double

Floating-point data types

Type Size
Float 4 bytes
Double 8 bytes

CHARACTER TYPE:
In order to store character constants in memory, java provides a character data type called char. The
char type assumes a size of 2 bytes but, basically, it can hold only a single character. BOOLEAN
TYPE:
There are only two values that a Boolean type can take: true or false. Both these words have
been declared as keywords. Boolean type is denoted by the keyword Boolean.

OPERATORS AND EXPRESSIONS


Operators are special symbols used in expressions. An operator is a symbol that tells the computer
to perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables.
ARITHMETIC OPERATORS
Java has five basic arithmetic operators. Each of these operators takes two operands, one on either
side of the operator. The list of arithmetic operators is given below:

Operator Meaning Example


+ Addition 8+10
- Subtraction 10-8
* Multiplication 20*84
/ Division 10/5
Modulus 10%6
RELATIONAL OPERATORS
We often compare two quantities, and depending on their relation, take certain decisions.
Java supports six relational operators.

Relational
Operator Meaning Value
expression
Is less
< 4.5<-10 FALSE
than
Is less
<= than or 4.5<=10 TRUE
equal to
Is
> greater 6>3 TRUE
than
Is
greater
>= -35>=0 FALSE
than or
equal to
Is equal
== 4+5==5+4 TRUE
to
Is not
!= 45!=9 TRUE
equal to

LOGICAL OPERATORS
Java has three logical operators.

Operator Meaning
&& Logical

AND
|| Logical

OR
! Logical

NOT

ASSIGNMENT OPERATORS
Assignment operators are used to assign the value of an expression to a variable.

Operator Expression Meaning


+= X+=Y X=X+Y
-= X-=Y X=X-Y
*= X*=Y X=X*Y
/= X/=Y X=X/Y
= X=Y X=Y
<<= Left shift
assignment
>>= Right shift
assignment
>>>= Zero fill
right shift
assignment
X&=Y AND
assignment
X |= Y OR
assignment
X ^=Y XOR
assignment

INCREMENT AND DECREMENT OPERATORS


Java has two very useful operators: Increment and Decrement operator
++ and –
the operator ++ adds 1 to the operand while – subtracts 1.Both are unary operators and are used in
the following form:
++m; or m++;
--m; or m--;
++m; is equivalent to m=m+1; (or m+=1;)
--m; is equivalent to m=m-1; (or m-=1 ;)

Decision Constructs:
SIMPLE IF STATEMENT:

The general form of a simple if statement is


If (test expression)
{
statement-block;
}
statement-x;

The ‗statement-block‘ may be a single statement or a group of statements. If the test expression
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
It should be remembered that when the condition is true both the statement-block and
the statement-x are executed in sequence
This is illustrated in fig.

Entry
True
test
expression
?

Statement-Block

False

Statement-x

Next statement

Flowchart of simple if control

THE IF-ELSE STATEMENT


The general form is
If (test expression)
{
true-block statement(s)
}
else
{
false-block statement(s)
}
statement-x

If the test expression is true, then the true-block statement (s) immediately following the if statement,
are executed; otherwise, the false-block statement(s) are executed. In either case, either
true –block or false-block will be executed, not both. This is illustrated in fig. In both the cases, the
control is transferred subsequently to the statement-x.

Entry

True Test expression False


?

True-block False-block
statements statements

Statement-x

Flowchart of if-----else control

Continue and Break

The format of the continue statement is simply


continue;
The format of the break statement is simply
break;
Break statement causes the loop to be terminated.
The continue statement tells the compiler, ―SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITH THE NEXT ITERATION‖.
Use of continue and break statements

class ContinueBreak
{
public static void main(String args[])
{
LOOP1 : for (int i=1;i<100;i++)
{
System.out.println (― ―);
If ( i >= 10) break;
for(int j=1;j<100;j++)
{
System.out.print(― * ―);
If (j == i)
Continue LOOP1;
}
}
System.out.println (―Termination by BREAK‖);
}
}

While Loop

A while loop keeps executing the statement in its body (which may be a compound statement, with a
number of single statements inside curly braces) while a particular logical condition evaluates to true.
Here‘s what a while loop looks like in general:

while (condition)
statement
Note that if condition is not true, the body of the loop is not even executed once.
public class check6
{
public static void main (String args[])
{
int xyz = 10;
while (xyz > 0)
{
System.out.println (―Value = ―, xyz - -);
}
}
}
do-while loop

The do-while loop is just like a while loop, except that the test condition is evaluated at the end of
the loop, not at the beginning. Here‘s what the do-while loop looks like (bear in mind that the
statement can be a compound statement with a number of single statement inside curly braces):

do
statement
while (condition);

public class check7


{
public static void main(String args[])
{
int a = 15;
do
{
System.out.println (a++);
} while (a<15);
}
}

for loop
The java for loop is a good choice when you want to use a numeric index that you automatically
increment or decrement each time through the loop, such as when you‘re working with as array.
Here‘s what the for loop looks like in general (note that statement can be a compound statement,
including several single statement inside curly braces:
for (initialization_expression; end_condition; iteration_expression)
{
statement
}

public class check8


{
public static void main(String args[])
{
int loop_index;
for (loop_index = 1; loop_index <=10; loop_index++)
{
System.out.println (―This is iteration number‖, + loop_index);
}
}
}
Array:

An array is a set of continuous memory locations. Array can hold similar type of data only.
Like any other variables, array must be declared and created in the computer memory before they
are used. Creation of an array involves three steps:
  Declare the array
  Create memory locations
 Put values into the memory locations.

Array in Java may be declared in two forms:


Form1
type arrayname [ ] ;
Form2
type [ ] arrayname;

Examples:
Int number[ ];
Float [ ] marks;

After declaring an array, we need to create it in the memory. Java allows us to create arrays using new
operator only, as shown below:
arrayname = new type [size];

Examples:
number = new int[5];
average = new float[10];

It is also possible to combine the two steps—declaration and creation – into one as shown below:
int number [ ] = new int [ 5 ];

Initialization of Arrays

The final step is to put values into array created.This process is known as initialization. This is done
using the array subscripts as shown below:
Arrayname [subscript] = value;
Example:
number [0] = 35;
number [1] = 40;

We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
Type arrayname [ ] = { list of values);
Example:
int number[ ] = { 35,40,20,57,12};
Array Length

In java all arrays store the allocated size in a variable named length.We can access the length of the
array a using a.length.
Example:
int aSize = a.length;

Sorting a list of numbers

class NumberSorting
{
public static static void main(String args[])
{
int number[] = { 55,40,80,65,71};
int n = number.length;
System.out.print(―Given list : ―);
For (int I = 0; I < n ; i++)
{
System.out.print(― ― + number[i]);
}
System.out.println(―\n‖);
//Sorting begins
for(int i=0; i < n ; i ++)
{
for(int j = i + 1; j < n; j++)
{
if (number[i] < number[j])
{
//Interchange values
int temp = number[ i ];
number[i] = number[j];
number[j] = temp;
}
}
}
System.out.print(―Sorted list: ― );
for(int i=0; i<n; i++)
{
System.out.print(― ― + number[i]);
}
System.out.println(― ―);
}
}
Output:
Given list: 55 40 80 65 71
Sorted list: 80 71 65 55 40

We may create a two-dimensional array like this:


int myArray[ ] [ ] ;
myArray = new int[3] [4];

Application of two-dimensional arrays

class MulTable
{
final static int ROWS = 20;
final static int COLUMNS = 20;
public static void main(String args[ ])
{
int product [] [] = new int [ROWS] [COLUMNS];
int row, column;
System.out.println(―MULTIPLICATION TABLE‖);
System.out.println(― ―);
int i,j;
for(i = 10; i<ROWS; i++)
{
for(j=10; j<COLUMNS; j++)
{
product [i] [j] = i * j;
System.out.print(― ― + product[i] [j]);
}
System.out.println(― ―);
}
}
}
STRINGS

Strings represent a sequence of characters. The easiest way to represent a sequence of characters in
Java is by using a character array. Example:
char charArray[ ] = new char[4];
charArray[0] = ‗J‘;
charArray[1] = ‗a‘;
charArray[2] = ‗v‘;
charArray[3] = ‗a‘;
In java , strings are class objects and implemented using two classes, namely,String and StringBuffer.
A java string is an instantiated object of the String class.A java string is not a character array and is
not NULL terminated. Strings may be declared and created as follows:
String stringName;
StringName = new String (―string‖);

Example:
String firstName;
FirstName = new String(―Anil‖);
These two statements may be combined as follows:
String firstName = new String(―Anil‖);

There are two ways of creating a String in java. One way is by not using the new operator. Thus
, normally a String is created ,
String s = new String(―hello‖);
But a slightly shorter method can be used
String s = ―GoodBye‖;

Eg.

class abc
{
public static void main(String args[])
{
String pchs1 = ―hello‖;
String prts1 = ―hello‖;
if (pchs1 = = prts1)
{
System.out.println(―String are equals‖);
}
String pchs2 = new String(―hello‖);
String prts2 = new String(―hello‖);
if(pchs2 = = prts2)
{
System.out.println(―String are equals‖);
}
}
}
Chapter-3

Working with Classes


1. Creating Files with one class only

Java is a full-fledge OOP language.The structure of Java is such that it enforce designing and
coding of application in an object oriented way .To developed a programe in an object priented way,
the program has to be n the form of a class. A simple example of creating a programe with only one
class is given below.

Class Test

public static void main(String args[])

System.out.println(―Testing my first Java programe‖);

2. Creating file with multiple classes.


In the above example we discussed above use only one class that contains the main method.
A real –life application will generally required multiple classes. The following programe illustrate a
java programe that define two classes Room and class RoomArea. The Room class defines two
variables and one method to assign values to these variables.The class RoomArea contains the main
method that initiate the execution.

The main method declares a local variable are and a Room type object room1 and
then assign values to the data members of Room class by using the getdata method.Finally,it
calculate the area and print the result.

class Room

float len;

float bre;

void getdata(float a,float b)

len = a;

bre = b;

}
class RoomArea

public static void main(String args[])

float area;

Room room1=new Room(); //Create an object room1


room1.getdata( 12 , 34 );

area = room1.length * room.beath;

System.out.println(―Area =‖+area);

when create file with multiple classes make sure that your file name is same with the class
name that contain the main method.

Import Statement
To make use of classes within different packages, the import statement is use .Once imported,the

classes within the package can be used by the programe.All standard package of Java are

included within a package called java.By default,all programe import the java.lang

package.Sepecially classes belonging to one particular can be imported or all of them be

simultaneously import using.

In java source filoe.import statement occur immediately


following the package(if it exist) and before nay class defination. This is the general form of
the import statement./

Import pkg1[.pkg2].(classname | *);


Here ,pkg1 is the name of a top level package,and pkg2 is the name of the subordinate
package inside the outer package separated by a dot(.).Finally,you sepecify either an explict
calssanme os a star(*),which indicates that the java compiler should import entire
package.This code fragment shows both forms in use
Import java.util.Date;
Import java.io.*;

3. Classpath Variable
Whenever a class is created without nay package statement,it is implied that the class is included

in Java‘s default package.Incase of writing small programes it is not necessary for the package

name to be mentioned. The necessity for packages can be understood in real time application

environment.

Java compiler and the interpreter searches the class file in the path specifed in
CLASSPATH environmental variable. The current working directory is,by default,included in this
variable.hence is possible to compile and execute the programe from the existing directory.In case of
creating package,insure that the root directory of the package is included in the CLASSPATH variable.
Chapter-4

Exceptions
1. Introduction
An exception is an abnormal condition that arise in a code sequence at runtime.In other
word,an exception ia n run time error.In computer language that does not support exception
heandling,errors must be checked and handle manually-typically through the use os error
code,ans so on.

2. Exception – Handling Fundamental


A java exception is an object that descrives an exception(that is,error)condition that has occurred in a
pice of code. When an exception condition arises, an object representing that exception is creatyed and
thrown in the method that caused the error. That method may choose to handle the exception itself,or
pass it on.either way,at some point, the exception is caught and process
.exception can be generatyed by the Java run time system,or they can be manuallyu generated by
your code.

Java excption handling is managed via five keywords : try,catch,throw,throws


and finally.
Using try and catch
Although the default exception handler provided by the java run-time system is
useful for debugging ,you will usually want to handle an exception yourself.Doing so provides
twi benefits.First it allows you to fix the error.Second,it prevents the programe from
automatically terminating.
To guard against and handle a run time error,simply enclose the code that you
want to monitor inside a try block. Immediately following the try block,include a catch clause
that specifies the exception type that you wish th catch. To illustrate how how easily this can be
done, the following programe include a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero:

Class Exc{
Public static void main(String args[])
{
int d,a;
try{
d=0;
a=42/d;
System.out.println(―This will not be printed‖)
}catch(ArithmeticException e)
{
System.out.println(―Division by zero‖);
}
System.out.println(―After catch statement .‖);
}
This programe generate the following output:

Division by zero
After catch statement.
Throw

So far,you have only been catching exception that are thrown by the Jva run time
system.However,it is possible for your programe to throw an exception explicitly,using the
throw statement. The general form of throw is shown here .

Throw ThrowableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass of throwable
.Simple types,such as int or char,as well as non-Throwable classes,such as String and
Object,cannot be used as exception. There are two ways you can obtain a Throwable object:
using a parameter into a catch clause,or creating one with the new operator.
Here is the sample programe that creates and throws an exception.
The handler that catches the exception rethorws it to the outer handler.

Class ThrowDemo{
Static void demoproc(){
Try{
Throw new NullPointerException (―demp‖);
} catch(NullpointerException e){
System.out.println(―Caught inside demoproc.‖);
throw e;
}
}
public static void main(String args[]){
try{
demproc();

}catch(NullpointerException e){
System.out.println(―Recought :‖=e);
}
}
}
Throws

If a method is capable of causing an exception that is does not handle, it must specify
this behavior so that the caller of the method can guard themselves against that
exception. you do this by including a throws clause in that a method‘s declaration . A
throws clause lists the type of exception that a method might throw. This is necessary for
all exception,except those of type Error or RuntimeException ,or nay of their
subclasses.All other exception that a method can throw must be declare in the throws
clause. If they are not, a compile-time error result.

This is general form of a method declaration that includes a throws claues:


Type method-name(parameter-list) throws exception-list
{
//body of method

}
Here,exception-list is a comma-separated list of the exceptions that a method can throw.

Following ia an example of an incurrect programe that tries to throw an exception that


is does not catch. Because the programe does not specify a throws clause to declare this fact,
the programe will not compile

// this programe contains an error an will not compile

class ThrowsDemo{
static void throwOne(){
System.out.println(―Inside throwOne ―);
Throw new IllegalAccessException(―demo‖);
}
public static void main(String args[]){
throwOne();
}
}

To make this example compile,you need to make two changes. First,you need to declare
that throwOne() throws IlligalAccessException.second, main() must define a try/catch
statement that catches this exception.
The correct example is shown here

// this is now correct


class ThrowsDemo {
static void throwOne( ) yhrows IllegalAccessException{
System.out.println(―Inside throwOne ―); Throw new
IllegalAccesException(―demo‖);
}
public static void main (String args[])
{
try{
throwOne();
} catch(IllegalAccessException e){
System.out.println(―Caught ― + e);
}
}
}

Here is the uotput generated by running this example programe


Inside throwOne
Caught java.lang.IllegalAccessException :n demo

Finally
Finaly create a block of code that will execute after a try/catch block has copplete and before
the code following the try/catch block . the finally block will execute whether or not an exception
is thrown. If an exception is thrown, the finally block will execute even if no catch statement
matches the exception. This can be use for closing file handle and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional. However,each try statement requires at least one
catch or a finally caluse.

Here is an example programe that shows three methods that exit in various ways, none
without executing their finally clause :
// demonstrate finally
class FinallyDemo{
try{
System.out.println(―inside procA‖); Throw
new RuntimeException(―demo‖);
} finally{
System.out.println(― procA‘s finally‖);
}
}
// Return from wirhin a try block‘

static void procB(){

try{
System.out.println(―inside procB‖);
Return;
}finally{
System.out.println(―procB‘s finally‖);
}
}
// Execute a try block normally
static void main(String args[])
{
try{
procA()
}catch(Exception e){
System.out.println(―Exception caught‖);
}
procB();
procC();
}
}
Creating User Defined Exception

Customized exception are necessary to handle abnormal codition of application created


by user. The advantages of creating such an exception class it that, according to situation define by
the user an exception can be thrown . It is also possible to set any condition or value to a variable
and genareted user-defined exception . For example,it is possible to check if the input is greter then
or lesser than a predefined number and according generate exception.

Example

Class OutOfRangeException extends Exception

OutOfRangeException(String str)

super(str);

public class Uexcep

void v1(int i) throws Exception


{
if(i<(-200) || I>200)
{
throw new OutOfRangeException(―The number ― + i + ― is not in
range thatshould be less then 200 andn gt –200‖); }

else
{
System.out.println(―The number ―+ I + ―is in range ―);
}
}
public static void main(String args[])
{
try
{
UExcept ue=new UExcep();
Ue.v1(-300);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Chapter-5

Inheritance, Abstract and Interfaces


Inheritance is the process by which objects of one class acquire the properties of objects of another
class. Inheritance supports the concept of hierarchical classification. For example, the bird robin is a
part of the class flying bird,which is again a part of the class bird.As illustrated in fig. , the principle
behind this sort of division is that each derived class shares common characteristics with the class
from which it is derived.

Bird

Attributes:
Feathers
Lay eggs

Flying Nonflying
Bird Bird

Attributes: Attributes:

Robin Swallow Penguin Kiwi

Attributes: Attributes: Attributes: Attributes:


Property inheritance
In OOP, the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it.This is possible by deriving a new class
from the existing one.The new class will have the combined features of both the classes.Thus the
real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a
class that is almost , but not exactly , what he wants , and to tailor the class in such a way that it
does not introduce any undesirable side effects into the rest of the classes.In Java , the derived
class is known as ‗subclass‘.

baseclass :
baseclass is a class from which another class inherits functionality. In Java , a baseclass is often
called a superclass.

derived class:
derived or sub class is a class that inherits from a base class.

abstract class:
abstract class is a class that can not be instantiated directly.Abstract classes exist so that
subclasses can inherit variables and methods from them.
Inheritance:
The mechanism of deriving a new class from an old one is called inheritance.The old class is known
as the base class or super class or parent class and the new one is called the subclass or derived
class or child class.The inheritance allows subclasses to inherit all the variables and methods of
their parent classes.Inheritance may take different forms:
 Single inheritance (only one super class)
 Multiple inheritance (several super classess)
 Hierarchical inheritance(one super class,many subclasses)
 Multilevel inheritance(Derived from a derived class)

Java does not directly implement multiple inheritance. However, this concept is implemented using
a secondary inheritance path in the form of interface.

A A B

B C

Single inheritance Multiple inheritance


Application of single inheritance

class Room
{
int length;
int breadth;
Room (int x, int y)
{
length = x;
breadth = y;

}
int area()
{
return (length * breadth);
}

}
class BedRoom extends Room // Inheriting Room
{
int height;
BedRoom(int x, int y, int z)
{
super(x,y); // pass value to superclass
height = z;
}
int volume()
{
return (length * breadth * height);
}
}

class InherTest
{
public static void main(String args[])
{
BedRoom room1 = new BedRoom(14,12,10);
int area1 = room1.area(); //superclass method
int volume1 = room1.volume(); // baseclass method
System.out.println(―Area1 = ― + area1);
System.out.println(―Volume1 = ― + volume1);
}
}

Output of the Program is:


Area1 = 168
Volume1 = 1680

Access specifiers:

Public: Use public if the field is to be visible everywhere.

Protected: Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.

Private: Use private if the field is not to be visible anywhere except in its own class.

Overriding methods:

A method defined in a super class is inherited by its subclass and is used by the objects created by
the subclass.Method inheritance enables us to define and use methods repeatedly in subclasses
without having to define the methods again in subclass.
However,there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called.That means, we should override the method
defined in the superclass.This is possible by defining a method in the subclass that has the same
name, same arguments and same return type as a method in the superclass.Then , when that method
is called , the method defined in the subclass is invoked and executed instead of the one in the
superclass.This is known as overriding.The following program illustrates the concept of
overriding.The method display() is overridden.
Illustration of method overriding

class Super
{
int x;
Super(int x)
{
this.x = x;
}
void display() // method defined
{
System.out.println(―Super x = ― + x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
Super(x);
this.y = y;
}
void display() //method defined again
{
System.out.println(―Super x = ‖ + x);
System.out.println(―Sub y = ― + y);
}
}

class OverrideTest
{
public static void main(String args[])
{
Sub s1 = new Sub(100,200);
s1.display();
}
}

Output:

Super x =100
Sub y = 200
Abstract methods and classes
By making a method final we ensure that the method is not redefined in a subclass.That is, the
method can never be subclassed.Java allows us to do something that is exactly opposite to this.That
is, we can indicate that a method must always be redefined in a subclass,thus making overriding
compulsory.This is done using the modifier keyword abstract in the method definition.Example:
abstract class Shape
{
……………
……………
abstract void draw();
……………
……………
}

When a class contains one or more abstract methods, it should also be declared abstract as shown in
the example above.
While using abstract classes, we must satisfy the following conditions:
 We cannot use abstract classes to instantiate objects directly. For example,

 Shape s = new Shape();


 is illegal because shape is an abstract class.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.

Interfaces
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but
with a major difference.The difference is that interfaces define only abstract methods and final
fields.This means that interfaces do not specify any code to implement these methods and data fields

contain only constants.Therefore, it is the responsibility of the class that implements an interface to
define the code for implementation of these methods.
The syntax for defining an interface is very similar to that for defining a class . The general
form of an interface definition is:

interface InterfaceName
{
variables declaration;
methods declaration;
}

Here, interface is the keyword and InterfaceName is any valid Java variable (just like class names).
Variables are declared as follows:

Static final type VariableName = Value;


Note that all variables are declared as constants.Methods declaration will contain only a list of
methods without any body statements.Example:
Return-type methodName1 (parameter_list);
Here is an example of an interface definition that contain two variables and one method
interface Item
{
static final int code final = 1001;
static String name = ―Fan‖;

void display();
}

Note that the code for the method is not included in the interface and the method declaration simply
ends with a semicolon.The class that implements this interface must define the code for the method.

Implementing Interfaces:

Interfaces are used as ―superclasses‖ whose properties are inherited by classes. It is therefore
necessary to create a class that inherites the given interface.This is done as follows:
class classname implements Interfacename
{
body of classname
}

Here the class classname ―implements‖ the interface interfacename.A more general form of
implementation may look like this:
Class classname extends superclass implements interface1,interface2,………..
{
body of classname
}

This shows that a class can extend another class while implementing interfaces.

Program: Implementing interfaces

//InterfaceTest.java
interface Area //Interface defined
{
final static float pi = 3.14F;
float compute(float x, float y);
}
class Rectangle implements Area //Interface implemented
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Area //Another implementation
{
public float compute(float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area; //Interface object area = rect;

System.out.println(―Area of Rectangle = ― +
area.compute(10,20)); area = cir;
System.out.println(―Area of Circle = ― + area.compute(10,0));
}
}
Output:
Area of Rectangle = 200
Area of Circle = 314

Java does not support multiple inheritance.But in Java this concept can be implemented using
interfaces.

Program: Implementing multiple inheritance


class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber()
{
System.out.println(―Roll No: ― + rollNumber);
}
}
class Test extends Student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1 = m1;
part2 = m2;
}
void putMarks()
{
System.out.println(―Marks obtained‖);
System.out.println(―Part1 = ― + part1);
System.out.println(―Part2 = ―+part2);
}
}
interface Sports
{
float sportWt = 6.0F;
void putWt();
}
class Results extends Test implements Sports
{
float total;
public void putWt()
{
System.out.println(―Sports Wt = ― + sportWt);
}
void display()
{
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putWt();
System.out.println(―Total score = ― + total);
}
}
class Hybrid
{
public static void main(String args[])
{
Results students1 =new Results();
student1.getNumber(1234);
student1.getMarks(27.5F,33.0F);
student1.display();
}
}

Output:
Roll No: 1234
Marks obtained
Part1 = 27.5
Part2 = 33
Sports Wt = 6
Total score = 66.5
Chapter: 6

Threads
A thread is similar to a program that has a single flow of control. It has a beginning, a body and an
end and executes commands sequentially.A thread is a single line of execution within a program. A
thread is created either by subclassing the Thread class or implementing the Runnable interface.

Multithreading is a conceptual programming paradigm where a program(process) is divided


into two or more subprograms(processes),which can be implemented at the same time in
parallel.For example, one subprogram can display an animation on the screen while another may
build the next animation to be displayed.Multiple threads can run concurrently in a single program.

LIFE CYCLE OF A THREAD

During the life of a thread, there are many states it can enter. They include:

 Newborn state
 Runnable state
 Running state
 Blocked state
 Dead state
A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in fig.

New Thread Newborn

start
stop

Active stop
Killed
Thread Dead Thread
Running Runnable

yield

Resume notify
stop
Suspend sleep wait

Idle Thread
(Not Runnable) Blocked
State transition diagram of a thread

Newborn State

When we create a thread object, the thread is born and is said to be in newborn state. The thread is
not yet scheduled for running. At this state, we can do only one of the following things with it:
  Schedule it for running using start() method.
 Kill it using stop() method.

If scheduled, it moves to the runnable state. If we attempt to use any other method at this stage,
an exception will be thrown.

Newborn

stop

start

Dead state
Runnable state

Scheduling a newborn thread

Runnable State

The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor. That is, the thread has joined the queue of threads that are waiting for execution . If
all threads have equal priority, then they are given time slots for execution in round robin fashion,
i.e., first-come,first-serve manner.The thread that relinquishes control joins the queue at the end
and again waits for its turn.This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread of equal priority
before its turn comes, we can do so by using the yield() method.
yield

Running Runnable Threads


Thread

Relinquishing control using yield() method


Running State

Running means that the processor has its time to the thread for its execution. The thread runs until
it relinquishes control on its own or it is preempted by a higher priority thread. A running thread
may relinquish its control in one of the following situations.
 It has been suspended using suspend() method. A suspended thread can be revived by using
the resume() method . This approach is useful when we want to suspend a thread for some
time due to certain reason, but do not want to kill it.

suspend

resume

Running Runnable Suspended

Relinquishing control using suspend() method

 It has been made to sleep.We can put a thread to sleep for a specified time period using
the method sleep(time) where time is in milliseconds.This means that the thread is out of
the queue during this time period.The thread re-enters the runnable state as soon as this
time period is elapsed.
sleep (t)

after t

Running Runnable Sleeping

Relinquishing control using sleep() method

 It has been told to wait until some event occurs. This is done using the wait() method. The
thread can be scheduled to run again using the notify () method.

wait

notify

Running Runnable Waiting

Relinquishing control using wait () method


Blocked State

A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state.This happens when the thread is suspended, sleeping, or waiting in
order to satisfy certain requirements.A blocked thread is considered ―not runnable‖ but not dead
and therefore fully qualified to run again.
Dead State

Every thread has a life cycle.A running thread ends its life when it has completed executing its run()
method.It is a natural death.However, we can kill it by sending the stop message to it at any state
thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running,
or even when it is in ―not runnable‖ (blocked) condition.

Creating Threads

A new thread can be created in two ways:


 By creating a thread class
 By converting a class to a thread
Chapter-7

Files, Directories and Streams


So far we have used variable and array for storing data inside the programe. This approach poses the
following problems.
1. The data is lost either when a variable goes out of scope when programe is terminated.
That is, the storage is temporary.
2. It is difficult to handle large volumes of data using variable and array.
We can overcome these problems by sorting data on secondary storage devices such as
floppy disks or hard disks. The data is stored in these devices using the concept of files.
Data stored in files is often called persistent data.
File
Athough most of the classes defined by java.io operate on streams, the File class does
not. It deal directly with files and the file system. That is, the File class does not specify how
information is retrieve from or store in files.

File are the primary source and destinition for data withinmany programs. Although there a
primary source and destination for data within many programes. Although there are servere
restrictions on their use wirhin applets for security reasons. A directory in java is treated simply a File
with one additional property – a list of filename that can be examinited by the list() method.

The following constructors can be used to create File object:


File( String directoryPath)
File(String directoryPath,String filename)
File(File dirObj,String filename)
File(URL uriObj)

Here, directoryPath is path name of the file. Filename is the name of the file ,dirObj is a File object
that specifies a directory, and uriObj is an URL object that describes a file .

CONCEPT OF STREAM
In file processing, input refers to the flow of data into a program and output means the flow of data
out of a programe. Input to a programe may come from the keyboard, the mouse,the memory, the
disk, a netwiork, or another programe. Similarly, output from a programmer may go to the screen,
the printer, the memory, the disk , the network, or another programe.
Java uses the concept of streams to represent the ordered sequence of data, a
common characteristic shared by all the input/output devices as stated above. A stream represents a
uniform,easy-to-use,object-oriented interface between the programe and the input/output devices.

Java stream are classified into two basic types, namely, input stream and output Stream .An
input stream extracts data from the source9file) and sends it to the programe.Similiarly, an output
stram takes data from the programe and sends(writes). ti the destination (file).
STREAM CLASSES

The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data . these classes may be categorized into two groups based on the data on
which they operate.
1. Byte stream classes that provide support for handling I/O operation on bytes.
2. Character stream classes that provide support for managing I/O operation on characters.

BYTE STREAM CLASSES


Byte stream classes have been designed to provide functional features creating and
manipulating stream and files for reading and writing bytes. Since the streams are unidirectional,
they can transmit bytes in only one cirection and therefore Java provides two kinds of byte stream
classes : input stream classes and output stream classes.

Output Stream Classes


Input stream classes that are used to read *-bit byte including a super class known as
InputStream and a number of subclasses for supporting various input-related functions.The super
class InputStream is an abstract class, and therefore we can not create instances of this class. Rather,
we must uswe the subclasses that inheret form this class. The InputStram class defines methods for
performing input function such as

1. Reading bytes
2. Closing streams
3. Marking positions in streams
4. Skipping ahead in stream
5. Finding the number of bytes in stream

Output Stream Classes


Output stream classes are derived from the base class OutputStream . Like InputStream, the
Outputtream is an adstract class and therefore we cannot instantiate it. The several subclasses of the
OutputStream can be used for performing the output operations.

The OutputStream includes methods that are designed to perform the following tasks
1. Write Bytes
2. Closing stream
3. Flushing stream

CHARACTER STREAM CLASSES


Character stream classes were not a part of the language when it was realeased in 1995 .
They were added later when the version 1.1 was announced. Character stream can be used to read
and write 16-bit Unicode characters. Like byte stream, there are twn kinds of character stream
classes, namely, reader stream classes and writer stream classes

Reader Stream Classes


Reader stream classes are designed to read character from files. Reader stream classes are
designed to read character from he file . Reader class in base class for all the other classes in this
group . These slasses are functionally very similar ti the input stream classes,except input stream use
as bytes as their fundamental unit of information,while reader streama use characters.
The Reader Class contains method that are indentical to these available in the InputStream class ,
except Reader is designed to handle characters. Therefore, reader classes can perform all functions
implemented by the input stream classes.

Writer Stream Classes


Like output stream classes, the writer stream classes are designed to perform all output
operations of files. Only difference is the while output stream classes are desgined to write bytes, the
writer stream classes are designed to write characters.
The Writer calss is an abstract class which acts as a base for all the other writer stream classes
. this base class provides support for all output operation by defining methods that are indentical to
those in OutputStream class.

READING/WRITING CHARACTER
As pointed earler, subclasses of Reader and Writer implement stream that can handle
character. The two subclasses used for handling character in the file are FileReader (for
reading character) and FileWrite (for writing character). The following programe uses these
two file stream classes to copy the contents of a file named ―input.dat‖ into a file called
―output.dat‖

// Copying character from on file into


another import java.io.*;
class CopyCharcters
{
public static void main(String args[])
{
// Declare and create input and output file

File infile = new File(―input.dat‖);


File outFile= new File(―output.dat‖);
FileReader ins = null; // Creating file stream ins
FileWriter outs = null; // creating file stream outs
Try
{
ins = new FileReader (inFile); // Opens inFile
outs = new FileWriter (outFile); //Opens outFile
// Read and write till the
end int ch;
while ( (ch = ins.read()) != -1)
{
outs.write(ch);
}
}catch(IOEception e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close file
{
try
{
ins.close();
outs.close();
}
catch(IOEception e){}
}
}
}
READING/ WRITING BYTES

In the earler programe we have used FileReader and FileWriter classes to read and
write 16-bit characters . However , most file system use only 8-bit bytes. As pointed out earler, Java
I/O system provides a number of classes that can handle 8-bit bytes. Two commonly used classes for
handling bytes are FileInputStream and FileOutputStream calasses . We can use them in place if
FileReader and FileWriter.

The following programe demonstrates how FileOutputStream class is used for writing bytes to a file.
The programe writes the name of some cities stored in abyte array to a new file named ―city.txt‖.
// Write buyes to a programe
import java.io.*;
calss WriteBytes
{
public static vopd main( String args[])
{
//Declare and initialize a byte array
byte cities[] = { ‗D‘,‘E‘,‘L‘,‘H‘,‘I‘,‘\n‘,‘M‘,‘A‘,‘D‘,
‘R‘,‘A‘,‘S‘,‘\n‘,‘L‘,‘O‘,‘N‘,D‘,‘O‘,‘N‘,‘\n‘};
// Create an output file stream
FileOutputStream outfile = null;
Try
{
//Connect the outfile stream to ―city.txt

outfile = new FileOutputStream(―city.txt‖);


// Write data the stream
outfile.write(cities);
outfile.close();
}
catch (IOException ioe)
{
System.out.println(ioe);
System.exit(-1);
}
}
}

CHAPTER-8

Applets
Applets are small Java programs that are primarily used in Internet computing. They can be
transported over the Internet from one computer to another and run using the Applet Viewer or any
Web browser that supports Java.An applet is intended not to be run on its own, but rather to be
embedded inside another application. Like any application program, applet can perform arithmetic
operations, display graphics, play sounds, accept user input, create animation and play interactive
games. A web page can now contain not only a simple text or a static image but also a Java applet
which, when run, can produce graphics, sounds and moving images.

For writing the Internet based applications we need Applet, which can be embedded on net.
Compiling an applet is exactly the same as compiling an application.By compiling the source
code of the applet we get the .class file of the applet.
Let us consider the HelloJava applet. This applet has been stored in a file called
HelloJava.java.Here are the steps required for compiling the HelloJava applet.
 Move to the directory containing the source code and type the following command:

javac HelloJava.java
 The compiled output file called HelloJava.class is placed in the same directory as the If any
error message is received, then we must check for errors, correct them and compile the
applet again.

Before we try to write applets, we must make sure that Java is installed properly and also ensure that
either the Java appletviewer or Java-enabled browser is available.The steps involved in developing
and testing an applet are:
 Building an applet code(.java file)
 Creating an executable applet(.class file)
 Designing a web page using HTML tags.
  Preparing <APPLET> tag.
 Incorporating <APPLET> tag into the web page
 Creating HTML file
 Testing the applet code

Running the Applet


Suppose we have created applet files as well as the HTML file in the name of HelloJava containing the
applet, we must have the following files in our current directory:
HelloJava.java
HelloJava.class
HelloJava.html

To run an applet, we require one of the following tools:


  Java-enabled web browser (such as HotJava or Netscape)
 Java appletviewer
If we use a Java-enabled web browser, we will be able to see the entire web page containing the
applet.If we use the appletviewer tool, we will only see the applet output.Remember that the
appletviewer is not a full-fledged web browser and therefore it ignores all of the HTML tags except
the part pertaining to the running of the applet.

The appletviewer is available as a part of the Java Development Kit that we have been using so far.We
can use it to run our applet as follows:
appletviewer HelloJava.html

Notice that the argument of the appletviewer is not the .java file or the .class file, but rather .html
file.

How Applets differ from Applications


Although both the applets and stand-alone applications are Java programs, there are significant
differences between them. Applets are not full-featured application program.
 Applets do not use the main() method for initiating the execution of the code.Applets,
when loaded, automatically call certain methods of Applet class to start and execute the
 applet code.
 Unlike stand-alone applications, applets cannot be run independently.They are run from
inside a web page using a special feature known as HTML tag.
  Applets cannot read from or write to the files in the local computer.
  Applets cannot communicate with other servers on the network.
  Applets cannot run any program from the local computer.
 Applets are restricted from using libraries from other languages such as C or C++.

APPLET LIFE CYCLE

Every java applet inherits a set of default behaviours from the applet class. As a result, when an
applet is loaded , it undergoes a series of changes in its state as shown in fig . The applet states
include:
 Born or initialization state
 Running state
 Idle state
 Dead or destroyed state

Begin Born Initialization


(Load Applet)

start()
stop()

Idle Stopped
Running
start()
Display

paint ()
destroy ()

End
Destroyed Dead

Exit of Browser
An applet‘s state transition diagram

Initialization State
Applet enters the initioalization state when it is first loaded.This is achieved by calling the init()
method of Applet Class.The applet is born.At this stage, we may do the following , if required.
  Create objects needed by the applet
  Set up initial values
  Load images or fonts
 Set up colors

The initialization occurs only once in the applet‘s life cycle. To provide any of the
behaviours mentioned above, we must override the init() method:

public void init()


{
………………….
………………….(Action)
………………….
}

Running State

Applet enters the running state when the system calls the start() method of Applet class.This occurs
automatically after the applet is initialized.Starting can also occur if the applet is already in ―stopped‖
(idle) state. For example, we may leave the web page containing the applet temporarily to another page
and return back to the page.This again starts the applet running. Note that, unlike init() method
, the start() method may be called more than once.We may override the start() method to create a
thread to control the applet.

public void start()


{
…………………
…………………(Action)
…………………
}

Idle or Stopped State

An applet becomes idle when it is stopped from running. Stopping occurs automatically when we
leave the page containing the currently running applet.We can also do so by calling the stop()
Method explicitly. If we use a thread to run the applet , then we must use stop() method to
terminate the thread.We can achieve by overriding the stop() method:
public void stop()
{
……………….
………………..(Action)
……………….
}

Dead State

An applet is said to be dead when it is removed from memory.This occurs automatically by invoking
the destroy() method when we quit the browser.Like initialization, destroying stage occurs only once
in the applet‘s life cycle.If the applet has created any resources, like threads, we may override the
destroy() method to clean up these resources.

public void destroy()


{
……………….
………………..(Action)
……………….
}

Display State

Applet moves to the display state whenever it has to perform some output operations on the
screen.This happens immediately after the applet enters into the running state. The paint() method is
called to accomplish the task.Almost every applet will have a paint() method.Like other methods in
the life cycle, the default version of paint() method does absolutely nothing. We must therefore
override this method if we want anything to be displayed on the screen.

public void paint (Graphics g)


{
………………….
………………….(Display statements)
………………….
}
It is to be noted that the display state is not considered as a part of the applet‘s life cycle.Infact , the
paint() method is defined in the Applet class.It is inherited from the Component class, a super class
of Applet.

Applet HelloJavaParam
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{
String str;
public void init()
{
str = getParameter(―string‖); // Receiving parameter
value if (str == null)
str = ―Java‖;
str = ―Hello‖ + str; //Using the value
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}

Now, let us create HTML file that contains this applet.


The HTML file for HelloJavaParam applet

<HTML>
<! Parameterized HTML file>
<HEAD>
<TITLE>Welcome to Java Applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE = HelloJavaParam.class
WIDTH = 400
HEIGHT = 200>
<PARAM NAME = ―string‖
VALUE = ―Applet ! ―>
</APPLET>
</BODY>
</HTML>
Save the file as HelloJavaParam.html and then run the applet using the appletviewer as follows:

appletviewer HelloJavaParam.html
CHAPTER-9

AWT Components
ABSTRACT WINDOW TOOLKIT (AWT)
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT
feature include:
  A rich set of user interface components i.e. (Button, TextArea, ScrollBar etc);
  A robust event-handling model;
 Graphics and imaging tools, including shape, color and font classes;

Button Class
This class creates a labeled button. The application can cause some action to happen when
the button is pushed.
If an application wants to perform some action based on a button being pressed and released,
it should implement ActionListener and register the new listener to receive events from this button,
by calling the button‘s addActionListener method. The application can make use of the button‘s
action command as a messaging protocol.

Label Class
A Label object is a component for placing text in a container. A label displayes a single line of read-
only text. The text can be changed by the application, but a user cannot edit it directly.

For example, the code….


setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
add(new Label(―Hi There!‖)); add(new Label(―Another
Label‖));
produces the following label:

Hi There! Another Label


TextField Class

A TextField object is a text component that allows for the editing of a single line of text.
For example, the following image depicts a frame with four text fields of varying widths. Two
of these text fields display the predefined text ―Hello‖.

I I tf2
tf1

tf3 Hello

tf4 Hello

Applet started

Here is the code that produces these four text fields:


TextField tf1, tf2,tf3,tf4;
// a blank text field
tf1 = new TextField();
// blank field of 20 columns
tf2 = new TextField(― ―,20);
//predefined text displayed
tf3=new TextField(―Hello!‖);
//predefined text in 30 columns
tf4=new TextField(―Hello‖,30);
Every time the user types a key in the text field, AWT sends two action events to the text field. The
first one represents the key press and the second one, the key release.Each action event embodies
the state of the system at the time that some action occurred. The properties of an action event
indicate which key was pressed, what modifier keys were also pressed, and the time at which the
event occurred.

Checkbox Class
A check box is a graphical component that can be in either an ―on‖ (true) or ―off‖ (false) state.
Clicking on a check box changes its state from ―on‖ to ―off‖ or from ―off‖ to ―on‖.

The following code example creates a set of check boxes in a grid layout:
setLayout(new GridLayout(3,1));
add(new Checkbox(―one‖,null,true));
add(new Checkbox(―two‖));
add(new Checkbox(―three‖));
Choice Class
The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of
the menu.
The following code example produces a pop-up menu:
Choice ColorChooser = new Choice();
ColorChooser.add(―Green‖);
ColorChooser.add(―Red‖);
ColorChooser.add(―Blue‖);

List Class
The List component presents the user with a scrolling list of text items. The list can be set up so that
the user can choose either one item or multiple items.

For example , the code…..


List lst = new List(4,false);
lst.add(―Mercury‖);
lst.add(―Venus‖);
lst.add(―Earth‖);
lst.add(―JavaSoft‖);
lst.add(―Mars‖);
lst.add(―Jupiter‖);
lst.add(―Saturn‖);
lst.add(―Uranus‖);
lst.add(―Neptune‖);
lst.add(―Pluto‖);
cnt.add(lst);

where cnt is a container.


Chapter-10

Working with Event


EVENT HANDLING
Event handling ia at the core of successful applet programming . Most ,event to which
your applet will respond are generated by the user. These events are passed to your applet in a
variety of ways, with the specific method depending upon the actual event. There are several types of
events. The most commonly handled events are those henerated by the mouse,, the keyboard, and
various controls, such as apuch button.Events are supported by the java.awt.event package.

Events :
In the delegation model, an event is an object that describes a state change in a
source.It can be generated as a consequence of a person interacting with the elements in a graphical
user interface. Some of the activities that cause events to the generated are passing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse.

Event Listener Interfaces:


As explained, the delegation event model has two parts: sources and listeners.
Listeners are created by implementing one or more of the interfaces defined by the java.awt.event
package. When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument. Table 20-3 lists commonly used listener
interfaces and brief description of he methods that they define. The following sections examine the
specific methods that are contained in each interface.

The ActionListener Interface


This interface defines the actionPerformed() method that is invoked when an action
event occurs. Its general form is shown here:

Void acionPerformed(ActionEvent ae)


The ItemListener Interface
This interface defines the itemStateChanged () method that is invoked when tha state ogf an
item changed. Its general form is shown here:

Void itemStateChanged(ItemEvent ie)

The MouseListener Interface


This interface defines five methods. If the mouse is pressed at the same point, mouseClick() is
invoked. When the mouse entered a component, the mouseEntered() method is called. When it leaves,
mouseExited() is called. The mousePressed() and mouseReleased() methods when the mouse is
pressed and released,respectively.
The general forms of these methods are shown here:
Void mouseClicked(MouseEvent me)
Void mouseEntered(MouseEvent me)
Void mouseExited(MouseEvent me)
Void mousePressed(MouseEvent me)
Void mouseReleased(MouseEvent me)
The WindowLitener Interface
This inteface defines seven methods. The windowActivated() and windowDeactivated()
method are invoked when a window is activated or deactivated,respectively. If a window is
iconified, the windowIconified() method is called. When the window is deiconified, the
windowDeiconified() method is called . When a window is opened or closed, the
windowOpned()
Or windowClosed() method are called, respectively. The windowClosing() method is called
when a window is being closed. He general from of these methods are.

Void windowActivated(WindowEvent we)


Void windowClosed(WindowEent we)
Void windowClosig(WindowEvent we)
Void windowDeactivated(WindowEvent we)
Void windowDeiconified(WindowEvent we)
Void windowIconified(WindowEvent we)
Void windowOpened(WindowEvent we)
Chapter-11

Frames and Menus


Window
The window class creates a top-level window. A top-level window is not contained within any
object; it sits sirectly on the desktop . Generally, you won‘t create Window object directly. Instead ,
you will use a subclass of Window called Frame.

Frame
Frame encapsulates what is commonly though of as a ―window‖. It is subclass of Window an
has a title bar, menu bar, border, and resizing corner. If you create a Frame object within an applet, it
will obtain a warning message, such as ― Java Applet Window‖ to the user that an applet window has
been created. This message warns trhat the window they see was created by an applet and not by
software running on their computer. When a Frame window is created by a programe rather than an
applet , a normal window is created.

Working with Frame Windows


After the applet, the type of window you will most often create is derived from Frame. You will
use it to create child window within applet, and top-level or chilled windows for application. As
mentioned, it creates a standard-style window.
Here are two of Frame‘s constructors:

Frame()
Frame(String title)
The first form create a standard window that does not contain a title. The second form create
a window with the title specified by title . Notice that you can not specify the dimentions of the
window. Instead, you must set the size of the window after it has been created

Creating a Frame Window in an applet

While it is possible to simply create a window by creating an instance of b Frame, you will
seldom do so, because you will not able to to much it. For example, you will not be able to receive or
process events that occur within it or easily output information to it. Most of the time, you will create
a subclass of Frame . Doing so let‘s you override Frame‘s methods and event handling.

// creating a child frame window from within a


applet import java.awt.*;
import java.awt.event..*;
import java.applet.*;
//create a subclass of frame
class SampleFrame extends Frame{
samplerame(String titile){
supper(title);
//create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
//register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g){
g.drawstring(―This is in frame window‖,10,40);
}
}
class MyWindowAdapter extends WindowAdapter{
SampleFrame sampleFrame;
Public MyWindowAdapter(SampleFrame sampleFrame){
This.sampleFrame= sampleFrame;
}
Public void windowClosing(WindowEvent we){
SampleFrame.setVisible(false);
}
}

//Create Frame windows


public class AppletFrame extends Applet{
Frame f;
Public void init(){
f = new SampleFrame(―A Frame window‖);
f.setSize(250,250);
f.setVisible(true);
}
public void start(){
f.setVisible(true);
}
public void stop(){
f.setVisible(false);
}
public void paint(Graphics g){
g.drawstring(―This is an applet window‖,10,12);
}
}
Using Menus

Several classes provide menu functionality in the AWT. These classes do not inherit from
Component,since many platforms place serve limits on menu capabilities.Instead, menu classes
inherit from the MenuComponent class. The AWT provides the folloeing MenuComponent subclasses
to support menus :
1. MenuItem: Each item in a menu is represented by a MenuItem object
2. CheckboxMenuItem: Each menu item that contain a checkbox is represented by a
CheckboxMeniItem object. CheckboxMenuItem is a subclass of Menutem.
3. Menu : Each menu is represented by a Menu object.Menu is implemented as a subclass of
MenuItem so that you can easily create a submenu by adding one to another.
4. MenuBar: Menu bars are implemented by the MenuBar class. A MenuBar represents the
platform-dependent notion of a group of menus attached to a window.
Chapter-12

Layouts
Layout Manager

The layout manager classes are a set of classes that implement the
java.awt.LayoutManager interface and help to position the component in a container. The
interface takes the task of laying out the child component in the container.This task is achieved
by resizing and moving the child container. This task is achieved by resizing and moving the child
components. The advantage of this type of machanism is that when the container is resize the
layout manager automatically update the interface.

The basic layout manager include

1. FlowLayout
2. BorderLayout
3. Gridyout
4. CardLayout

FlowLayout

A flow layout arrange components in the left-to-right flow,much like lines of text in
a paragraph.Flow layout are typically used to arrange buttons in a panel.It will arrange buttons left
to right until no more buttons fit on the same line. Each line is centered.
For example, the following programe shows an applet using the flow layout manager
to position three buttons:

Import java.awt.*;
Import java.applet.Applet;
Public calss myButtons extends Applet{
Button button1,button2,button3;
Public void init(){
button1=new Button(―ok‖);
button2=new Button(―Open‖);
button3=new Botton(―close‖);
add(button1);
add(button2);
add(button3);
}
}
A flow layout lets each component assume its natural size;

GridLayout

The GridLayout class is a layout manager that lays out a container‘s components in a
rectangular grid. The container is divided into equal-sized rectangles, and one component is
placed in each rectangle

Example
Import java.awt.*;
Import java.applet.*;
Public calss GlayoutEx extends Frame
{
Button b1, b2, b3, b4, b5, b6;

Public GlayoutEx()
{
setLayout(new GridLayout93,5));
b1=new Button(―a1‖);
b2=new Button(―a2‖);
b3=new Button(―a3‖);
b4=new Button(―a4‖);
b5=new Button(―a5‖);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setSize(400,400);
setVisible(true);
}
public static void main(String srgs[])
{
GlayoutEx gex=new GlayoutEx();
}
}

BorderLayout
A border layout lays out a container, arranging and resizing its components to fit in
five regions: north, east, west, and center. Each region is identified by the corresponding
constant: NORTH, SOUTH, WEST, and CENTER. When adding a components to a container with a
border layout, ues one of these five constant.

In additon, BorderLayout support four relative positioning constants,


BEFORE_FIRST_LINE, AFTER_LAST_LINE, BEFORE_LINE_BEGINS, and AFTER_LINE_ENDS. In a
container whose Component Oriented is set to ComponentOrientation.LEFT_TO_RIGHT,these
constants map to NORTH,SOUTH,WEST,and EAST, respectively.
Mixing the two types of constants can lead to unpredictable results. If you use both
types, the relative constants will take precedence. For example, if you add components using
both the NORTH and BEFORE_FIRST_LINE constants in a container whose orientation is
LEFT_TO_RIGHT,only the BEFORE_FIRST_LINE will be layed out.
Card Layout
A card Layout object is a layout object manager for a containet. It treats each
component in the container as a card. Only one card is visible at a time, and the container acts as
a stack of cards. The first component added to a Card Layout object is the visible component
when the container is first displayed.
The ordering of cards is determined by the container‘s own internal ordering of its
component objects. Card Layout defines a set of methods that allows an application to flip
through these cards sequentially, or to show a specified card. The
CardLayout#addLayoutComponent method can be used to associate a string identifier with a
given card for fast random access.
Chapter-13

Frames, Panes and Panels


Introduction to JFC
JDK1.2 was introduce with a new set of packages- the java Foundation Classes, or JFC-that
include an improve user interface calles the Swing component.
The Java Foundation Classes(JFC) were developed, to address the shortcomings of AWT. The
development of JFC was unique. JFC 1.2 is an extansion of the AWT container class. The method
contained in the Component and Container classes that AWT programmers are familiar with are still
valid for JFC visual classes.

Swing
Swing component facilitate efficient graphical user interface(GUI) development. These component
are a collection of lightweight visul components. Swing component contain a replacement for the
heavyweight AWT components as well as complex uesr-interface components such as trees and
tables.
The major difference between lightweight and heavyweight componenta is that lightweight
components can have transparent pixel while heavyweight components are always
opaque.Lightweight component can be non rectangular while heavyweight components are always
rectangular.

JPanel
Jpanle is a generic lightweight container.The primary purpose of the class is to provide a concrete
container for the JFC. The JPanel class is provided ti give a concrete container class.Being a

extansion of the Jcomponent class,Jpanle is a container and inherits the features contained in
that class
The following code illustrates the usages of JPanel

Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;
Import javax.swing.*;
Class panel extends Jframe{
Public panle(){
SetTitle(―Box 1‖);
Jpanle contentpane=(Jpane)getContentPane();
Contentpane.setLayout(new GridLayout());
JButton ok=new Jbutton(―OK‖);
Contentpane.add(ok);
Jbutton cancel=new Jbutton(―CANCEL‖);
Contentpane.add(cancel);
Myadapter myapp=new myadapter();
AddWindowListener(myapp);
}
private class myadapter extends WindowAdapter{
public void windowClosing(WindowEvent e){
system.exit(0);
}
}
public static void main(String args[]){
panle b= new panle();
b.setSize(400,400);
b.setVisible(true);
}
}
JFrame
This is an extension of the AWT Frame class. An instance of the Jframe class is a
heavyweight component. It creates a top-level class that con be positioned and resized
independently.
The JFrame can be created using the constructors mentioned below

Constructors Description
JFrame() Create a new JFrame that is initially invisible
JFrame(String title) Create a new JFrame,initially invisible with the
specified title

JApplet

The JApplet class is an extension of the AWT applet class. This class is the preferred entry
point when creating applet that contain JFC components. The structure of the JApplet calss is the
same as that of the JFrame class. It contains an instance of the JrootPane class as its Child.
Components are added to to ContentPane

The following code illustrate the usages of JApplet


Import java.awt.event.*;
Import java.awt.*;
Import javax.swing.*;
Public class Applets extends JApplet{
Jbutton but;
Public void init(){
Jpanle contentpane=(Jpanle)getContentPane());
But=new Jbutton(―Dispalyed in an Applet‖);
Contentpane.add(but);
}
}
CHAPTER-14

Lists, Combo Boxes, Scrollers and Sliders


Combo Boxes
Swing provides a combo box through the JcomboBox class,which extends Jcomponent. A
combo box normally displays one entry.However ,it can also display a drop-down list that allows a
user to select a different entry.Two of JcomboBox‘s constructor are shown here:
JcomboBox()
JcomboBox(Vector v)
Here, v is a vector that initialized the combo box.
Item are added to the list of choices via the addItem() method, whose signature is shown
here

Void addItem(Object obj)


Here,obj is the object to be added to the combo box

Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class JcomboBoxDemo extends JApplet
Implements ItemListener {
Jlabel ji;
ImageIcon france,germany,italy, japan
Public void init(){
Container contentPane = getContentPane();
ContentPane.setLayout(new FlowLayout());
JcomboBox jc = new JcomboBox();
Jc.addItem(―France‖);
Jc.addItem(―germany‖);
Jc.addItem(―Itally‖);
Jc.addItem(―Japan‖);
Jc.addItemListener(this);
ContentPane.add(jc);

// create label
jl = new Jlabel(new ImageIcon(―france.gif‖);
contentPane.add(jl);
}
public void itemStateCahnged(ItemEvent ie){
String s = (String)ie.getItem();
Jl.setIcon(new ImageIcon(s + ―.gif‖));
}
}
Jlist
A Jlist is functionally similar to JcomboBox menu in that it allows the user to select one or
more objects from alist of choices. A Jlist will generate events when its selection changes,or when
any of its items changes . The differences between a Jlist and JcomboBox menu are given below

1. Unlike JcomboBox,which displays only the single-selected item, the list can be made to
show any number of choices in the visible window.
2. The Jlist can be constructed to allow multiple selection.

ScrollPane

A scroll pane is a component that presents a rectangular areas in which a component may be
viewed. Horizontal and/or vertical scroll bars may be provided if necessary .Scroll panes are
implemented in swing by the JscrollPane class,which extends Jcomponent.Some of it constructor
are shown here:
JscrollPane(Component comp)
JscrollPane(int vsb,int hsp)
JscrollPane(Component comp,int vsb,int hsb)
Here comp is the component to be added to the scroll pane pane.vsb and hsb are int constants that
define when vertical and horizontal scroll bars for this scroll pane are shown.
CHAPTER-15

Menus and Tooltips


A menu facilitates us to utilize all the capabilities of an application. A menu actually contains a list
of items using which one can set properties, display and hide application window and dialogs, exit
the application, navigate help and perform numerous other activities. A swing menu contains three
kinds of objects, namely, menu bar, menu items and menus. The menu bar is an object that acts as
the root for all menus and menu items. Menus are a special kind of menu items that stores a list of
menu items that will be displayed when the menu item is selected.

The Menu Components


The menu components are components, which will be attached to the menu. The following are
the menu components
JMENUBAR JMENUITEM
JMENU JCHECKBOXMENUITEM
JPOPUPMENU JRADIOBUTTONMENUITEM

JMenuBar
This component typically appears at the top of a JFrame, JWindow and JInternalFrame. It cannot be
added directly to the frame. It can be added only through the JFrame, Jwindow and JinternalFrame‘s
root pane. A JMenuBar is a component that can be added to a container similar to any other
component. It contains a set of Jmenus, with each Jmenu represented as a string within the
JMenuBar. When the user clicks one of the text strings, the associated menu pops up under the text
string and displays its menu items.

Steps in Creating a JMenuBar


Create the menu bar. There is only one constructor in this class.
JMenuBar mb=new JMenuBar();
Components, which implement MenuElement interface, can be added to the menu bar. Generally
Jmenu components will be added to the menu bar. Create a Jmenu and add some items into it.

Jmenu jm=new Jmenu(―Edit‖);


JmenuItem m1=new JmenuItem(―Cut‖);
JmenuItem m2=new JmenuItem(―Copy‖);
Jm.add(m1);
Jm.add(m2);

Now add the menu to the menu bar.


Mb.add(jm);

The next step is to add the menu bar into the JFrame. Normally the menu bar will be placed under
the title bar of the JFrame or JInternalFrame. These components use their root pane to hold menu

bars. Components with JRootPanes typically have a convenient method called setJMenuBar. Using
this
method, menu bar can be added in to the JFrame.
MyFrame.setJMenuBar(mb);
JMenu
This component actually appears in two ways. When this component is added to a JMenuBar, it
appears as a text string. When the user clicks on that text string, the JMenu expands the ral menu
under its menu bar string, displaying all of its menu items.Only one menu can be selected at a time
in the menu bar.

JPopupMenu
JPopupMenu component is used to display an expanded form of menu. There are two ways in which
this component can be used. It can be used as part of a JMenu or used by itself as a menu that can
be displayed anywhere on the applet. A JPopupMenu looks like a rectangular window that contains
a list of items, which will be displayed when a menu is clicked. These menu items are normally any
component that implement the MenuElement interface. The standard menu items that are added to
the JPopupMenu are JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem.

JMenuItem
A menu item is essentially a button in a list. When the user selects the button, the action associated
with the menu item is performed. A JmenuItem contained in a JPopupmenu performs exactly that
function. This component typically appears as a text String possibly with an icon in a Jmenu or
JPopupmenu. Pressing a JmenuItem does not change its appearance as JButton does. One thing to
be noticed here is that when the user clicks and releases the mouse on a JmenuItem, the menu that
contains this item will disappear from the screen and the corresponding dialog box will be
displayed for that menu item.

JCheckBoxMenuItem
From the name of the component it is understood that this menu item will contain one of the
JComponents called JCheckbox as menu items. A JcheckBoxMenuItem will always either be selected
or deselected and its appearance shows its current state. When a JcheckBoxMenuItem is selected it
has a mark next to it. If it is not selected , there is not checkmark. This component can also have a
string or an icon. The properties of JcheckBoxMenuItem can also be change. This is one of the great
features, which makes it possible to control the components appearance.

JRadiioButtonMenuItem
JRadioButtonMenuItems belongs to a single ButtonGroup so that only one can be selected at any
point to time. A JradioButtonMenuItems has a string or an icon and display it current state, i.e,
whether it is selected or deselected, by placing a dot to the left of the text icon. The icon in the
menu items are only for decoration purposes. The icon will not change the current state when the
user select or deselects the JradioButtonMenuItem.
The following code illustrates the usage of Menus:

Import java.util.*;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Import javax.swing.event.*;
Public class Menus extends JPanel implements ActionListener, MenuListener
{
JTextField field;
Public Menus(JFrame frm)
{
JMenuBar bar=new JMenuBar();
JMenu menu=new JMenu(―Emp.Names‖);
JmenuItem tmp;
SetBackground(Color.lightGray);
SetLayout(new BorderLayout());
SetDoubleBuffered(true);
Menu.addMenuListener(this);
Tmp=new JmenuItem(―‖Robert‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Robert‖);
Menu.add(tmp);
Tmp=new JmennuItem(―Mohammed‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Mohammed‖);
Menu.add(tmp);
Tmp=new JMenuItem(―vinod‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―vinod‖);
Menu.add(tmp);
Tmp=new JMenuItem(―Quit‖);
Tmp.addActionListener(this);
Tmp.setActionCommand(―Quit‖);
Menu.add(tmp);
Bar.add(menu);
Frm.setJMenubar(bar);
Field=new JtextField(10);
Field.addActionListener(this);
Field.setActionCommand(―Text Filed Activated‖);
Add(field,‖South‖);
}
public void actionPerformed(ActionEvent e)
{
Stribg cmd;
Cmd=e.getActionCommand();
Field.setText(―Action:‖+cmd);
If(cmd.equals(―Quit‖))
{
System.exit(0);
}
}
public void menuSelected(MenuEvent e)
{
field.setText(―Menu selected‖);
}
public void menuDeselected(MenuEvent e)
{
field.setText(―Menu deselected‖)
}
public void menuCanceled(MenuEvent e)
{
field.setText(―Menu canceled‖);
}
public Dimension getPreferredSize()
{
return new Dimension(200,100);
}
public static void main(String s[])
{
JFrame frame=new JFrame(―Menus‖);
Menus panel=new Menus(frame);
Frame.setForeground(Color.black);
Frame.setBackground(Color.lightGray);
Frame.addWindowLstener(new WindowCloser());
Frame.getContentPane().add(panel,‖center‖);
Frame.setSize(panle.getPreferredSize());
Frame.setVisible(true);
}
}
class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window win=e.getWindow();
Win.setVisible(false);
System.exit(0);
}
}

You might also like