0% found this document useful (0 votes)
37 views181 pages

Introduction to Java Programming Basics

The document provides an introduction to Java, detailing its history, features, and structure. It explains the evolution of Java from its inception as Oak to its current status as a popular language for enterprise applications and mobile platforms. Additionally, it covers the Java Development Kit, program structure, data types, keywords, and operators in Java.

Uploaded by

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

Introduction to Java Programming Basics

The document provides an introduction to Java, detailing its history, features, and structure. It explains the evolution of Java from its inception as Oak to its current status as a popular language for enterprise applications and mobile platforms. Additionally, it covers the Java Development Kit, program structure, data types, keywords, and operators in Java.

Uploaded by

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

1.

INTRODUCTION TO JAVA

 History of JAVA:-

 Around 1990 James Gosling, Bill Joy and others at Sun Microsystems began developing a
language called Oak. The wanted it primarily to control microprocessors embedded in consumer
items such as cable set-top boxes, VCR’s, toasters, and also for personal data assistants (PDA).
 To serve these goals, Oak needed to be:
Platform independent (since multiple manufacturers involved)
Extremely reliable
Compact.
 However, as of 1993, interactive TV and PDA markets had failed to take off. Then the Internet and
Web explosion began, so Sun shifted the target market to Internet applications and changed the
name of the project to Java.
 By 1994 Sun's HotJava browser appeared. Written in Java in only a few months, it illustrated the
power of applets, programs that run within a browser, and also the capabilities of Java for speeding
program development.
 Riding along with the explosion of interest and publicity in the Internet, Java quickly received
widespread recognition and expectations grew for it to become the dominant software for browser
and consumer applications.
 However, the early versions of Java did not possess the breadth and depth of capabilities needed
for client (i.e. consumer) applications. For example, the graphics in Java 1.0 seemed crude and
clumsy compared to mature software developed with C and other languages.
 Applets became popular and remain common but don't dominate interactive or multimedia displays
on web pages. Many other "plug-in" types of programs also run within the browser environment.
 So Java has not succeeded at development of consumer applications. However, Java's capabilities
grew with the release of new and expanded versions (see below) and it became a very popular
language for development of enterprise, or middleware, applications such as on line web stores,
transactions processing, database interfaces, and so forth.
 Java has also become quite common on small platforms such as cell phones and PDAs. Java is now
used in several hundred cell phone models. Over 600 million JavaCards, smart cards with
additional features provided by Java, have been sold as of the summer of 2004.

 What is JAVA?
The term Java actual refers to more than just a particular language like C or Pascal. Java
encompasses several parts, including :
A high level language:- The Java language is a high level one that at a glance looks very
similar to C and C++ but offers many unique features of its own.
Java bytecode:- a compiler, such as Sun's javac, transforms the Java language source code to
bytecode that runs in the JVM.
Java Virtual Machine (JVM):- A program, such as Sun's java, that runs on a given platform and
takes the bytecode programs as input and interprets them just as if it were a physical processor
executing machine code.
 Sun provides a set of programming tools such as javac, java and others in a bundle that it calls a
Java Software Development Kit for each version of the language and for different platforms such
as Windows, Linux, etc.
 Sun also provides a runtime bundle with just the JVM when the programming tools are not needed.

[Link] Institute of Technology-560056


 Note that because of the open nature of Java (see below), any or all of these parts can be replaced
by non-Sun components. For example, just as many different languages can create machine code
for a given processor, compilers of other languages have been created that output bytecode to run
in the JVM. Similarly, many JVMs have been written by groups outside of Sun.
 In this book and web course, when we use the term Java we are referring to the the high level
language unless noted otherwise. Also, those packages that come with the SDK for a given version
will be referred to as comprising the core language for that version, as distinguished from optional
or third party packages.

 Java Virtual Machine(JVM):

 Java Virtual Machine or JVM as its name suggest it is a “virtual” machine that resides in the “real”
computer as a software.
 JVM gives Java the flexibility of platform independence. Let us see first how exactly Java program
is created, compiled and executed.
 Java code is written in .java file.
 This code contains one or more Java language attributes like Classes, Methods, Variable, Objects
etc.
 Javac is used to compile this code and to generate .class file. Class file is also known as “byte
code“.
 The name byte code is given may be because of the structure of the instruction set of Java
program.
 Java byte code is an input to Java Virtual Machine. JVM read this code and interpret it and
executes the program

 Java Virtual Machine like its real counterpart, executes the program and generate output. To
execute any code, JVM utilizes different components.
 JVM is divided into several components like the stack, the garbage-collected heap, the registers
and the method area. Let us see diagram representation of JVM.

 Features of JAVA:

 Simple
 Object oriented
 Compiled and interpreted
2
[Link] Institute of Technology-560056
 Platform independent
 Robust and secure
 Distributed
 Multithreaded
 High performance
 Dynamic

 Simple:-
Java is a small and simple language. Java doesn’t use pointers, preprocessor header files,
GOTO statement and many others. It also eliminates operator overloading and multiple
inheritance.

 Object oriented:-
Java is a true object oriented language. All program code and data reside within objects and
[Link] becomes extensive set of class.
Advantage of Object oriented programming:
Simpler, easier to read programs
More efficient reuse of code
Faster time to market
More robust, error-free code

 Compiled and interpreted:-


Usually a computer language is either compiled or [Link] combines both these
features thus making java a Two-stage system.
java compiler translates source code into bytecode instructions.
Bytecodes are not machine instructions and therefore in the second stage Java interpreter
generates machine code then execute the java program.
Thus we can say java is both compiled and interpreted language.

 Platform independent and portable:-


The most important features of java over other languages are its portability.
Java programs can be easily moved from one computer to another, anywhere and any
[Link] and upgrades in operating systems, and system resources will not force any
changes in java programs.
Java ensures portability in two ways. First java compiler generates bytecode instructions that
can be implemented on any machine. Secondly, the sizes of the primitive data types are machine-
independent.

 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.
Security becomes an important issue for a language that is use for programming on internet.
Threat of viruses and abuse of resources are everywhere. Java systems not only verify all
memory access but also ensure that no viruses are communicated with an applet.

 Distributed:-
Java is designed as a distributed language for creating applications on networks. It has ability
to share both data and programs.

 Multithreaded:-

[Link] Institute of Technology-560056


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.

 High performance:-
Java performance is impressive for an interpreted language, due to the use of intermediate byte
code.

 Dynamic:-
Java is a dynamic language. Java is capable of dynamically linking new class libraries,
methods, and objects.

 Java Development Kit(JDK):-


 The java development kit comes with a collection of tools that are used for developing and running
java programs. They include:

TOOL DESCRIPTION
Appletviewe Enables us to run java applets
Javac The java compiler, which translates java source code to bytecode file.
Java Java interpreter that interpreting bytecode files.
Javadoc Creates HTML –format document from java source code files.
javah Produces header files
javap Java disassembler, which enables us to convert bytecode into program description.
Jdb Java debugger, which helps us to find errors in our programs.

 The JDK. It consists of a framework of about 3700 classes. These classes must be implemented
according to this specification in every JDK. Sun defines this specification.
 The Java Platform, or JDK, has evolved over time so there are several versions of it.
 The latest major version is Java SE 7 or JDK 7.
 Our applications are mostly written against either version 1.4 or 5, which are both still supported
by Sun.
 Even though the Java Platform is often called the JDK, the correct definition is very different.
 As originally defined, the Java Development Kit (JDK) is actually a combination of Java
compilation tools and API implementation for a particular version of the Java Platform.
 It also typically includes a Java runtime (JRE), so that you can run the programs you compile.

 Explain Java Program Structure?

4
[Link] Institute of Technology-560056
 Documentation Section
The documentation section comprises a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to refer to at a later stage. We
use comment for documentation.

 Package Statement
The first statement allowed in a Java file is a package statement.
This statement declares a package name and informs the compiler that the classes defined here
belong to this package.
The package statement is optional. That is, our classes do not have to be part of a package.

 Import Statements
The next thing after a package statement (but before any class definitions) may be a number of import
statements. This is similar to the #include statement in C.

 Interface Statement
An interface is like a class but includes a group of method declarations.
It is new concept in java. This is also an optional section and is used only when we wish to
implement the multiple inheritance features in the program.

 Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a Java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.

 Main Method Class


Since every Java stand –alone program requires a main method as its starting point ,this class
is the essential part of a Java program.

[Link] Institute of Technology-560056


 Explain the Basic Structure of JAVA Program.

 Let us see now how the simple java program will look like. You can use any editor like notepad or
any Java IDE for writing java programs.
class Sample
{
public static void main (String args[])
{
[Link] (“JAVA IS BETTER”);
}
}

Here class Sample declares a class


class is a keyword and declares that a new class definition.
Every class definition in java begins with an opening brace “ { “ and ends with a matching
brace “ } “,appearing in the last line in the example.
public static void main(String args[ ])
Defines a method name main. Conceptually this is similar to the main () function in
C/C++.
Every java application program must include the main () method.
This line contains a number of keywords, public, static and void.

public The keyword public is an access specifier that declares the main method as
unprotected & therefore making it accessible to all other classes.
static The keyword Static, which declares this method as one that belongs to the
entire class and not a part of any object
void The type modifier void states that the main method does not return any value.

The only executable statement in the program is [Link](“JAVA IS BETER”);


The println() method is a member of the out object, which is a static data member of system
class.

 DATA TYPES:

 Every variable in java has a data type. Data types specify the size and type of values that can be
stored. The variety of data types available allows the programmer to select appropriate types.
 There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
 Primitive Data Types:
There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word. Let us now look
into detail about the eight primitive data types.

6
[Link] Institute of Technology-560056
 PRIMITIVE DATA TYPES:

Primitive data types is divided into four groups.

Group Name Data types Size(in bits) Range


byte 8 -128 to 127
short 16 -32768 to 32767
Integers
int 32 -231 to 231-1
long 64 -263 to 263-1
float 32 1.4e-045 to 3.4e+038
Floating point numbers
double 64 4.9e-324 to 1.8e+308
Characters
(also use Unicode char 16 0 to 65536
characters)
Boolean boolean 1 NA

 ESCAPE SEQUENCE IN JAVA

 Java language supports few special escape sequences for String and char literals as well. They are:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)

 KEYWORDS IN JAVA

 Keywords are reserved words that are predefined in the language; see the table below. All the
keywords are in lowercase.

abstract boolean break byte case catch


char class const continue default do
double else extends final finally float
for goto if implements import instanceof
int interface long native new package
private protected public return short static
strictfp super switch synchronized this throw
throws transient try void volatile while

 An identifier is composed of a sequence of characters where each character can be a letter, a digit,
an underscore, or a dollar sign.

[Link] Institute of Technology-560056


 An identifier declared by the programmer cannot be a Java keyword and it cannot start with a digit.
For instance:

 OPERATORS IN JAVA

 Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Conditional(ternery) operators
Bitwise operators

 Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A =10 and variable B =20 then:

Operator Description Example


+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand A - B will give -10
operand
* Multiplication - Multiplies values on either side of the A * B will give 200
operator
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand B % A will give 0
and returns remainder
++ Increment - Increase the value of operand by 1 B++ gives 21
-- Decrement - Decrease the value of operand by 1 B-- gives 19

 The following simple example program demonstrates the arithmetic operators. Copy and paste
following Java program in [Link] file and compile and run this program.
class Test
{
public static void main(String args[])
{
int a = 10; a + b = 30
int b = 20; a - b = -10
int c = 25; a * b = 200
int d = 25; b/a=2
[Link]("a + b = " + (a + b) ); b%a=0
[Link]("a - b = " + (a - b) ); c%a=5
[Link]("a * b = " + (a * b) ); a++ = 10
[Link]("b / a = " + (b / a) ); b-- = 11
[Link]("b % a = " + (b % a) ); d++ = 25
[Link]("c % a = " + (c % a) ); ++d = 27
[Link]("a++ = " + (a++) );
[Link]("b-- = " + (a--) );
// Check the difference in d++ and ++d
[Link]("d++ = " + (d++) );
[Link]("++d = " + (++d) );
8
[Link] Institute of Technology-560056
}
}

 Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:

Operato Description Example


r
== Checks if the value of two operands is equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Checks if the value of two operands is equal or not, if values (A != B) is true.
are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand, if yes then condition becomes
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

The following simple example program demonstrates the relational operators. Copy and paste
following Java program in [Link] file and compile and run this program.
class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
[Link]("a == b = " + (a == b) );
[Link]("a != b = " + (a != b) );
[Link]("a > b = " + (a > b) ); a == b = false
[Link]("a < b = " + (a < b) ); a != b = true
[Link]("b >= a = " + (b >= a) ); a > b = false
[Link]("b <= a = " + (b <= a) ); a < b = true
} b >= a = true
} b <= a = false

 Logical Operators:

The following table lists the logical operators:


Assume Boolean variables A holds true and variable B holds false then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then (A && B)
condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands are non zero (A || B) is
then condition becomes true. true.

[Link] Institute of Technology-560056


! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B)
operand. If a condition is true then Logical NOT operator will make is true.
false.

class Test
{
public static void main(String args[])
{
int a = true;
int b = false;

[Link]("a && b = " + (a&&b) );

[Link]("a || b = " + (a||b) );

[Link]("!(a && b) = " + !(a && b) );


}
}

 Bitwise Operator:
Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands.
They are summarized in the following table:
Operator Name
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
<<= Shift left assignment
Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number
of times. It has this general form:
value << num
Example:
class ByteShift
{
public static void main(String args[])
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
[Link]("Original value of a: " + a);
[Link]("i and b: " + i + " " + b);
}
10
[Link] Institute of Technology-560056
}
OUTPUT
Original value of a: 64
i and b: 256 0
 Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
of times. Its general form is shown here:
value >> num
Example:
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35
>> 2
00001000 8

 Assignment Operators:

There are following assignment operators supported by Java language:

Operator Description Example


= Simple assignment operator, Assigns values C = A + B will assign value of A + B
from right side operands to left side operand into C

 Conditional Operator ( ? : ):


Conditional operator is also known as the ternary operator.
This operator consists of three operands and is used to evaluate boolean expressions.
The goal of the operator is to decide which value should be assigned to the variable.
Conditional operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
class Test {
public static void main(String args[]){
int a , b, c;
a = 10;
b=20;
c = (a<b) ? 20: 30;
[Link]( "Value of b is : " + c);
}
}

 Precedence of Java Operators:

 Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
 For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then adds into 7.

[Link] Institute of Technology-560056


Category Operator Associativity
Postfix(Highest) () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= Right to left
Comma(Lowest) , Left to right

 Java Control Statements:

 Control statements control the order of execution in a java program, based on data values and
conditional logic. There are three main categories of control flow statements;
Selection statements: if, if-else, nested if-else, else-if ladder and switch.
Iteration statements: while, do-while and for.
 We use control statements when we want to change the default sequential order of execution

 Selection Statement

 If Statement
if statement executes a block of code only if the specified expression is true.
If the value is false, then if block is skipped and execution continues with the rest of the
program.
You can either have a single statement or a block of code within if statement.
Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<condition>) <statement>
Below is an example that demonstrates conditional execution based on if statement condition.
Example:
class IfDemo
{
public static void main(String[] args)
{
int a = 67;
if(a <100)
{
[Link]("a is less than 100");
}
}
}

12
[Link] Institute of Technology-560056
 If-else Statement:-

if-else statement is an extension of the if statement.


Here condition in if statement is false then it will goes into the else block.
Note that the conditional expression must be a Boolean expression.
Syntax:
if(condition)
statement1;
else
statement2;
Below is an example that demonstrates conditional execution based on if else statement
condition.
Example:-
class IfElseDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;
if(a > b)
{
[Link]("a is maximum");
}
else
{
[Link]("b is maximum");
}
}
}

 Nested If-else:-
Syntex:-
The syntax for a nested if...else is as follows:
if(condition1)
{
if(condition2)
{
Statement-1;
else
Statement-2;
}
else
Statement-3;
}
In nested if else logic if condition1 is true then check condition2 if it is true then statement1
will be execute else statement2 will be execute.
In nested if else logic if condition -1 is false then statement -3 is execute.

[Link] Institute of Technology-560056


Example:

class NestedIfElse
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=30;

if (a>b)
{
if (a>c)
{
[Link]("a is max ");
}
else
{
[Link]("c is a max");
}
}
else
{
if (b>c)
{
[Link]("b is max");
}
else
{
[Link]("c is a max");
}
}
}
}

 If-else-if ladder:
In this if-else-if ladder, conditions are evaluated from top. First condition-1 will be evaluated and if
this is true, the code inside the if block will be executed. If condition-1 is false, condition-2 will be
evaluated.
If condition-2 is true, the code inside that else if block will be executed. If condition-2 is false,
condition-3 will be evaluated. This will go on like this.
If none of the conditions are true, the code inside the else block will be executed.
Syntex:
if(condition-1)
{
Statement1;
}
else if (condition-2)
{
Statement2;
14
[Link] Institute of Technology-560056
}
.
.
.
else if (condition-n)
{
Statement n-1;
}
else
{
Statement n;
}
Example:-
public class IfElseIfLadderDemo1
{
public static void main(String args[])
{
int test=2;

if(test==1)
{
[Link]("Hello");
}
else if(test==2)
{

[Link]("Hi");
}
else if(test==3)
{
[Link]("Good");
}
else
{
[Link]("No Match Found");
}
}
}

 Iteration statement(Looping structure):-

Loop is the control statement of any language in which whenever you want to perform the
repetitious work then you use the Loop control statement.
There are mainly three types of loops.
Loop repeats a statement or a process multiple times according to the specified conditions.
It allows the multiple statements or process to be run for the specified time or it also follows
the certain conditions.
Loop makes your program readable, flexible and reliable.

[Link] Institute of Technology-560056


 While Loop:
While loop checks the certain condition first, if the condition is true then all the statements or
processes written under the while loop are executed otherwise ignored all.
Syntax:

Initialization;
while(condition)
{
statements;
}
In this program you will see how to use the while loop statement.
This program takes the 1 to 10 number.
class test
{
public static void main(String[] args)
{
int i = 1;
while(i<=10)
{
[Link](i);
i++;
}
[Link](“Loop Complete”);
}
}

 do-while: 
In do-while loop, compiler executes some statements and processes once at least.
do-while loop is same as the while loop statement but while loop checks the condition is first
and in do-while loop executes all the statements first at once and then check the condition if the
condition is true then all the statements are also executed second times otherwise loop
terminates.
Syntax :
Initialization;
do
{
statements;

}while(condition);

In this example you will see how to use the do-while loop statement.
class test
{
public static void main(String[] args)
{
int i;
i=1;
do
{
[Link]("Number : " + i);
}while (i <=10);
}
16
[Link] Institute of Technology-560056
}
 for loop:
for loop is often used when you want to repeat a section of a program for a fixed number of
times.
Syntax:
for( initialization; condition; increment/decrement)
{
statements;
}
Initialization: It allows the variable to be initialize. Such as:
int i = 1;
int j = 1;
condition: It allows to check the certain condition. If condition is true then all statements and
processes written in the for block will be executed otherwise ignored
Condition such as:
i <= 5;
j <= i;
Increment: It allows the how much increase the given variable. Such as:
i++;
j++;
Example:-
class test
{
public static void main(String[] args)
{
int i;
for(i=1;i<=10,i++)
{
[Link]("Number : " + i);
}
[Link](“Loop Complete”);
}
}

 switch statement:

 An alternative to a series of else if is the switch statement.


 The switch statement allows you to choose a block of statements to run from a selection of code,
based on the return value of an expression.
 The expression used in the switch statement must return an int or an enumerated value.
 The syntax of the switch statement is as follows.
switch (expression)
{
case value_1 :
statement (s);
break;
case value_2 :
statement (s);
break;
.

[Link] Institute of Technology-560056


.
.
case value_n :
statement (s);
break;
default:
statement (s);
}

 Example:
class test
{
public static void main(String[] args)
{
int i = 1;
switch (i)
{
case 1 :
[Link]("One.");
break;
case 2 :
[Link]("Two.");
break;
case 3 :
[Link]("Three.");
break;
default:
[Link]("You did not enter a valid value.");
}
}
}
 Break statement:

 The break statement is used to break from an enclosing do, while, for, or switch statement.
 It is compile errors to use break anywhere else.
 'break' breaks the loop without executing the rest of the statements in the block.
 For example, consider the following code
class test
{
public static void main(String[] args)
{
int i = 0;
while (i<100)
{
if (i > 3)break;
[Link](i);
}
}
}

18
[Link] Institute of Technology-560056
 continue statement:

 The continue statement stops the execution of the current iteration and causes control to begin with
the next iteration.
 For example, the following code prints the number 0 to 9, except 5.
class test
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
[Link](i);
}
}
}

 Array:

 An array is a very common type of data structure where in all elements must be of the same data
type.
 Once defined, the size of an array is fixed and cannot increase to accommodate more elements.
 The first element of an array starts with zero
 Using and array in your program is a 3 step process -
Declaring your Array
Constructing your Array
Initializing your Array
 Syntax for Declaring Array Variables is
<elementType>[] <arrayName>;
 Example:
int a[];
int []a;

 Constructing an Array
= new [];
 Example:
a = new int[10]; // Defines that intArray will store 10 integer values

 Declaration and Construction combined


int a[] = new int[10];

 Example:First Array Program(One dimensional)


class test
{
public static void main(String args[])
{
int a[] = new int[3];
int i;
for (i=0;i<3;i++)

[Link] Institute of Technology-560056


{
a[i]=i+1;
}
for(i=0;i<3;i++)
{
[Link]("Value of array"+a[i]);
}
}
}

 Multidimensional arrays:
Multidimensional arrays, are arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another set of
square brackets.
int twoD[ ][ ] = new int[4][5] ;
When you allocate memory for a multidimensional array, you need only specify the memory
for the first (leftmost) dimension.
You can allocate the remaining dimensions separately.

Example:-1

class test
{
public static void main(String args[])
{
int a[ ][ ];
a=new int[3][3];
int i,j,k=0;
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
a[i][j] = k;
k++;
}
}
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
[Link](a[i][j]);
}
}
}
}

Example:-2
class test
{
public static void main(String args[])
{
int a[ ][ ] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };
int I,j;
20
[Link] Institute of Technology-560056
for (i=0; i<3; i++)
{
for(j=0;j<i;j++)
{
[Link](a[ I ][ j ]);
}
}
}
}

 Difference between JRE, JDK and JVM:

 In short here are few differences between JRE, JDK and JVM:
JRE and JDK come as installer while JVM are bundled with them.
JRE only contain environment to execute java program but doesn’t contain other tool for
compiling java program.
JVM comes along with both JDK and JRE and created when you execute Java program by
giving “java” command.

 Difference between Java and C

JAVA C
Java is object-oriented language. C is procedure oriented language.
Java does not support structure, union. C supports structure,union,enum.
enum.
Java does not support Pointer. C supports pointer.

[Link] Institute of Technology-560056


Java does not support Global variable C supports Global variable
Java does not support go to, sizeof, C supports goto, sizeof, typedef.
typedef.
There are no header files in java There is no. of header files in C.
Java does not support Pre-processor. C support Pre-processor.
Java does not define Type modifiers C defines Type modifiers keyword
keyword Auto, extern, register, signed, Auto, extern, register, signed, unsigned.
unsigned.

 Difference between Java and C++.

JAVA C++
Java does not support Operator C++ supports Operator overloading.
overloading.
Java does not support Template class. C++ support Template class.
Java does not support Multiple C++ supports Multiple inheritance.
inheritance but it supports interface.
Java does not support Global variable C++ support Global variable
Java does not use Pointer. C++ use Pointer.
There are no header files in java There is no. of header files In C++.
Java has replace destructor Function C++ has a constructor & also Destructor
with finalize ( ). Function.
Java does not support Pre-processor. C++ support Pre-processor.

22
[Link] Institute of Technology-560056
2. INTRODUCTION TO CLASSES

 CLASS FUNDAMENTALS:-

 A class can be defined as a template/ blue print that describe the behaviors/states
that object of its type support.
 A class is a user-defined data type with a template that serves to define its properties.
 once the class type has been defined, we can create “variable s” of that type using declarations
that are similar to the basic type declarations.
 In java, these variables are termed as instances of classes, which are the actual objects.
 The basic form of a class definition is:
Class Syntax:-
class classname
{
type instance-variable1 ;
type instance-variable2 ;
…..
…..
type instance-variableN ;

type methodname1 (parameter-list )


{
// body of method
}
type methodname2 (parameter-list )
{
// body of method
}
.....
…..
type methodnameN (parameter-list )
{
// body of method
}
}
SIMPLE CLASS

 Here is a class called Box that defines three instance variables: width, height, and depth.
 Currently, Box does not contain any methods.
class Box
{
double width;
double height;
double depth;
}
 As stated, a class defines a new type of data.
 It is important to remember that a class declaration only creates a template; it does not create an
actual object.

[Link] Institute of Technology-560056


 To actually create a Box object, you will use a statement like the following:
 Box b = new Box(); // create a Box object called b
 After this statement executes, b will be an instance of Box.
 Again, each time you create an instance of a class, you are creating an object that contains its own
copy of each instance variable defined by the class.
 Thus, every Box object will contain its own copies of the instance variables width, height, and
depth.
 To access these variables, you will use the dot (.) operator. The dot operator links the name of the
object with the name of an instance variable.
 For example, to assign the width variable of mybox the value 100, you would use the following
statement:
 [Link] = 100;
/* A program that uses the Box class. Call this file [Link] */
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box b = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
}
}
 You should call the file that contains this program [Link], because the main( ) method is
in the class called BoxDemo, not the class called Box.
 When you compile this program, you will find that two .class files have been created, one for Box
and one for BoxDemo.
 When you do, you will see the following output:
 Volume is 3000.0

 DECLARING OBJECTS:

 Object: object is a basic run time entity of the class.


 As pointed out earlier, an object in java is essentially a block of memory that contains space to
store all the instance variables.
 Object in java are created using the new operator.
 The new operator creates an object of the specified class and returns a reference to that object.
 Here is an example of creating an object of type Box.
Box b1; // declare reference to object
B1 = new Box(); // allocate a Box object

[Link] Institute of Technology-560056


 The first statement declares a variable to hold the object reference and the second one actually
assigns the object reference to the variable.
 But in reality, b1 simply holds the memory address of the actual Box object. The effect of
these two lines of code is depicted in Figure

 ASSIGNING OBJECT REFERENCE VARIABLES

 Object reference variables act differently than you might expect when an assignment takes place.
 For example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
 after this fragment executes, b1 and b2 will both refer to the same object.
 The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It
simply makes b2 refer to the same object as does b1.
 Thus, any changes made to the object through b2 will affect the object to which b1 is referring,
since they are the same object.
 This situation is depicted here:

 INTRODUCING METHODS:

 A class with only data fields has no life.


 The data contained in the class.
 Methods(functions) are declared inside the body of the class but immediately after the declaration
of instance variables.
 The general form of a methods declaration is
return type methodname (parameter-list)
{
Method-body;
}
 Method declarations have four basic parts:
 The name of the method(method name)

[Link] Institute of Technology-560056


 The type of the value the method returns(type)
 A list of parameters(parameter-list)
 The body of the method
 The type specifies the type of value the method would return.
 It could any data type or void, if the method does not return any value then its data type will be
void.
 The method name is a valid identifier.
 The parameter list is always enclosed in parentheses.

 Example:
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
void volume()
{
[Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxClass
{
public static void main(String args[])
{
Box b = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link]();
}
}
 Example:
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxClass
{
public static void main(String args[])
{
Box b = new Box();
4

[Link] Institute of Technology-560056


double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link]();
[Link]("Volume is " + vol);
}
}
 Example:
// method-1:-This program uses a parameterized method.
class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}

void setDim(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box();
double vol;
[Link](10, 20, 15);
[Link](3, 6, 9);
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}
OUTPUT of Method-1 and Method-2:-
Volume is 3000.0
Volume is 162.0

 CONSTRUCTORS:

 This automatic initialization is performed through the use of a constructor.


 A constructor will call initializes an object immediately upon creation.
 It has the same name as the class and syntactically similar to a method.

[Link] Institute of Technology-560056


 Once defined, the constructor is automatically called immediately after the object is created,
before the new operator completes.
 Constructors have no return type, not even void.
 This is because the implicit return type of a class’ constructor is the class type itself.
 Let’s begin by defining a simple constructor that simply sets the dimensions of each box to the
same values. This version is shown here:
 Example: 
/* Here, Box uses a constructor to initialize the dimensions of a box.*/
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box with no parameter.
Box()
{
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box();
Box b2 = new Box();
double vol;

vol = [Link]();
[Link]("Volume is " + vol);

vol = [Link]();
[Link]("Volume is " + vol);
}
}

OUTPUT:-
Volume is 1000.0
Volume is 1000.0

 PARAMETERIZED CONSTRUCTORS

 What is needed is a way to construct Box objects of various dimensions.


 The easy solution is to add parameters to the constructor. As you can probably guess, this makes
them much more useful.
6

[Link] Institute of Technology-560056


 For example, the following version of Box defines a parameterized constructor which sets the
dimensions of a box as specified by those parameters. Pay special attention to how Box objects
are created.
 Example: 
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class DemoBox
{
public static void main(String args[])
{
Box b1 = new Box(10, 20, 15);
Box b2 = new Box(3, 6, 9);
double vol;
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}

 THE this KEYWORD

 this can be used inside any method to refer to the current object.
 That is, this is always a reference to the object on which the method was invoked.
 You can use this anywhere a reference to an object of the current class’ type is permitted.
 To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d)
{
[Link] = w;
[Link] = h;
[Link] = d;
}
 This version of Box( ) operates exactly like the earlier version.
7

[Link] Institute of Technology-560056


 The use of this is redundant,but perfectly correct.
 Inside Box( ), this will always refer to the invoking object.
 Example:
class A

int a,b,c;

void input(int a,int b)

this.a=a;

this.b=b;

int mul()

return a*b;

class This1

public static void main(String[] args)

A a=new A();

[Link](2,3);

int x;

x=[Link]();

[Link]("X Value:"+x);

 GARBAGE COLLECTION: 

 Garbage collection is one of the most important features of Java.


8

[Link] Institute of Technology-560056


 The purpose of garbage collection is to identify and delete objects(or allocated memory of
objects) that are not needed by a program so that their resources can be reused.
 Garbage collection is also called automatic memory management.
 Garbage collection is an automatic process.
 Example:-2

 Run the garbage collector using System class

public class Main

public static void main(String[] args)

[Link]();

 THE finalize() METHOD:

 Finalize method will use when object will need to perform some action when it is destroyed.

 For example, if an object has some non-java resource such as a file handle or window character
font, then you have free those resources for future use.

 To handle such situations, java provides a mechanism called finalization.

 Right before an asset is freed, the java run time calls the finalize() method on the object.

 The finalize() method has this general form:

protected void finalize()

// finalization code here

 Here, the keyword protected is a specifier that prevents access to finalize() by code defined
outside its class. 

[Link] Institute of Technology-560056


 It is important to understand that finalize() is only called just prior to garbage collection. 

 It is not called when an object goes out-of-scope, for example. This means program should
provide other means of releasing system resources, etc., used by the object. It must not rely on
finalize() for normal program operation.

 Wrapper Class

 Java is an object-oriented language and can view everything as an object. A simple file can be
treated as an object (with [Link]), an address of a system can be seen as an object (with
[Link]), an image can be treated as an object (with [Link]) and a simple data type
can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes.
Wrapper classes are used to convert any data type into an object
 As the name says, a wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type. It can be compared with a
chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution.
The user takes the chocolate, removes and throws the wrapper and eats it.

 The name of the wrapper class corresponding to each primitive data type, along with the arguments
its constructor accepts, is listed below: 

Primitive datatype Wrapper Class


boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

 Example
public class WrappingUnwrapping
{
public static void main(String args[])
{
int marks = 50;
Integer m1 = new Integer(marks);
[Link]("Integer object m1: " + m1);
int iv = [Link]();
[Link]("int value, iv: " + iv);
}
}

OUTPUT:
10

[Link] Institute of Technology-560056


Integer object m1: 50
int value, iv: 50

11

[Link] Institute of Technology-560056


3. More about Methods and Classes

 Overloading Methods

 Class have multiple methods(functions) by same name but different parameters,it is known as
method overloading.
 Method overloading is one of the ways that Java supports polymorphism. 
 But as you will see, method overloading is one of Java’s most exciting and useful features.
 When an overloaded method is called, Java uses the type and/or number of arguments as its guide
to determine which version of the overloaded method to actually call. 
 Thus, overloaded methods must differ in the type and/or number of their parameters.
 While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
 Here is a simple example that illustrates method overloading:
 EXAMPLE: Sum of two numbers using method overloading.
//Demonstrate method overloading.
class sumoftwo
{
void sum(int a,int b)
{
[Link](a+b);
}
void sum(int a,int b,int c)
{
[Link](a+b+c);
}
}
class sum
{
public static void main(String args[])
{
sumoftwo ob=new sumoftwo();
[Link](10,20,30);
[Link](20,50);
}
}

 EXAMPLE:
// Demonstrate method overloading.
class one
{
void test()
{
[Link]("No parameters");
}
void test(int a)
{
[Link]("a: " + a);

[Link] Institute of Technology-560056


}
void test(int a, int b)
{
[Link]("a and b: " + a + " " + b);
}
}
class two
{
public static void main(String args[])
{
one ob = new one();
[Link]();
[Link](10);
[Link](10, 20);
}
}

OUTPUT:
No parameters
a: 10
a and b: 10 20

 Overloading Constructors

 Constructor is special type of method which called at the time of object creation.
 In addition to overloading normal methods, you can also overload constructor.
 There is two types of constructor:
(1) Default constructor (Constructor have no-parameter)
(2) Parameterized constructor (Constructor have parameter)
 EXAMPLE:
//Demonstrate constructor(default constructor) overloading.
class display
{
display()
{
[Link](“Hello world”);
}
}
class read_display
{
public static void main(String args[])
{
display ob=new display();
}
}

 /* Here, Box defines three constructors to initialize the dimensions of a box various ways.*/
//Demonstrate constructor overloading.
class Box

[Link] Institute of Technology-560056


{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
double volume()
{
return width * height * depth;
}
}
class Demobox
{
public static void main(String args[])
{
Box b1 = new Box(10, 20, 15);
Box b2 = new Box();
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
}
}

OUTPUT:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

 Using Objects as Parameters


 Using simple types as parameters to methods.
 However, it is both correct and common to pass objects to methods.
 For example, consider the following short program:
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;

[Link] Institute of Technology-560056


}
boolean equals(Test o)
{
if(o.a == a && o.b == b)
{
return true;
}
else
{
return false;
}
}
}
class Demopass
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
[Link]("ob1 == ob2: " + [Link](ob2));
[Link]("ob1 == ob3: " + [Link](ob3));
}
}

OUTPUT:
ob1 == ob2: true
ob1 == ob3: false

 As you can see, the equals( ) method inside Test compares two objects for equality and returns the
result.
 That is, it compares the invoking object with the one that it is passed.
 If they contain the same values, then the method returns true .
 Otherwise, it returns false.
 Notice that the parameter object in equals( ) specifies Test as its type. Although Test is a class type
created by the program, it is used in just the same way as Java’s built-in types.

 Call-By-Value
 If we call a method passing a value, it is known as call by value. The changes being done in the
called method, is not affected in the calling method.
 This approach copies the value of an argument into the formal parameter of the subroutine.
 Therefore, changes made to the parameter of the subroutine have no effect on the argument.
 Inside the subroutine, this reference is used to access the actual argument specified in the call.
 This means that changes made to the parameter will affect the argument used to call the
subroutine. 
 In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.
 EXAMPLE:
// Primitive types are passed by value.

[Link] Institute of Technology-560056


class Test
{
void abc(int i, int j)
{
i = 2;
j = 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: " + a + " " + b);
[Link](a, b);
[Link]("a and b after call: " + a + " " + b);
}
}

OUTPUT:
a and b before call: 15 20
a and b after call: 15 20

 Call-By-Reference
 This concept is not correct for java.
 In this approach, a reference to an argument (not the value of the argument) is passed to the
parameter.
 Thus, when you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
 This effectively means that objects are passed to methods by use of call-by-reference. 
 Changes to the object inside the method do affect the object used as an argument.
 EXAMPLE
// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void abc(Test o)
{
o.a = 2;
o.b = 4;
}

[Link] Institute of Technology-560056


}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
[Link]("Value Of ob.a Before Call " + ob.a );
[Link]("Value Of ob.b Before Call " + ob.b );
[Link](ob);
[Link]("Value Of ob.a After Call " + ob.a );
[Link]("Value Of ob.b After Call " + ob.b );
}
}
OUTPUT:
Value Of ob.a Before Call 15
Value Of ob.a Before Call 20
Value Of ob.a After Call 2
Value Of ob.b After Call 4

 Returning an object
 A method can return any type of data, including class types that you create.
 For example, in the following program, the abc( ) method returns an object in which the value of a
is ten greater than it is in the invoking object.
EXAMPLE:
class Test
{
int a;
Test(int i)
{
a = i;
}
Test abc()
{
Test temp = new Test(a+10);
return temp;
}
}
class two
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: "+ ob2.a);
}

[Link] Institute of Technology-560056


}
OUTPUT:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

 Recursion

 Recursion is a basic programming technique you can use in Java, in which a method calls itself
 A method that calls itself is said to be recursive. 
 The classic example of recursion is the computation of the factorial of a number.
 The factorial of a number N is the product of all the whole numbers between 1 and [Link]
 example, 3 factorial is 1 × 2 × 3 , or 6.
 Here is how a factorial can be computed by use of a recursive method:
 EXAMPLE:-
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==0 || n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
}
}

OUTPUT:
Factorial of 3 is 6

 Static and Final Keyword


 The static keyword is used in java mainly for memory management.
 We may apply static keyword with variables, methods and blocks.
 The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an object of a class.
 static method can access static data member and can change the value of it.

[Link] Institute of Technology-560056


 To create such a member, precede its declaration with the keyword static.
 When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
 The most common example of a static member is main( ).
 main( )is declared as static because it must be called before any objects exist.
 Methods declared as static have several restrictions:
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way. (The keyword super relates to inheritance and is
described in the next chapter.)
 EXAMPLE:-Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int a = 3;
static void meth(int x)
{
[Link]("x = " + x);
[Link]("a = " + a);
}
static
{
[Link](“Static block initialized.”);
}
public static void main(String args[])
{
meth(42);
}
}
OUTPUT:
Static block initialized.
x = 42
a=3
 Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class followed by
the dot operator.
 For example, if you wish to call a static method from outside its class, you can do so using the
following general form.
[Link]( )
 Here,classname is the name of the class in which the static method is declared.
 As you can see, this format is similar to that used to call non- static methods through object-
reference variables.
 A static variable can be accessed in the same way—by use of the dot operator on the name of the
class.
class Demo
{
static int a = 42;
static int b = 99;

[Link] Institute of Technology-560056


static void callme()
{
[Link]("a = " + a);
}
}
class test
{
public static void main(String args[])
{
[Link]();
[Link]("b = " + Demo.b);
}
}
OUTPUT:
a = 42
b = 99

 final KEYWORD:
 A variable can be declared as final.
 The Java final keyword is used to indicate that something "cannot change".
 Use of Final keyword:
It is used to indicate that a class cannot be extended.
It is used to indicate that a method cannot be overridden.
It is used to indicate that a local variable cannot be changed once its value is set.
It is used to indicate that a static variable cannot be changed once set, in effect
implementing "constants".
 For example:
final int I= 1;
 Subsequent parts of your program can now use i, etc., as if they were constants, without fear that a
value has been changed.
 EXAMPLE:
public class Demo
{
final int I=10;
void abc()
{
[Link]("Final variable value : "+i);
}
public static void main(String[] args)
{
Demo f=new Demo();
[Link]();
}
}
OUTPUT:-
Final variable value :10

[Link] Institute of Technology-560056


 Nested Classes
 Class within another class such classes is known as nested classes.
 A nested class has access to the members, including private members, of the class in which it is
nested.
 However, the enclosing class does not have access to the members of the nested class.
 There are two types of nested classes: static and non-static.
 A static nested class is one which has the static modifier applied. Because it is static, it must
access the members of its enclosing class through an object. That is, it cannot refer to members
of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
 The most important type of nested class is the inner class.
 An inner class is a non-static nested class.
 It has access to all of the variables and methods of its outer class and may refer to them directly
in the same way that other non-static members of the outer class

 Inner Classes
 As with instance methods and variables, an inner class is associated with an instance of its
enclosing class and has direct access to that object's methods and fields.
 Also, because an inner class is associated with an instance, it cannot define any static members
itself. 
 Objects that are instances of an inner class exist within an instance of the outer class.
 Consider the following classes:
class OuterClass
{
...
class InnerClass
{
...
}
}
 An instance of InnerClass can exist only within an instance of OuterClass and has direct access
to the methods and fields of its enclosing instance. 
 The next figure illustrates this idea.

 An Instance of Inner Class Exists Within an Instance of OuterClass. 

 Example:
class Outer
{
int outer_x = 100;

[Link] Institute of Technology-560056


void test()
{
Inner inner = new Inner();
[Link]();
}
// this is an inner class
class Inner
{
void display()
{
[Link]("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
[Link]();
}
}
OUTPUT:
display: outer_x = 100

 Command Line Arguments

 The user enters command-line arguments at the time of application run and specifies them after the
name of the class to be run.
 For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file
named [Link], a user would enter:
java Sort [Link]
 When an application is launched, the runtime system passes the command-line arguments to the
application's main method via an array of Strings. 
 In the previous example, the command-line arguments passed to the Sort application in an array
that contains a single String: "[Link]".
 EXAMPLE:
public class Test2
{
public static void main(String[] args)
{
int num=[Link];
String s[]=new String[num];
if(num>0)
{
[Link]("The values enter at argument command line are:");
for(int i=0;i<num;i++)
{
[Link]("Argument"+(i+1)+"="+args[i]);

[Link] Institute of Technology-560056


}
}
else
{
[Link]("No values has been entered at the command line.");
}
}
}

OUTPUT:

C:\JavaPro>java Test2 programming with java


The values enter at argument command line are:
Argument 1 = programming
Argument 2 = with
Argument 3 = java

[Link] Institute of Technology-560056


4. Inheritance
 Inheritance 
 Inheritance is a mechanism to derive a new class from old class.
 New class is a sub class or child class.
 Old class is a base class or super class, parent class.
 Define a sub class
class sub name extends super class
{
Variable declaration;
Function(Method) declaration
}
 The keyword extends signifies that the properties of super class name are extends to the sub class
name.
 Advantages:
Reusability
Extensibility
Data hiding
Overriding
 Disadvantages:
Both classes are tightly coupled.
They cannot work independently of each other.
Changing code in super class method also affects subclass functionality.

 Types of Inheritance:
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance

 Single Inheritance 

 Sub class can be deriving from super class this mechanism is known as single inheritance.

Class A Super class

Class B Sub class

 Syntax:
Class A
{
----
----
}

[Link] Institute of Technology-560056


Class B extends A
{
----
----
}

 Example: Program for single inheritance.


class A
{
void add()
{
int a, b, c;
a=2;
b=4;
[Link]("Value C :"+ (a+b));
}
}
class B extends A
{
void mul()
{
int a, b, c;
a=2;
b=4;
[Link]("Value C :"+ a*b);
}
}
class singleinheritance
{
public static void main(String[] args)
{
B ob=new B();
[Link]();
[Link]();
}
}

 Multilevel Inheritance 
 C class is derived from B class & B class is derived from A class this type of mechanism is called
multilevel inheritance.
 Sub class can be derived from another super class.

Class A Super class

Class B Intermediate
class

Class C Sub class

[Link] Institute of Technology-560056


 Syntax:
class A
{
----
----
}
class B extends A
{
----
----
}
class C extends B
{
----
----
}
class multilevel
{
----
----
}
 Example: Program for multilevel inheritance.
class A
{
void add()
{
int a, b, c;
a=2;
b=4;
[Link]("Value C :"+ a+b);
}
}
class B extends A
{
void mul()
{
int a, b, c;
a=2;
b=4;
[Link]("Value C :"+ a*b);
}
}
class C extends B
{
void div()
{
int a, b, c;
a=4;
b=2;
[Link]("Value C :"+ a/b);
}
}

[Link] Institute of Technology-560056


class Multilevel
{
public static void main(String[] args)
{
C ob=new C();
[Link]();
[Link]();
[Link]();
}
}

 Hierarchical Inheritance 
 One super class and more than one sub class it’s called hierarchical inheritance.

Class A Super class

Class B Class C

Sub class
 Syntax:
class A
{
----
----
}
class B extends A
{
----
----
}
class C extends A
{
----
----
}
class hierarchical
{
----
----
}
 Example:-Program for hierarchical inheritance.
class A
{
void add()
{
int a, b, c;
a=2;

[Link] Institute of Technology-560056


b=4;
[Link]("Value C :"+ a+b);
}
}
class B extends A
{
void mul()
{
int a, b, c;
a=2;
b=4;
[Link]("Value C :"+ a*b);
}
}
class C extends A
{
void div()
{
int a, b, c;
a=4;
b=2;
[Link]("Value C :"+ a/b);
}
}
class hierarchical
{
public static void main(String[] args)
{
B ob1=new B();
[Link]();
[Link]();
C ob2=new C();
[Link]();
}
}

 Super keyword:

 The super is a keyword defined in the java programming language.


 Super is a reference variable that is used to refer parent/super/base class objects.
 Super is a used to access variables, constructors and methods of a parent/super/base class.
 Example to use the super keyword to call the constructor of the superclass:
public class car
{
int speed=200;
}
class bike extends car
{
int speed=100;
void dispaly()
{
[Link]([Link]);//super to access speed method of car class

[Link] Institute of Technology-560056


[Link](speed);
}
}
class vehicle
{
public static void main(String args[])
{
bike ob=new bike();
[Link]();
}
}
 The syntax super.method_name() is used to call a method of the super class from the sub class.
 class car
{
car()
{
[Link]("Printed in car class.");
}
}
class bike extends car
{
bike()
{
super(); // here super keyword is to access constructor of car(super) class
[Link]("Printed in bike class");
}
}
class vehicle
{
public static void main(String[] args)
{
bike ob = new bike();
}
}
 The syntax super() is used to call a constructor of the super class from the sub class.

 When Constructors Are Called in Multilevel hierarchy


 The answer is that in a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.
 Further, since super( ) must be the first statement executed in a subclass’ constructor, this order is
the same whether or not super( ) is used.
 If super( ) is not used, then the default or parameter less constructor of each superclass will be
executed. The following program illustrates when constructors are executed:
 Demonstrate when constructors are called.
class A
{
A()
{
[Link]("Inside A's constructor.");
}
}

[Link] Institute of Technology-560056


// Create another subclass by extending A.
class B extends A
{
B()
{
[Link]("Inside B's constructor.");
}
}
class C extends B
{
C()
{
[Link]("Inside C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
C c = new C();
}
}

 Method overriding
 When method in sub class has same name as a method in super class then method in sub class is
said to override the method in super class.
 Advantage of Method Overriding
Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method Overriding is used for Runtime Polymorphism
 Rules for Method Overriding:
method must have same name as in the parent class
Method must have same parameter as in the parent class.

 Example 1: Program for overriding

class Superclass
{
void print()
{
[Link]("Printed in Superclass.");
}
}
class Subclass extends Superclass
{ Overriding
void print() method
{
[Link]();
[Link]("Printed in Subclass");

[Link] Institute of Technology-560056


}
public static void main(String[] args)
{
Subclass s = new Subclass();
[Link]();
}
}

 Example 2: Program for overriding


class A
{
int i,j;
A(int a,int b)
{
i=a;
j=b;
}
void show()
{
[Link]("i and j:"+i+” “+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
[Link]();
[Link]("k:"+k);
}
}
class overriding
{
public static void main(String[] args)
{
B ob=new B(10,20,30);
[Link] ( );
}
}

 What is difference between overloading and overriding?

Method overloading Method overriding


When two or more methods in a class have When a method in a subclass has the same
the same method names with different method name with same arguments as that of
arguments, it is said to be method the super class, it is said to be method
overloading. overriding.

[Link] Institute of Technology-560056


Overloading does not block inheritance from Overriding blocks inheritance from the super
the super class. class.
In case of method overloading, parameter In case of method overriding parameter must
must be different. be same.

 Basically overloading and overriding are different aspects of polymorphism.


Static/early binding polymorphism: overloading
dynamic/late binding polymorphism: overriding

 Java Abstract Class


 An abstract class is a class that is declared by using the abstract keyword.
 We have seen that by making a method final we ensure that the method is not redefined in a
subclass.
 That is, the method can never be subclass.
 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 insatiate 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.
 Example:
abstract class One
{
int i;
int j;
One(int a, int b)
{
i = a;
j = b;
}
abstract int area();
}
class Two extends One
{
Two(int a, int b)
{

[Link] Institute of Technology-560056


super(a, b);
}
int area()
{
[Link]("Inside Area for.");
return i * j;
}
}
class AbstractDemo
{
public static void main(String args[])
{
// One f = new One(10, 10); // illegal now
Two t = new Two(9, 5);
One o; // this is OK, no object is created
o = t;
[Link]("Area is " + [Link]());
}
}

 Using final with Inheritance 


 The keyword final has three uses.
it can be used to create the equivalent of a named constant.
Two uses of final apply to inheritance. Both are examined here.
 Using final to Prevent Overriding
Using final to Prevent Overriding While method overriding is one of Java’s most powerful
features
There will be times when you will want to prevent it from occurring. To disallow a method
from being overridden, specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void show()
{
[Link]("This is a final method.");
}
}
class B extends A
{ ERROR! Can't
void show() override.
{
[Link]("Illegal!");
}
}
Because show( ) is declared as final, it cannot be overridden in B.
If you attempt to do so, a compile-time error will result.
Methods declared as final can sometimes provide a performance enhancement.
 Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited.

[Link] Institute of Technology-560056


To do this, precede the class declaration with final.
Declaring a class as final implicitly declares all of its methods as final, too.
As you might expect, it is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}
 As the comments imply, it is illegal for B to inherit A since A is declared as final.

[Link] Institute of Technology-560056


5. PACKAGES AND INTERFACES

 Packages:
 A package is a group of classes and interfaces.
 Package can be categorized in two form:
built-in package such as java, lang, awt, javax, swing, net, io, util, sql etc.
user-defined package which is created by user.
 Advantages of Packages:
Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provides access protection.
Package removes naming collision.

 Naming rules for packages:


Package names are written in all lowercase to avoid conflict with the names of classes or
interfaces.
The directory name must be same as the name of package that is created using "package"
keyword in the source file.
Before running a program, the class path must be picked up till the main directory (or
package) that is used in the program.
If we are not including any package in our java source file then the source file automatically
goes to the default package.
In general, we start a package name begins with the order from top to bottom level.
In case of the internet domain, the name of the domain is treated in reverse (prefix) order.

 How to create a Package?


 To create a package, you choose a name for the package and put a package statement with that
name at the top of every source file that contains the types ( classes, and interfaces) that you
want to include in the package.
 The package statement (example-package graphics;) must be the first line in the source file.
 There can be only one package statement in each source file, and it applies to all types in the
file.
 Steps to crate packages:
Declare the package at the beginning of a file using the from
package packagename;
Define the class that is to be put in the package and declare it public.
Create a subdirectory under the directory where the main source files are stored.
Store the listing as the [Link] file in the subdirectory created.
Compile the file. This creates Class file in the subdirectory.
 You can create a hierarchy of packages.
 To do so, simply separate each package name from the one above it by use of a period.
 The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
 A package hierarchy must be reflected in the file system of your Java development system.
 For example, a package declared as

[Link] Institute of Technology-560056


package [Link];
 Needs to be stored in java\awt\image in a Windows environment.
You cannot rename a package without renaming the directory in which the classes are stored
 Example :
Save program in your directory(e.g.-D:\Java_prog\Package\[Link])
Compile using D:\>Java_prog\Package\javac –d . [Link]
Then pack directory has been generate with [Link] file.
Then run program D:\>Java_prog\Package\java pack.A
package pack;
public class A
{
public static void main(String args[])
{
[Link]("B. S. Patel Polytechnic");
}
}

 Finding Packages and CLASSPATH


 As just explained, packages are mirrored by directories.
 This raises an important question:
 How does the Java run-time system know where to look for packages that you create?
 The answer has three parts.
First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in a subdirectory of the current directory, it will be found.
Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable.
Third, you can use the -classpath option with java and javac to specify the path to your
classes.
 For example, consider the following package specification:
package pk1
 In order for a program to find pk1, one of three things must be true. Either the program can be
executed from a directory immediately above pk1, or the CLASSPATH must be set to include
the path to pk1, or the -classpath option must specify the path to pk1 when the program is run via
java.
 When the second two options are used, the class path must not include pk1, [Link] must simply
specify the path to pk1.
 For example, in a Windows environment, if the path to PK1 is
C:\MyPrograms\Java\ pk1
 Then the class path to pk1 is
C:\MyPrograms\Java

 Access Specifiers(Visibility Modifiers) OR Access protection in packages:

Access Description
protection
No modifier The classes and members specified in the same package are accessible to
(default) all the classes inside the same package.
public The classes, methods and member variables under this specifier can be accessed
from anywhere.

[Link] Institute of Technology-560056


protected The classes, methods and member variables under this modifier are accessible by
all subclasses,
and accessible by code in same package.
private The methods and member variables are accessible only inside the class.

 Access to fields in Java at a look:

Access By public protected default private


The class itself Yes Yes Yes Yes
A subclass in same Yes Yes Yes No
package
Non sub-class in the Yes Yes Yes No
same package
A subclass in other Yes Yes No No
package
Non subclass in other Yes No No No
package

 Importing package

In a Java source file, import statements occur immediately following the package statement (if it
exists) and before any class definitions.
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 a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed by the file
system.
Finally, you specify either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
This code fragment shows both forms in use:
import [Link];
import [Link].*;
 Example:
package pack;
public class A
{
int a;
int b;
A(int i,int j)
{
a=i;
b=j;
}
public void display()
{
[Link](a + "&" + b);
}
}

[Link] Institute of Technology-560056


compile your program like :- D:\>Java_prog\Package\javac –d . [Link]
This source file should be named [Link] and stored in the sub directory pack.
Now compile this java file.
The resultant [Link] will be stored in the same sub directory.
import pack.A;
class B
{
public static void main(String args[])
{
A ob= new A(5,9);
[Link]();
}
}
 The source file should be saved as [Link] and then compiled.
 The source file and the compiled file would be saved in the directory of which pack was a
subdirectory.
D:\>Java_prog\Package\javac B. java
D:\>Java_prog\Package\java B
Output:- 5&9

 Interfaces
 Interface is just like a class.
 Interface declares with interface keyword.
 Interface does not have any implementation of method.
 In Java Interface defines the methods but does not implement them.
 Interface is collection of methods and variables.
 In interface variable consider as a constant and method consider as abstract.
 More than one class can be implement interface.
 Interface extends two or more interfaces.
 It means using interface we can create multiple inheritance.
 Syntax:
[access] interface InterfaceName [extends OtherInterface]
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
 Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements keyword in a class definition, and then
create the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body

[Link] Institute of Technology-560056


}
If a class implements more than one interface, the interfaces are separated with a comma.
If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.
The methods that implement an interface must be declared public.
 Example:-1
interface I1
{
public int a=10;
public int b=20;
public void sum();
}
class one implements I1
{
public void sum()
{
[Link]("Sum-->"+(a+b));
}
}
class two
{
public static void main(String[] args)
{
one ob1=new one();
[Link]();
}
}
 Example:-2
interface I1
{
public void show();
}
interface I2
{
public void show1();
}
class A implements I1,I2
{
public void show() {
[Link]("i am the implentation of interface first"); }
public void show1() {
[Link]("I am the implentation of interface second"); }
}
class interface1
{
public static void main(String[] args) {
A a=new A();
[Link]();
a.show1();
}
}

[Link] Institute of Technology-560056


6. EXCEPTION HANDLING
 Exception – Handling fundamentals

 An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run out of
memory.
 Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
 To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
Checked exceptions:
 A checked exception is an exception that is typically a user error or a problem that cannot be
foreseen by the programmer.
 For example, if a file is to be opened, but the file cannot be found, an exception occurs.
 These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions:
 A runtime exception is an exception that occurs that probably could have been avoided by the
programmer.
 As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors:
 These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer.
 Errors are typically ignored in your code because you can rarely do anything about an error.
 For example, if a stack overflow occurs, an error will arise. They are also ignored at the time
of compilation.

 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that you want to check for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and handle it in some normal manner.
System-generated exceptions are automatically thrown by the Java run-time [Link] manually
throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.
 Syntax:
try
{
// block of code to check for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}

[Link] Institute of Technology-560056


catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}

 Exception types(Explain various exception techniques in java?...)

EXCEPTION TYPE CAUSE OF EXCEPTION


Arithmetic Exception Caused by math errors such as division by
Array Index Out of Bounds Exception Caused by bad array indexes
Array Store Exception Caused when a program tries to store the wrong
type of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file
IoException Caused by general I/O failures, such as inability to
read from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings and
number fails
OutofMemoryException Caused when there’s not enough memory to
allocate a new object
SecurityException Caused when an applet tries to perform an action
not allowed by the browser’s security setting
StackOverFlowException Caused when he system runs out of stack space
StringIndexOut of Bounds Exception Caused when a program attempts to access a
nonexistent character position in a string
ClassCastException Thrown when attempting to cast a reference
variable to a type that fails the IS-A test

Example:
1) int a=50/0; //ArithmeticException
2) String s="abc";
int i=[Link](s); //NumberFormatException
3) String s=null;
[Link]([Link]());//NullPointerException
4) int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

 Using try and catch

 The try/catch statement encloses some code and is used to handle errors and exceptions that might
occur in that code.

[Link] Institute of Technology-560056


 With the help of try and catch we solve the run time error easy.
 The general syntax of the try/catch statement is as below:
try
{
body-code
}
catch (exception-classname variable-name)
{
handler-code
}

 The try/catch statement has four parts.


The body-code contains code that might throw the exception that we want to handle.
The exception-classname is the class name of the exception we want to handle.
The variable-name specifies a name for a variable that will hold the exception object if the
exception occurs.
Finally, the handler-code contains the code to execute if the exception occurs. After the
handler-code executes, execution of the thread continues after the try/catch statement.

 Advantage of using try & catch:


It allows the programmer to fix the error.
It prevents the programmer from automatically terminating.

 Example:-
class Trycatch
{
public static void main(String[] args)
{
try
{
int a,b,c;
a=12;
b=0;
c=a/b;
[Link](c);
}
catch(Exception e)
{
[Link](e);
}
}
}

 Uncaught exceptions

 This small program includes an expression that intentionally causes a divide-by-zero error:
class Test
{
public static void main(String args[])

[Link] Institute of Technology-560056


{
int d = 0;
int a = 42 / d;
}
}
 In above program error detects at the time of divide by zero so here it generates exception.
 This causes the execution of Test to stop.
 Any exception that is not caught by your program will ultimately be processed by the default handler
provided by the Java run-time system. 
 Here is the exception generated by default handler when this example is executed:
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
 Notice how the class name, Test; the method name, main; the filename, [Link]; and the line
number, 6, are all included in the simple stack trace.
 Also, notice that the type of exception thrown is a subclass of Exception called
ArithmeticException, which more specifically describes what type of error happened.

 Multiple catch clauses


 In some case, more than one exception could be raised by a single piece of code.
 In such situations two on more catch block can be specified each catching a different type of
exception. 
 The first catch block whose type matches is executed.
 After one catch statement executed, the others are bypassed & executed continues after try-catch
block. At that time we use multiple catch
 Example:-
class Multicatch
{
public static void main(String[] args)
{
try
{
int a,b,c;
int d[]=new int[3];
a=12;
b=12;
c=a/b;
[Link](c);
d[4]=46;
[Link](d[4]);
}
catch (ArithmeticException e)
{
[Link](e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
}
}

[Link] Institute of Technology-560056


 When you use multiple catch statements, it is important to remember that exception subclasses must
come before any of their superclasses. 
 This is because a catch statement that uses a superclass will catch exceptions of that type plus any of
its subclasses.
 Thus, a subclass would never be reached if it came after its superclass

 Nested try statements

 In Java we can have nested try and catch blocks.


 It means that, a try block inside the another try block .
 If an inner try statement does not have a matching catch statement for a particular exception, the
control is transferred to the next try statements catch handlers that are expected for a matching
catch statement.
 This continues until one of the catch statements succeeds, or until all of the nested try statements
are done in.
 If no one catch statements match, then the Java run-time system will handle the exception.

 Syntax:-
try
{
try
{
// ...
}
catch (Exception1 e)
{
//statements to handle the exception
}
}
catch (Exception2 e2)
{
//statements to handle the exception
}
 Example:-
class NestedTry
{
public static void main (String args [ ] )
{
try
{
int a = [Link](args [0]);
int b = [Link](args [1]);
int c = 0;

try
{
c = a / b;
[Link](c);
}
catch (ArithmeticException e)

[Link] Institute of Technology-560056


{
[Link]("divide by zero");
}
}
catch (NumberFormatException e)
{
[Link] ("Incorrect argument type");
}
}
}

 Throw, throws, finally

 Throw
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to
throw custom exception
 Syntax:-
throw someThrowableObject;
All the classes are children of the Throwable class, and all allow programs to differentiate
among the various types of exceptions that can occur during the execution of a program.
Used in program:
try
{
// statements
throw new UserDefinedException( );
// statements
}
catch (UserDefinedException e)
{
[Link] (“User defined exception caught”);
}

The UserDefinedException is a class made specifically to handle an exception and it is


encapsulating some specific kind of user defined behaviour.
This exception is raised explicitly using the throw clause.
At the same time the catch clause is there ready to catch the same exception object.

Example:-
class Throwclause
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[])
{

[Link] Institute of Technology-560056


validate(13);
[Link]("rest of the code...");
}
}

Output:Exception in thread main [Link]:not valid

 Throws

The throws keyword is used to declare an exception.


It gives an information to the programmer that there may occur an exception so it is better for
the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.
Syntax:-
void method_name() throws exception_class_name
{
...
}

Example:-
class Throwsclause
{
static void abc( ) throws IllegalAccessException
{
try
{
throw new IllegalAccessException( ); // exception thrown
}
catch (IllegalAccessException e)// exception caught
{
[Link] ("catch block");
throw new IllegalAccessException( );
// exception thrown again
}
}
public static void main (String args [ ])
{
try
{
abc( );
}
catch (IllegalAccessException e)
{
[Link] ("Exception caught");
}
}
}

[Link] Institute of Technology-560056


 Diference between throw and throws
throw throws
1)throw is used to explicitly throw an 1) throws is used to declare an exception.
exception.
2)checked exception can not be propagated 2)checked exception can be propagated with
without throw. throws.
3)throw is followed by an instance. 3) throws is followed by class.
4)throw is used within the method. 4) throws is used with the method signature.
5)You cannot throw multiple exception 5) You can declare multiple exception e.g.
public void method() throws IOException,
SQLException.

 Finally
Java support another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements.
Finally block can be used to handle any exception generated within a try block.
It may be added immediately after the try block or after the last catch block shown as follow.
When a finally block is defined, this is guaranteed to execute.
As a result, we can use it to perform certain house-keeping operations such as closing file and
releasing system resource.
Syntax:
try
{
// statements
}
catch (<exception> obj)
{
// statements
}
finally
{
//statements
}
Example:-
class Finally
{
public static void main(String[] args)
{
try
{
int a,b,c;
a=2;
b=0;
c=a/b;
[Link](c);
}
catch (Exception e)

[Link] Institute of Technology-560056


{
[Link](e);
}
finally
{
[Link]("In the finally block");
}
}
}

 Creating your own exception sub classes

 You can create your own exception class by defining a subclass of Exception.
 The Exception class does not define any methods of its own. It inherits methods provided by
Throwable.
 All exceptions have the methods defined by Throwable available to them.
 They are shown in the following list.
Throwable fillInStackTrace( )
 Returns a Throwable object that contains a completed stack trace.
Throwable getCause( )
 Returns the exception that underlies the current exception.
String getLocalizedMessage( )
 Returns a localized description.
String getMessage( )
 Returns a description of the exception.
StackTraceElement[ ] getStackTrace( )
 Returns an array that contains the stack trace.
Throwable initCause(Throwable causeExc)
 Associates causeExc with the invoking exception as a cause of the invoking exception.
void printStackTrace( )
 Displays the stack trace.
void printStackTrace(PrintStream stream)
 Sends the stack trace to the stream.
void printStackTrace(PrintWriter stream)
 Sends the stack trace to the stream.
void setStackTrace(StackTraceElement elements[ ])
 Sets the stack trace to the elements passed in elements.
String toString( )
 Returns a String object containing a description of the exception.

 Example:-
class MyException extends Exception
{
private int b;
MyException(int a)
{
b = a;
}
public String toString()

[Link] Institute of Technology-560056


{
return "MyException[" + b + "]";
}
}
public class Main
{
static void display(int a) throws MyException
{
[Link](a);
if (a > 10)
throw new MyException(a);
[Link]("Normal exit");
}
public static void main(String args[])
{
try
{
display(2);
display(20);
}
catch (MyException e)
{
[Link]("Caught " + e);
}
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

7. MULTITHREDED PROGRAMMING

 What is thread?
 A thread is a single sequential flow of control within a program.
 Thread is a path of the execution in a program. 
 Muti-Threading:
Executing more than one thread (part of a task) parallel using a single processor is called
multithreading
Thread: A thread can be loosely defined as a separate stream of execution that takes place
simultaneously with and independently of everything else that might be happening.
A thread is like a classic program that starts at point A and executes until it reaches point B.
It does not have an event loop. A thread runs independently of anything else happening in the
computer.
Without threads an entire program can be held up by one CPU intensive task or one infinite
loop, intentional or otherwise.
With threads the other tasks that don't get stuck in the loop can continue processing without
waiting for the stuck task to finish.
It turns out that implementing threading is harder than implementing multitasking in an
operating system
The reason it's relatively easy to implement multitasking is that individual programs are
isolated from each other. Individual threads, however, are not.
To return to the printing example, suppose that while the printing is happening in one thread,
the user deletes a large chunk of text in another thread.
What's printed? The document as it was before the deletion? The document as it was after the
deletion? The document with some but not all of the deleted text? Or does the whole system
go down in flames? Most often in a non-threaded or poorly threaded system, it's the latter.
Threaded environments like Java allow a thread to put locks on shared resources so that while
one thread is using data no other thread can touch that data.
This is done with synchronization. Synchronization should be used sparingly since the purpose
of threading is defeated if the entire system gets stopped waiting for a lock to be released.
The proper choice of objects and methods to synchronize is one of the more difficult things to
learn about threaded programming
Creating threads using the thread class

 Life Cycle of Thread


 When you are programming with threads, understanding the life cycle of thread is very valuable. 
 While a thread is alive, it is in one of several states.
 By invoking start() method, it doesn?t mean that the thread has access to CPU and start executing
straight away. Several factors determine how it will proceed
 Different states of a thread are :

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 New state:
After the creations of Thread instance the thread is in this state but before the start() method
invocation.
At this point, the thread is considered not alive.
 Runnable (Ready-to-run) state:
A thread start its life from Runnable state.
A thread first enters runnable state after the invoking of start() method but a thread can return to
this state after either running, waiting, sleeping or coming back from blocked state also.
On this state a thread is waiting for a turn on the processor.
 Running state:
A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in Running
state: the scheduler select a thread from runnable pool.
 Dead state:
A thread can be considered dead when its run() method completes.
If any thread comes on this state that means it cannot ever run again.
 Blocked: 
A thread can enter in this state because of waiting the resources that are hold by another thread.

 Methods that can be applied apply on a Thread:


 Some Important Methods defined in [Link] are shown in the table:
Method Return Description
Type
currentThread( ) Thread Returns an object reference to the thread in which it is invoked.
getName( ) String Retrieve the name of the thread object or instance.
start( ) void Start the thread by calling its run method.
run( ) void This method is the entry point to execute thread, like the main
method for applications.
sleep( ) void Suspends a thread for a specified amount of time (in milliseconds).
isAlive( ) boolean This method is used to determine the thread is running or not.
activeCount( ) int This method returns the number of active threads in a particular

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

thread group and all its subgroups.


interrupt( ) void The method interrupt the threads on which it is invoked.
yield( ) void By invoking this method the current thread pause its execution
temporarily and allow other threads to execute.
join( ) void This method and join(long millisec) Throws
InterruptedException. These two methods are invoked on a thread.
These are not returned until either the thread has completed or it is
timed out respectively.

 Process
 A process is an instance of a computer program that is executed sequentially. 
 It is a collection of instructions which are executed simultaneously at the rum time.
 Thus several processes may be associated with the same program.
 For example, to check the spelling is a single process in the Word Processor program and you can
also use other processes like printing, formatting, drawing, etc. associated with this program

 The Java thread model


 Thread
A thread is a lightweight process which exist within a program and executed to perform a
special task.
Several threads of execution may be associated with a single process.
Thus a process that has only one thread is referred to as a single-threaded process, while a
process with multiple threads is referred to as a multi-threaded process.
In Java Programming language, thread is a sequential path of code execution within a program.
Each thread has its own local variables, program counter and lifetime.
In single threaded runtime environment, operations are executes sequentially i.e. next operation
can execute only when the previous one is complete.
It exists in a common memory space and can share both data and code of a program
Threading concept is very important in Java through which we can increase the speed of any
application.
You can see diagram shown below in which a thread is executed along with its several
operations with in a single process.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 The main thread


 When any standalone application is running, it firstly execute the main() method runs in a one
thread, called the main thread. 
 If no other threads are created by the main thread, then program terminates when the main()
method complete its execution. 
 The main thread creates some other threads called child threads.
 The main() method execution can finish, but the program will keep running until the all threads
have complete its execution.

 Features of Threads:
1. Creating a Thread
2. Context Switch
3. Priorities
4. Synchronization
5. Messaging

 Creating a thread
 In Java, an object of the Thread class can represent a thread.
 Thread can be implemented through any one of two ways:
Extending the [Link] Class
Implementing the [Link] Interface

 Extending the [Link] Class


For creating a thread a class have to extend the Thread Class. For creating a thread by this
procedure you have to follow these steps:
Extend the [Link] Class.
Override the run( ) method in the subclass from the Thread class to define the code
executed by the thread.
Create an instance of this subclass. This subclass may call a Thread class constructor by
subclass constructor.
Invoke the start( ) method on the instance of the class to make the thread eligible for
running.
Example:- Single thread creation extending the "Thread" Class:
class MyThread extends Thread
{
String s=null;
MyThread(String s1)
{
s=s1;

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

start();
}
public void run()
{
[Link](s);
}
}
public class RunThread
{
public static void main(String args[])
{
MyThread m1=new MyThread("Thread started. .. ");
}
}

 Implementing the [Link] Interface


The procedure for creating threads by implementing the Runnable Interface is as follows:
A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
Create an object of Thread Class by passing a Runnable object as argument.
Invoke the start( ) method on the instance of the Thread class.
Example: Thread creation implenting the Runnable interface:
class MyThread1 implements Runnable
{
Thread t;
String s=null;
MyThread1(String s1)
{
s=s1;
t=new Thread(this);
[Link]();
}
public void run()
{
[Link](s);
}
}
public class RunableThread
{
public static void main(String args[])
{
MyThread1 m1=new MyThread1("Thread started ... ");
}
}
There are two reasons for implementing a Runnable interface preferable to extending the Thread
Class.
If you extend the Thread Class, that means that subclass cannot extend any other Class, but
if you implement Runnable interface then you can do this.
The class implementing the Runnable interface can avoid the full overhead of Thread class
which can be excessive.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Creating multiple threads


 Like creation of a single thread, You can also create more than one thread (multithreads) in a
program using class Thread or implementing interface Runnable.
 Example:- implenting the Runnable interface:

class MyThread1 implements Runnable
{
Thread t;
String s=null;
MyThread1(String s1)
{
s=s1;
t=new Thread(this);
[Link]();
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link]("Thread-->" + s + " " + i);
}
}
}
public class MultipleThread
{
public static void main(String args[])
{
new MyThread1("One"); // start threads
new MyThread1("Two");
new MyThread1("Three");
}
}

 Using isAlive( ) & join( )


 isAlive() method is used to check whether thread is running or not. it returns true if it is running
otherwise it returns false. 
 final boolean isAlive( )
 Java thread’s join() method is used to join the next thread at the end of current thread. When the
execution of current thread stops the next thread executes.
 The join() method in Java Thread class has three overloaded method,
void join();
void join(long timeout);
void join(long timeout, int nanoseconds);
 void join()
This join method accepts no arguments and forces the thread to wait till it dies.
 void join(long timeout)
This join method accepts only one argument as timeout. The timeout value is milliseconds. This
method forces the thread to wait for given milliseconds for the completion of the specified
thread.
 void join(long timeout, int nanoseconds) 

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

This join method accepts two arguments. First as timeout in milliseconds and second an integer
value for nanoseconds. The amount of timeout in milliseconds is along with the nanoseconds.
This method also forces the thread to wait for the given time.
 Example:
public class Join1 implements Runnable
{
public void run()
{
Thread t = [Link]();
//Tests if this thread is alive
[Link]([Link]()+" is alive "+[Link]());
}
public static void main(String args[]) throws Exception
{
Thread t = new Thread(new Join1());
[Link]();
//Waits for this thread to die.
[Link]();
//Tests if this thread is alive
[Link]([Link]()+" is alive "+[Link]());
}
}

 Thread priorities
 Every thread created has some priority.
 Threads are executed according to their priority.
 Threads with higher priority are executed before threads with lower priority. A newly created thread
has same priority as the thread that creates it.
 Java thread priorities are integer values ranging from 1 to 10.
 1 is the lowest priority and 10 is the highest priority. 
 The default priority of a thread is 5.
 The thread priorities are assigned to some constant literals as follows,
Thread.MIN_PRIORITY : It is the minimum priority of any thread i.e. 1
Thread.MAX_PRIORITY : It is the maximum priority of any thread i.e. 10
Thread.NORM_PRIORITY : It is the normal and default priority of any thread i.e. 5
 To set the thread priorities we can use setPriority() method. Its syntax is, 
final void setPriority(int level);
 To obtain the current priority of a thread we can use getPriority() method. Its syntax is,
final int getPriority();

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example:
public class priority implements Runnable
{
public void run()
{
for (int i=1;i<=3;i++)
{
[Link](i + " This is thread " +
[Link]().getName());
}
}
public static void main(String[] args)
{
Thread t1 = new Thread(new priority(), "Thread A");
Thread t2 = new Thread(new priority(), "Thread B");
Thread t3 = new Thread(new priority(), "Thread C");
[Link](10);
[Link]();
[Link]();
[Link]();
}
}

 Synchronization
 Synchronization is the capabilility of control the access of multiple threads to any shared resource.
 Synchronization is better in case we want only one thread can access the shared resource at a time.
 Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

 Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Here we will learn Thread Synchronization
Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
Each object has just one lock.
All methods in a class need not to be synchronized. A class can have both synchronized and
non-synchronized methods.
If two threads wants to execute a synchronized method in a class, and both threads are using the
same instance of the class to invoke the method then only one thread can execute the method at a
time.
If a class has both synchronized and non-synchronized methods, multiple threads can still access
the class's non-synchronized methods. If you have methods that don't access the data you're
trying to protect, then you don't need to synchronize them.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Synchronization can cause a hit in some cases (or even deadlock if used incorrectly), so you
should be careful not to overuse it.
If a thread goes to sleep, it holds any locks it [Link] doesn't release them.
A thread can acquire more than one lock. For example, a thread can enter a synchronized
method, thus acquiring a lock, and then immediately invoke a synchronized method on a
different object, thus acquiring that lock as well. As the stack unwinds, locks are released again.
You can synchronize a block of code rather than a method.
Constructors cannot be synchronized
 In non synchronized multithreaded application, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating the object's value. 
 There are two ways to synchronized the execution of code:
Example: Synchronized Methods
class A extends Thread
{
public void run()
{
display();
}
public static synchronized void display()
{
int i;
for( i=0;i<10;i++)
{
try
{
sleep(1000);
[Link]([Link]().getName()+" "+i);
}
catch (Exception e)
{
[Link](e);
}
}
}
}
class Sn1
{
public static void main(String[] args)
{
A a=new A();
Thread t1=new Thread(a);
Thread t2=new Thread(a);
[Link]();
[Link]();
}
}
Example:
class A extends Thread
{
public void run()

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

{
synchronized(this) // synchronized block
{
int i;
for( i=0;i<10;i++)
{
try
{
sleep(1000);
[Link]([Link]().getName()+" "+i);
}
catch (Exception e)
{
}
}
}
}
}
class Sn
{
public static void main(String[] args)
{
A a=new A();
Thread t1=new Thread(a);
Thread t2=new Thread(a);
[Link]();
[Link]();
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Inter thread communication


 Java provides a very efficient way through which multiple-threads can communicate with each-
other.
 This way reduces the CPU?s idle time i.e. A process where, a thread is paused running in its critical
region and another thread is allowed to enter (or lock) in the same critical section to be executed.
This technique is known as Interthread communication which is implemented by some methods.
 These methods are defined in "[Link]" package and can only be called within synchronized code
shown as:
Method Description
wait( ) It indicates the calling thread to give up the monitor and go to sleep until
some other thread enters the same monitor and calls method
notify() or notifyAll().
notify( ) It wakes up the first thread that called wait() on the same object.
notifyAll( ) Wakes up (Unlock) all the threads that called wait( ) on the same object. The
highest priority thread will run first.
 All these methods must be called within a try-catch block.
 Example:
class MyOwnRunnable implements Runnable
{
private Object o;
public MyOwnRunnable( Object o)
{
this.o = o;
}
public void run()
{
synchronized (o)
{
for (int i = 0; i < 10; i++)
{
[Link]([Link]().getName()+" "+i);
}
[Link]();
}
}
}
public class Wait1
{
public static void main(String[] args)
{
try
{
Object o = new Object();
MyOwnRunnable a =new MyOwnRunnable(o);
Thread thread1 = new Thread(a);
Thread thread2 = new Thread(a);
Thread thread3 = new Thread(a);
synchronized (o)
{

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
catch (InterruptedException e)
{
[Link]();
}
}
}

 Suspending, resuming, stopping threads


 While the suspend( ), resume( ), and stop( ) methods defined by Thread class seem to be a perfectly
reasonable and convenient approach to managing the execution of threads, they must not be used for
new Java programs and obsolete in newer versions of Java.
 The following example illustrates how the wait( ) and notify( ) methods that are inherited from
Object can be used to control the execution of a thread.
 This example is similar to the program in the previous section. However, the deprecated method
calls have been removed. Let us consider the operation of this program. 
 The NewThread class contains a boolean instance variable named suspendFlag, which is used to
control the execution of the thread. It is initialized to false by the constructor.
 The run( ) method contains a synchronized statement block that checks suspendFlag. If that variable
is true, the wait( ) method is invoked to suspend the execution of the thread. The mysuspend( )
method sets suspendFlag to true. The myresume( ) method sets suspendFlag to false and invokes
notify( ) to wake up the thread. Finally, the main( ) method has been modified to invoke the
mysuspend( ) and myresume( ) methods.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example:
class MyThread implements Runnable
{
Thread t;
boolean suspended;
boolean stopped;
MyThread(String name)
{
t = new Thread(this, name);
suspended = false;
stopped = false;
[Link]();
}
public void run()
{
try
{
for (int i = 1; i < 10; i++)
{
[Link]("\t$");
[Link](50);
synchronized (this)
{
while (suspended)
wait();
if (stopped)
break;
}
}
}
catch (InterruptedException exc)
{
[Link]([Link]() + " interrupted.");
}
[Link]("\n" + [Link]() + " exiting.");
}

synchronized void stop()


{
stopped = true;
suspended = false;
notify();
}
synchronized void suspend()
{
suspended = true;
}
synchronized void resume()
{
suspended = false;
notify();

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

}
}
public class Main
{
public static void main(String args[]) throws Exception
{
MyThread mt = new MyThread("MyThread");
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
[Link](100);
[Link]();
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

8. STRING HANDLING

 The string constructors 


The String class supports several constructors.
To create an empty String, you call the default constructor.
For example,
 String s = new String();
will create an instance of String with no characters in it
You can construct a String object that contains the same character sequence as another String
object using this constructor:
 String(String strObj) Here, strObj is a String object.
Example:
class test
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
[Link](s1);

}
}
 OUTPUT: Java

 String length
length()-To find a length of string.
Syntax:- String [Link] ( );
Example:-
class length
{
public static void main(String[] args)
{
String s1=new String ("HELLO");
[Link]([Link]());
}
}
 OUTPUT:5

 Special string operation


string literals, concatenation of multiple String objects by use of the + operator, and the
conversion of other data types to a string representation.
String literals
 For each string literal in your program, Java automatically constructs a String object.
 Thus, you can use a string literal to initialize a String object.
 Example:-
class literal
{

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

public static void main(String[] args)


{
String s2 = "KAP"; // use string literal
[Link]("KAP".length());
}
}
 OUTPUT:3
 Because a String object is created for every string literal, you can use a string literal any
place you can use a String object.

String Concatenation(+ Operator)


 In general, Java does not allow operators to be applied to String objects.
 The one exception to this rule is the + operator, which concatenates two strings, producing
a String object as the result.
 This allows you to chain together a series of + operations
 Example:
class concat
{
public static void main(String[] args)
{
String name = "Hello " + "World";
[Link](name);
}
}

 Character Extraction
charAt ( ) :- To abstract single character from a string.
 Syntax :- String [Link] (Position of character);
 Example
class strcharat
{
public static void main(String[] args)
{
String s1=new String("Hello");
[Link]([Link](3));
}
}

getBytes( )
 There is an alternative to getChars( ) that stores the characters in an array of
bytes.
 This method is called getBytes( ), and it uses the default character-to-byte
conversions provided by the platform.
 Syntax:
 byte[ ] getBytes( )

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

getChars( )

 If you need to extract more than one character at a time, you can use the getChars( )
method.
 Syntax
 void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
 sourceStart:- specifies the index of the beginning of the substring
 sourceEnd:- specifies an index that is end of the desired substring.
 The array that will receive the characters is specified by target.
 The index within target at which the substring will be copied is passed in
targetStart.
 Example:
class getCharsDemo
{
public static void main(String args[])
{
String name= "This is a demo of the getChars method.";
int s=10;
int e=14;
char n[] = new char[e - s];
[Link](s, e, n, 0);
[Link](n);
}
}

toCharArray( )
 If you want to convert all the characters in a String object into a character array, the
easiest way is to call toCharArray( ).
 It returns an array of characters for the entire string.
 Syntax:
 char[ ] toCharArray( )
 This function is provided as a convenience, since it is possible to use getChars( ) to
achieve the same result.

 String comparison
equals ( )
 The equal’s methods compare the character inside string of.
 It returns true if the string contains same character in the same order & otherwise false.
 The comparison is case sensitive.
 Syntax
 String [Link] (string object2);
 Example:-1
class equals
{
public static void main(String[] args)
{
String s1=new String("Java");
String s2=new String("Java");
[Link]([Link](s2));
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example 2:-
class equals1
{
public static void main(String[] args)
{
String s1=new String ("Hello");
String s2=new String ("Hello");
if([Link](s2))
{
[Link] ("strings are equal");
}
else
{
[Link] ("strings are not equal");
}
}
}

compare To( )
 It compares weather two string are less then, greater than or equal.
 Returns negative if s1<s2 Returns positive if s1>s2 Returns zero if s1=s2.
 Syntax
 String [Link] (string object2);
 Example:-
class strcompare
{
public static void main(String[] args)
{
String s1=new String("Hello");
String s2=new String("Hello");
[Link]([Link](s2));
}
}

 Searching strings

The String class provides two methods that allow you to search a string for a
specified character or substring:
 indexOf( ) Searches for the first occurrence of a character or substring.
 lastIndexOf( ) Searches for the last occurrence of a character or substring.
indexOf ( )
 Gives the position of first occurrence of ‘h’ in the string s1.
 Syntax
 String [Link](‘h’);
 Example:-
class indexof
{
public static void main (String [] args)
{
String s1=new String ("Hello");
[Link] ([Link] ('h'));
}
} Page 4 K.A. Prajapati

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Modifying a string
substring( )
 You can extract a substring using substring( ). It has two forms.
 Syntax:
String substring(int startIndex)
 Here, startIndex specifies the index at which the substring will begin.
 This form returns a copy of the substring that begins at startIndex and runs to the
end of the invoking string.
 The second form of substring( ) allows you to specify both the beginning and
ending index of the substring:
 String substring(int startIndex, int endIndex)
startIndex specifies the beginning index
endIndex specifies the stopping point.
 Example:-
class substring
{
public static void main(String[] args)
{
String s1=new String("Hello");
[Link]([Link](2,5));
}
}
concat ( )
 This method is use to concatenate two string s1 & s2.
 Syntax:
 String [Link](string object2);
 Example:-
class concat
{
public static void main(String[] args)
{
String s1=new String ("Hello");
String s2=new String ("BSPP");
[Link]([Link](s2));
}
}
replace ( )
 Replace method replaces all occurrence of one character in the string with
another characters.
 Syntax
 String [Link] (‘old character’,’ new character’);
 Example:-
class replace
{
public static void main(String[] args)
{
String s1=new String("Java");
[Link]([Link]('J','h'));
}
}
Page 5 K.A. Prajapati

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

trim( )
 Remove white space at beginning & end of the string.
 Syntax
 String [Link]( );
 Example:-
class strtrim2
{
public static void main(String[] args)
{
String s1=new String(" Hello");
[Link] ([Link]());
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 toUpperCase ( )

This method converts all character in a string from lower to upper.


Syntax:
String [Link]();
Example:-
class upper
{
public static void main (String[] args)
{
String s1=new String("Hello");
[Link] ([Link]());
}
}

 toLowerCase ( )

This method converts all character in a string from upper to lower.


Syntax
 String [Link]();
 Example:-
class lower
{
public static void main(String[] args)
{
String s1=new String ("HELLO");
[Link] ([Link]());
}
}

 valueOf( )

String class valueOf method example:-


 This example demonstrates the working of valueOf method. this method returns String
representations of all data types values
 Syntax:-
 String valueOf(boolean b)
 Java String class defines following methods to convert various Java primitives to Java
String object.
 static String valueOf(int i)
 Converts argument int to String and returns new String object representing argument int.
 static String valueOf(float f)
 Converts argument float to String and returns new String object representing argument
float.
 static String valueOf(long l)
 Converts argument long to String and returns new String object representing argument
long.
 static String valueOf(double i)
 Converts argument double to String and returns new String object representing argument
double.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 static String valueOf(char c)


 Converts argument char to String and returns new String object representing argument
char.
 static String valueOf(boolean b)
 Converts argument boolean to String and returns new String object representing
argument boolean.
 static String valueOf(Object o)
 Converts argument Object to String and returns new String object representing argument
Object.
 Example:-
public class Test
{
public static void main(String args[])
{
int i=10;
float f = 10.0f;
long l = 10;
double d=10.0d;
char c='a';
boolean b = true;
Object o = new String("Hello World");

[Link]( [Link](i) ); // convert int to String


[Link]( [Link](f) ); //convert float to String
[Link]( [Link](l) ); // convert long to String
[Link]( [Link](d) ); //convert double to String
[Link]( [Link](c) ); //convert char to String
[Link]( [Link](b) ); //convert boolean to String
[Link]( [Link](o) ); //convert Object to String
}
}

 String buffer
String buffer is used to create modifiable(mutable) string.
It allows character or substring to be inserted in the middle or append at the end.
length( ) : To find a length of string buffer.
 Syntax
 [Link]();
 Example:-
class length
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello");
[Link] ([Link] ());
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

capacity()
 The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
 Syntax
 [Link]();
 Example:-
class capacityofstring
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2

}
}
append()
 Append string s2 to s1 at the end.
 Syntax
 [Link]();
 Example:-
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java"); //now original string is changed
[Link](sb); //prints Hello Java
}
}

insert ( )
 Insert the string s2 at the position of index s1.
 ‘N’=character of string of index.
 Syntax
 [Link] (index of charecter,”string” );
 Example:-
class insert
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java"); //now original string is changed
[Link](sb); //prints Hjavaello
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

reverse( )
 You can reverse the characters within a StringBuffer object using reverse( ), shown here:
 Syntax:
 StringBuffer reverse( )
 This method returns the reversed object on which it was called
 Example:-
class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Hello");
[Link]();
[Link](s); //prints olleH
}
}

delete( )
 You can delete characters within a StringBuffer by using the methods delete( )
 Syntax:
 StringBuffer delete(int startIndex, int endIndex)
 The delete( ) method deletes a sequence of characters from the invoking object.
 Here, startIndex specifies the index of the first character to remove, and endIndex
specifies an index one past the last character to remove.
 Example:-
class deleteDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb); //prints Hlo
}
}

replace( )
 You can replace one set of characters with another set inside a StringBuffer object by
calling replace( ).
 Syntax:-
 StringBuffer replace(int startIndex, int endIndex, String str)
 The substring being replaced is specified by the indexes startIndex and endIndex.
 Thus, the substring at startIndex through endIndex–1 is replaced.
 The replacement string is passed in str.
 The resulting StringBuffer object is returned.
 Example:-
class replaceDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb); //prints HJavalo

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

}
}

 Vector Class
Vector class is in [Link] package of java.
Vector is dynamic array which can grow automatically according to the required need.
Vector does not require any fix dimension like String array and int array.
Vector contains many useful methods.
To add element in Vector, we can use add() method of vector class.
To add elements at fix position, we have to use add(index, object) method.
To get value from Vector, Vector provides get() method and Vector size() method.
Size() method returns total number of elements in Vector.
Vector is synchronized, ArrayList is not
Syntax of some important method of Vector class. Given below.
 add(Object o) : It adds the element in the end of the Vector.
 elements() : It returns an enumeration of the element.
 elementAt(int index) : It returns the element at the specified index.
 firstElement() : It returns the first element of the vector.
 lastElement() : It returns last element.
 removeElementAt(int index) : It deletes the element from the given index.
 size() : It returns total number of components available in vector.

Example:-1
import [Link].*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> a=new Vector<String>();
[Link]("1");
[Link]("2");
[Link]("3");
[Link]("4");
[Link]("5");
[Link](3, "Element at fix position");
[Link]("Vector Size :"+[Link]());
for(int i=0;i<[Link]();i++)
{
[Link]("Vector Element "+[Link](i));
}
[Link](“Vector Array:-”+a);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Example-2:
import [Link];
import [Link];

public class VectorExample3


{
public static void main(String[] arr)
{
// creates a empty object of vector class
Vector<Integer> a=new Vector<Integer>();
// Add elements in vector
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link]("Elements in vactor class.");
// creates a enumeration object of vector class.
Enumeration ob1=[Link]();
while ([Link]())
{
[Link]([Link]()+" ");
}
}
}

 What is difference between string and string buffer?


Strings are immutable(unmodifiable). which means once u initialize the value for
this? it can not be changed.
StringBuffer is mutable(modifiable) and one can change the contents of it strings
are immutable where as string buffer is a mutable, that means strings having the
fixed size and stringbuffer size is varied(grow able).
The significant performance difference between these two classes is that String
Buffer is faster than String when performing simple concatenations.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

9. APPLETS AND APPLICATIONS


 The Applet class
 What is an Applet?
 An applet is a Java program that embedded with web content(html) and runs in a Web
browser. It runs inside the browser and works at client side.
 We can fetch image, audio clip, play audio clip, Print a status message in the browser, and
Get the network location in applet.
 You have to import [Link] ,[Link] packages
 Advantages of Applet:
 It works at client side so less response time.
 More Secured
 Applets can work on all the version of Java Plugin.
 Applets are supported by most web browsers in many platforms like Windows, Mac OS and
Linux platform.
 User can also have full access to the machine if user allows.
 Disadvantages of Java Applet:
 Java plug-in is required to run applet.
 Java applet requires JVM so first time it takes significant start up time
 Its difficult to design and build good user interface in applets compared to HTML technology

 Applets and HTML (The applet Tag)


 To start with an applet first of all we need to learn applet tag.
 There are two ways to run an applet
(1) By html file.
(2) By appletviewer tool (for testing purpose).
 Applets have the file extension "class". An example would be " [Link]". Some applets
consist of more than just one class file.
 Before embedding an applet on your page you need to upload the required files to your server.
 Below is a short example showing how simple it is to embed an applet on a page

Attribute Explanation Example


Code Name of class file Code=" [Link]"
Width Width of applet Width=200
Height Height of applet Height=100
Alt" Text that will be shown in browsers alt="Menu Applet"
where the ability to show applets has
been turned off.
Name Assigning a name to an applet can Name="starter"
be used when applets should
communicate with each other.
Align=Left/Right/Top Justifies the applet according to the Align=Right
/Middle/Bottom text and images surrounding it.
A full explanation of the individual
parameters is given here.
Vspace Space over and under the applet. Vspace=20
Hspace Space to the left and right of applet. Hspace=40

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 The procedure to create and run an applet goes as follows for an applet that simply displays
Welcome to Java in its graphical window and also prints it to the Java console.

 1) run By HTML file


 Step 1: Use an editor to enter the following code for FirstApplet applet:
import [Link].*;
import [Link].*;
public class FirstApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("Welcome to Java",150,150);
}
}
 Save this code into a file called [Link] . (Note that the file name must match
exactly with the class name FirstApplet.)
 Step 2: Then compile the application with javac [Link]
 This creates the class file [Link]
 Step 3: Next you must create a web page file to hold the applet.
 Put the following code into a HTML file give name [Link]:
<HTML>
<Head>
<Title> A Simple Program </Title>
<Body>
<Applet Code="FirstApplet .class" width="150" height="50">
</Applet>
</Body>
</HTML>
 Then put this file into the same directory as the [Link] file.
 Step 4: We have included the applet in this web page. So opening the file [Link] in
your browser will display the same as the window here. You can also see the "Welcome to Java"
line in the Java Console of the browser.

 2) By appletViewer tool (for testing purpose).


 An alternative way to run the applet is with appletviewer: appletviewer [Link]
import [Link].*;
import [Link].*;
public class FirstApplet extends Applet
{
/*
<applet CODE="FirstApplet .class" width="300" height="300">
</applet>
*/
public void paint(Graphics g)
{
[Link]("Welcome to Java", 150, 150);
}
}
 Compile : D:\java\javac [Link]
 Run : D:\java\appletviewer [Link]

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Life cycles of an applets(Init(), start, stop, destroy method).


 The life cycle of an applet involves the following five stages:
 Initialization
 Starting
 Stopping
 Destroying
 Painting

 The following methods implement the life cycle of an Applet:


 init(): This method is called to initialized an applet.
 start(): This method is called after the initialization of the applet.
 stop(): This method can be called multiple times in the life cycle of an Applet.
 destroy(): This method is called only once in the life cycle of the applet when applet is
destroyed.

 Initialization(init() method)
 Initialization occurs when the applet is first loaded (or reloaded).
 It is called after the param tags inside the applet tag have been processed.
 Syntax :
public void init ( )
{
// Original signature over ridden
}

 Starting(start() method)
 After an applet is initialized, it is started.
 Starting can happen many different times during an applet’s lifetime, whereas initialization
happens only once.
 Starting can also occur if the applet was previously stopped.
 For example, an applet is stopped if the reader follows a link to a different page, and is
started again when the reader returns back to the page.
 Syntax:
public void start ( )
{
// Original signature over ridden
}

 Stopping(stop() method)
 Stopping occurs when the reader leaves the page that contains a currently running applet, or
by calling the stop ( ) method.
 By default, when the reader leaves a page, any threads the applet had started will continue
running.
 Syntax:
public void stop ( )
{
// Original signature over ridden
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Destroying(destroy() method)
 Destroying enables the applet to perform a cleanup job just before it is destroyed or the
browser exits for example, or release any other resources.
 Generally the destroy( ) method is overridden if there are specific objects that need to be
released, for example threads that the applets has created .
 Syntax:
public void destroy ( )
{
// Original signature over ridden
}

 Painting(paint() method)
 Called immediately after the start() method, and also any time the applet needs to repaint
itself in the browser. The paint() method is actually inherited from the [Link].
 Painting is the way an applet actually draws something on the screen, be it text, a line, a
colored background, or an image.
 Painting may occur a number of times during an applets life cycle.
 The Paint( ) method gets executed every time the applet is minimized or maximized, or
when the applet is initialized and the browser is placed behind another window on the
screen, and then brought forward again.
 Syntax:
public void paint (Graphics g)
{
// Original signature over ridden
}

 Graphics class
 The AWT(Abstract Window Toolkit) graphics class is an abstract class that is the basis for all
graphical constructions in Java.
 You cannot implement this class directly.
 You use the paint and update methods to implement the features in the Graphics class in your
programs.
 You use the following code line to declare the paint method:
 public void paint(Graphics g)
 To include the different primitives of the Graphics class, be sure to import it into your program:
import [Link];
 The example applet shown these ideas. The output from this applet is Figure
import [Link].*;
import [Link].*;
public class demo extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10, 10, 100, 100)
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 drawString():
 The drawSring() method draws the given string as the parameter. Here is the syntax of the
drawString() method :
 Syntax:
drawString(String string, int X, int Y);
X is the starting X- axis coordinate
Y is the starting Y- axis coordinate
 Example:
import [Link].*;
import [Link].*;
public class HelloWorld extends Applet
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
public void paint(Graphics g)
{
[Link]("Hello world!", 50, 25);
}
}

 drawRect() and fillRect():


 drawRect() method used to create a rectangle.
 fillRect() method to draw a color-filled rectangle.
Syntax:-
[Link] ( int X,int Y, int width, ino height);
[Link] ( int X,int Y, int width, ino height);
X is the starting X- axis coordinate, counting from the left edge of the screen
Y is the starting Y- axis coordinate, counting from top edge of the screen
width is the width of the rectangle
height is the height of the rectangle
 The Graphics class provides additional methods that you can use for creating different types
of rectangles.
 Example:
import [Link].*;
import [Link].*;
public class Rect1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10,50,10,20);
[Link](50,80,100,200);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 clearRect()
 The clearRect() method can be used to clear a rectangular area.
 Syntax:
[Link] (int X, int Y, int Width, int Height)
 Height: The vertical size of the rectangle in pixels.
 Width: The horizontal size of the rectangle in pixels.
 X: Horizontal location of the upper left corner of the rectangle, in pixels.
 Y: Vertical location of the upper left corner of the rectangle, in pixels.
 Example:-
import [Link];
import [Link].*;
public class Clear1 extends Applet
{
public void paint (Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link] (20, 20, 180, 180);
[Link] (50, 70, 120, 80);
}
}

 drawLine()
 You use the drawLine() method to draw a line.
 Syntax:-
[Link] (int startX, into startY, into endX, into endY );
startX is the starting X- axis coordinate
startY is the starting Y- axis coordinate
endX is the ending X- axis coordinate
endY is the ending Y- axis coordinate
 Example:-
import [Link].*;
import [Link].*;
public class line1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10,20,30,40) ;
}
}

 fillRoundRect() And drawRoundRect()


 drawRoundRect ( ) method used to create a Rounded rectangle and fillRoundRect() method
used to create filled Rounded rectangle
 Used to draw to rectangle with rounded corners.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Syntax:-
g. drawRoundRect(int X, int Y, int Width, int Height, int arcWidth, int arcHeight);
[Link](int X, int Y, int Width, int Height, int arcWidth, int arcHeight);

 X is the starting X- axis coordinate, counting from the left edge of the screen
 Y is the starting Y- axis coordinate, counting from top edge of the screen
 width is the widths of the rectangle
 height is the height of the rectangle
 The curvature of the corners is specified by the two arguments, arcWidth and arcHeight.
 You can also use the fillRoundRect() method to draw a color-filled of rounded rectangle.
 Example:-
import [Link].*;
import [Link].*;
public class RoundRect1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](10,50,100,150,68,120) ;
[Link](50,50,100,150,68,120) ;
}
}

 drawOval() and fillOval()

 The drawOval() and fillOval() methods to draw circles and ellipses. The difference between
drawing circles and ellipses lies in the coordinates specified in the drawOval() method.
Syntax:
g. drawOval (int X, int Y, int Width , int Height);
g. fillOval (int X, int Y, int Width , int Height);
X and Y represent the top-left screen coordinates
width and height represent the width and the height of the circle or ellipse
 In the case of a circle, the width and height should be same.
 Example:
import [Link].*;
import [Link].*;
public class Oval1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link](50,50,100,150);
[Link] (100,150,100,150);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 drawArc():
 Description:
Used to draw an arc, which is similar to an incomplete oval.
The first parameters are similar to those for drawing an oval.
The last two parameters specify the starting and ending angles of the arc.
Example:
import [Link].*;
import [Link].*;
public class Arc1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
setBackground([Link]);
[Link]([Link]);
[Link](150,150,100,150,190,200);
}
}

 drawPolygon():
 drawPolygon() and fillpolygon() methods of the graphics class. In the case of a polygon,
the coordinates are specified as a part of two array variables.
 Syntax:
[Link] (int x[] , int y[] , int points) ;
 In the give syntax
x [] is an array of x-axis coordinates
y [] is an array of y-axis coordinates
points is the number of points defined by the (x, y) coordinates
 Example:
import [Link].*;
import [Link].*;
public class Polygon1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
int x[]={20,100,150};
int y[]={230,220,280};
int n=3;
[Link](x,y,n);
[Link](x,y,n);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Painting the applet


 Update():
 This method is defined by the AWT and is called when your applet has requested that a
portion of its window be redrawn.
 The problem is that the default version of update() first fills an applet with the default
background color and then calls paint(), this gives rise to a flash of default color (usually gray)
each time update is called.
 To avoid this you define your update() method such that it performs all necessary display
activities
 The paint() in this case will simply call update().
public void update(Graphic g)
{
//Redisplay your window here.
}

public void paint(Graphics g)


{
update(g) // call to the update()method.
}
 You need to override update() only when needed.

 Paint():
 The paint() method is called each time your applet's output must be redrawn.
 For example, the window in which the applet is running may be overwritten by another
window and then uncovered.
 Or the applet window was resized.
 paint() is also called when the applet begins execution.
 Whatever the cause, whenever the applet must redraw its output, paint() is called.
 The paint() method has one parameter of type Graphics.
 This is needed for the applet to know where the applet should paint its output.
public void paint(Graphics g)
{
//Body.
}
 Example:-
import [Link].*;
import [Link].*;
public class Paint1 extends Applet
{
public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
</applet>
*/
[Link]([Link]);
[Link]("KAP",100,50);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 repaint():
 The repaint() method is defined by the AWT. It causes the AWT run time system to call to
your applet's update() method, which in its default implementation, calls paint().
 Again for example if a part of your applet needs to output a string, it can store this string in a
variable and then call repaint()
 Inside paint(), you can output the string using drawstring().
 The repaint method has two forms.
void repaint()
void repaint(int left, int top, int width, int height)
 Let's look at each one –
void repaint()
This causes the entire window to be repainted
void repaint(int left, int top, int width, int height)
This specifies a region that will be repainted. integers left, top, width and height are in
pixels. You save time by specifying a region to repaint instead of the whole window.

 Passing parameters to applets getparameter() method


 Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the
opening and closing APPLET tags.
 Inside the applet, you read the values passed through the PARAM tags with the getParameter()
method of the [Link] class.
 The applet parameter "Message" is the string to be drawn.
 Example:-
import [Link].*;
import [Link].*;
public class Getparameter extends Applet
{

private String a = "Hello!";


public void paint(Graphics g)
{
/*
<applet CODE="[Link]" width="100" height="100">
<PARAM name="Message" value="How Are You!">
</applet>
*/
String b = [Link]("Message");
if (b == null)
{
b = a;
}
[Link](b, 50, 25);
}
}
 You also need an HTML file that references your applet. The following simple HTML file will
do:
<html>
<body>
<applet CODE="[Link]" width="100" height="100">

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

<PARAM name="Message" value="How Are You!">


</applet>
</body
</html>
 Of course you are free to change "How are you" to a "message" of your choice.
 You only need to change the HTML, not the Java source code. PARAMs let you customize
applets without changing or recompiling the code.
 However rather than hard coding the message to be printed it's read into the variable b from a
PARAM element in the HTML.
 You pass getParameter() a string that names the parameter you want.
 This string should match the name of a PARAM element in the HTML page.
 getParameter() returns the value of the parameter. All values are passed as strings. If you want to
get another type like an integer, then you'll need to pass it as a string and convert it to the type you
really want.
 The PARAM element is also straightforward. It occurs between <APPLET> and </APPLET>.
 It has two attributes of its own, NAME and VALUE.
 NAME identifies which PARAM this is.
 VALUE is the string value of the PARAM. Both should be enclosed in double quote marks if they
contain white space.
 An applet is not limited to one PARAM. You can pass as many named PARAMs to an applet as
you like.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

10. USING AWT IN APPLICATION


 The AWT classes
 The Abstract Window Toolkit(AWT) contains numerous classes and methods that allow you to create
and manage windows.
 Although the main purpose of the AWT is to support applet windows, it can also be used to create
stand-alone windows that run in GUI environment, such as windows.
 The AWT classes are contained in the '[Link]' package.
 Fortunately, because it is logically organized in a top-down, hierarchical fashion, it is easier to
understand and use.
 Following are the list of some AWT classes.
Class Description
AWTEvent Encapsulates AWT events.
BorderLayout The border layout manager. Border layouts use five components: North, South,
East West, and Center.
Button Creates a push button control.
Canvas A blank, semantics-free window.
CardLayout The card layout manager. Card layouts emulate index cards. Only the one on top
is showing.
Checkbox Creates a checkbox control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list/Dropdown list(Combo box).
Color Manages colors in a portable, platform-independent fashion.
Container A subclass of Component that can hold other components.
Dialog Creates a dialog window.
Event Encapsulates events.
FileDialog Creates a window from which a file can be selected.
FlowLayout The flow layout manager. Flow layout positions components left to right, top to
bottom.
Font Encapsulates a type font.
Frame Creates a standard window that has t title bar, resize corners, and a menu bar.
Graphics Encapsulates the graphics context. This context is used by the various output
methods to display output in a window.
GridLayout The grid layout manager. Grid layout displays components in a two-dimensional
grid.
Image Encapsulates graphical images.
Label Creates a label that displays a string.
List Creates a list from which the user can choose. Similar to the standard Windows
list box.
Menu Creates a pull-down menu.
MenuBar Creates a menu bar.
MenuComponent An abstract class implemented by various menu classes.
MenuItem Creates a menu item.
MenuShortcut Encapsulates a keyboard shortcut for a menu item.
Panel The simplest concrete subclass of Container.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Point Encapsulates a Cartesian co-ordinate pair, stored in x and y.


Polygon Encapsulates a polygon.
PopupMenu Encapsulates a pop-up menu.
PrintJob An abstract class that represents a print job.
Rectangle Encapsulates a rectangle.
Scrollbar Creates a scroll bar control.
ScrollPane A container that provides horizontal and/or vertical scroll bars for another
component.
SystemColor Contains the colors of GUI widgets such as windows, scroll bars, text, and
others.
TextArea Creates a multiline edit control.
TextComponent A superclass for TextArea and TextField.
TextField Creates a single-line edit control.
Toolkit Abstract class implemented by the AWT.
Window Creates a window with no frame, no menu bar, and no title.

 Layout Manager:
 A layout manager is an object that is used to organize components in a container.
 Layout managers are objects that determine how the components are organized in a
container.
 Every container has a default layout manager.
 There are types of layout manager:
Flow layout
Grid layout
Border layout
Card layout
 A class of the same name represents each layout manager.
 To use a layout manager in a Java program, you need to use an object of the
corresponding layout manager class.
 To use a layout manager for a container, create an object of the appropriate layout
manager class, and use the setLayout ( ) method to specify the type of the layout to be
used.
 Flow Layout
 The flow layout manager is the default layout manager for applets and panels.
 It places controls linearly from left to right and from top to bottom in horizontal and vertical
rows.
 For example, when the layout manager reaches the right border of the container, it positions the
components in the next row.
 The flow layout manager places the controls centrally aligned in each row.
 Example:-
import [Link].*;
import [Link].*;
public class Aptflow1 extends Applet
{
public void init()
{
/*

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

<Applet CODE="[Link]" width="100" height="100">


</Applet>
*/
Button bt1=new Button("ok");
Button bt2=new Button("save");
FlowLayout bl=new FlowLayout([Link]);
setLayout(bl);
add(bt1);
add(bt2);
}
}
 Grid Layout
 The grid layout manager is used to position components in a grid.
 The grid layout manager organizes the components by placing them in a rectangular grid
consisting of rows and columns.
 The number of components and the size of the container determine the size of a cell.
 The manager divides the area of the container by the number of components to obtain the size of
a cell.
 Example:-
import [Link].*;
import [Link].*;
public class Aptgrid extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Button bt1=new Button("ok");
Button bt2=new Button("save");
Button bt3=new Button("ok1");
Button bt4=new Button("save1");
GridLayout gl=new GridLayout(2,2);
setLayout(gl);
add(bt1);
add(bt2);
add(bt3);
add(bt4);
}
}
 Border Layout
 The border layout is the default layout for windows and dialog boxes.
 The border layout manager is used to organize components along the four borders of the
container with one component in the center.
 In addition, the border layout manager is used to create interfaces that focus on region- based
positioning(directions) of components instead of coordinates based position as in flow and
layouts, and to create dialog boxes that display captions along with the ‘OK’ and ‘CANCEL’
buttons.
 Example:-
import [Link].*;

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

import [Link].*;
public class AptBorder extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Button bt1=new Button("ok");
Button bt2=new Button("cancel");
BorderLayout bl=new BorderLayout(2,2);
setLayout(bl);
add(bt1,[Link]);
add(bt2,[Link]);
}
}
 Card Layout
 The CardLayout layout manager is significantly different from the other layouts.
 The CardLayout is unusual.
 It breaks the applet into a deck of cards, each of which will normally have a panel with its own
LayoutManager.
 Only one card appears on the screen at a time.
 You then flip between cards, each of which shows a different set of components.
 The common analogy is with an installer wizard.
 This might be used for a series of data input screens, where more input is needed than can
comfortably be fit on one screen.
 Conversely, you can use a CardLayout for a slide show, where there's more data to be presented
than will fit on one screen.
 Example:
import [Link].*;
import [Link].*;
public class CardExample extends Applet
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
CardLayout cl=new CardLayout();
public void init()
{
setLayout(cl);
Panel pA = new Panel();
Panel pC = new Panel();
setLayout(new GridLayout(3,1));
List l =new List(3,false);
Choice c=new Choice();
[Link]("A");
[Link]("B");
[Link]("C");

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

[Link]("Male");
[Link]("Female");

[Link](l);
[Link](c);
add("One",pA);
add("Two",new Button("Click Here"));
add("Three",pC);
}
}
 Panel:
 To make Applet or Frame layout easier, you break a frame up into regions and compose each of
them separately. Each region is called a Panel
 Each can have its own different LayoutManager. Panels don’t have any visible bounding lines.
 You can delimit them with differing background colours.
 Example:
import [Link].*;
import [Link].*;
public class PanelExample extends Applet
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
public void init()
{
Button bt1=new Button("ok");
Panel p1=new Panel();
[Link](bt1);
add(p1);
}
}
 Canvas
 The [Link] class is a rectangular area on which you can draw using the methods of
[Link].
 The Canvas class has only three methods:
 public Canvas()
 public void addNotify()
 public void paint(Graphics g)
Example:-import [Link].*;
import [Link].*;
public class MyCanvas extends Applet
{
/*<applet code=[Link] height=300 width=500>
</applet>*/
public MyCanvas()
{
setSize(200, 400);
}
public void paint(Graphics g)
{
[Link](0, 0, 90, 50);
[Link]("A Canvas", 15,15);
}} Page 5 [Link]

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 You generally won't instantiate a canvas directly. Instead you'll subclass it and override the paint()
method in your subclass to draw the picture you want.
 Frame
 Usage: A Frame is a top-level window with a title and a border. It is normally used as the main
window of a standalone application.
 Package: [Link]
 Class: [Link]
 Parent Classes
 [Link] implements MenuContainer
 [Link] implements Accessible
 [Link]
 [Link] implements ImageObserver, MenuContainer, Serializable
 [Link]
 Common Public Methods
 addWindowListener(WindowListener Handler): Configures a window event handler for the
frame.
 setBackground (Color BackgroundColor): Sets the background color of the frame.
 setFont (Font TextFont): Sets the font for this component.
 setForeground (Color TextColor): Sets the color of the text for the frame.
 setSize (int Width, int Height): Resizes this window so that it has the specified Width and
Height.
 setTitle (String Text): Sets the text for the title bar.
 show (): Makes the window visible.
 Arguments
 BackgroundColor: The color to be used for the background of the button.
 Handler: The object which handles window events from this frame.
 Text: The text to appear in the title bar.
 TextColor: The color to be used for the text of the button.
 TextFont: The font to be used for the text of the button.

 Example:
import [Link].*;
import [Link].*;
public class Frame2 extends Frame
{
public static void main(String[] args)
{
Frame f=new Frame("Button Frame");
Button button = new Button("Submit");
[Link](button);
[Link](new FlowLayout());
[Link](200,100);
[Link](true);

[Link](new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
}
);
}}
Page 6 [Link]

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Dialog box
 Dialog boxes are pop-up windows on the screen that appear for a small time to take either input or
display output while a main application is running
 The windows that appear for a brief time are known as transient windows.
 Dialog boxes are generally used to draw special attention of the user like displaying warnings.
 Dialog box is a top-level window that comes with a border including a title bar.
 The dialog box can be made non-resizable and the default layout manager is BorderLayout which
can be overridden.
 A dialog box works within a main program.
 It cannot be created as a standalone application.
 It is a child window and must be connected to a main program or to a parent window.
 Frame is a parent window as it can work independently.
 For example, the Find and Replace Dialog box cannot be obtained without opening MS-Word
document.
 Likewise, File Deletion Confirmation box cannot appear without deleting a file.
 Two commonly used constructors are shown here:
 Dialog(Frame parentWindow, boolean mode)
 Dialog(Frame parentWindow, String title, boolean mode)
 Example:
import [Link].*;
import [Link].*;
import [Link].*;

public class test extends Applet implements ActionListener


{
/*<applet code="[Link]" width="320" height="230" ></applet>*/

public void init()


{
Button bt1 = new Button("Push Button");
[Link](this);
add(bt1);
}
public void actionPerformed(ActionEvent e)
{
Frame f = new Frame();
Dialog d = new Dialog(f, "hello", true);
[Link](new Label("hello"));
[Link]();
}
}

 Controls

 Textbox
 Usage: The TextField class can be used to add single line text input to a container.
 Package: [Link]
 Parent Classes:
 [Link] implements Accessible
 [Link] implements ImageObserver, MenuContainer, Serializable
 [Link]

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Common Public Methods


 void addActionListener (ActionListener Handler):Configures an event handler for the
TextField.
 String getText():- Returns the text in the field.
 void setBackground([Link]):- Sets the background color of the TextField.
 void setEditable (boolean Editable):- Sets the field as being editable or fixed.
 void setFont (Font TextFont):- Sets the font for this component.
 void setText (String Text):- Sets the text for the field.
 Arguments
 BackgroundColor:- The color to be used for the background of the field.
 Editable:- The state of the field as editable or fixed.
 Handler:- The object which handles action events from this field.
 Text:- The text to appear in the field.
 TextFont:- The font to be used for the text of the button.

 Example:
import [Link].*;
import [Link].*;
public class AptTextbox extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
TextField t=new TextField("Your Name");
add(t);
}
}

 TextArea
 Usage: The TextArea class is a GUI component which can be used to provide multiple line text
input or output.
 Package: [Link]
 Parent Classes:
 [Link] implements Accessible
 [Link] implements ImageObserver, MenuContainer, Serializable
 [Link]
 Common Public Methods
 void addActionListener (ActionListener Handler):Configures an event handler for the
TextField.
 String getText ():- Returns the text in the field.
 void setBackground (Color BackgroundColor):- Sets the background color of the TextField.
 void setEditable (boolean Editable):- Sets the field as being editable or fixed.
 void setFont (Font TextFont):- Sets the font for this component.
 void setText (String Text):- Sets the text for the field.
 Arguments
 BackgroundColor:- The color to be used for the background of the field.
 Editable:- The state of the field as editable or fixed.
 Handler:- The object which handles action events from this field.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Text:- The text to appear in the field.


 Rows:- The height of the text area.
 TextFont:- The font to be used for the text of the button.

 Example:-
import [Link].*;
import [Link].*;
public class AptTextArea extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
TextArea t=new TextArea("Your Address");
add(t);
}
}

 Button
 Usage:- The Button class can be used to add interactive buttons to a container.
 Package:- [Link]
 Parent Classes
 [Link] implements ImageObserver, MenuContainer, Serializable
 [Link]
 Common Public Methods
 void addActionListener (ActionListener Handler)
 void setBackground (Color BackgroundColor):- Sets the background color of the button.
 void setEnabled (boolean State):- Enables or disables the button.
 void setFont (Font TextFont):- Sets the font for this component.
 void setForeground (Color TextColor):- Sets the color of the text for the button.
 void setLabel (String Text):- Sets the text for the button.
 Arguments
 ActionText:- The ActionCommand text for the event associated with the button.
 BackgroundColor:- The color to be used for the background of the button.
 Handler:- The object which handles action events from this combo box.
 State:- The enable state of the button (true or false.)
 Text:- The text to appear next to the button.
 TextColor:- The color to be used for the text of the button.
 TextFont:- The font to be used for the text of the button.
 Example:
import [Link].*;
import [Link].*;
public class AptButton extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

*/
Button b1=new Button("Submit");
add(b1);
}
}

 Label
 Usage: The Label class can be used to add text labels to a container.
 Package: [Link]
 Subclass of: [Link]
 Common Methods:
 void setBackground (Color BgdColor):Sets the color of the background for the label.
 void setAlignment (int Alignment):Sets the alignment of the label's contents along the
X axis.
 void setFont (Font TextFont):Sets the font for this component.
 void setForeground (Color TextColor):Sets the color of the text for the label.
 void setText (String Text):Sets the text for the label.
 Arguments:
 Alignment: The horiziontal position of the text within the label. One of:
[Link]: The central position in an area.
[Link]: Box-orientation constant used to specify the left side of a box.
[Link]: Box-orientation constant used to specify the right side of a box.
 BgdColor:The color to be used for the background of the label.
 Text:The text to appear in the label.
 TextColor:The color to be used for the text of the label.
 TextFont:The font to be used for the text of the label.
 Example:
import [Link].*;
import [Link].*;
public class Aptlabel extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Label l1=new Label("User Name");
add(l1);
}
}

 CheckBox
 Usage:The CheckBox class can be used to add interactive grouped radio checkboxs to a
container.
 Package: [Link]
 Subclass of: [Link]
 Common Methods:
 void addItemListener (ItemListener Handler):- Configures an event handler for the
checkbox.
 boolean isSelected ():- Returns the state (checked or not checked) of the checkbox.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 void setBackground (Color BackgroundColor):- Sets the background color of the checkbox.
 void setSelected (boolean State):- Sets the state (checked or not checked) of the checkbox.
 void setFont (Font TextFont):- Sets the font for this component.
 void setForeground (Color TextColor):- Sets the color of the text for the checkbox.
 void setLabel (String Text):- Sets the text for the checkbox.
 Arguments:
 BackgroundColor:- The color to be used for the background of the checkbox.
 Group:- A CheckboxGroup for interactive boxes to act as radiobuttons.
 Handler:- The object which handles action events from this combo box.
 State:- The checked state of the checkbox (true or false.)
 Text:- The text to appear in the checkbox.
 TextColor:- The color to be used for the text of the checkbox.
 TextFont:- The font to be used for the text of the checkbox.
 Example: 1(Simple CheckBox)
import [Link].*;
import [Link].*;
public class AptCheckbox extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Checkbox ch=new Checkbox("FootBall");
add(ch);
Checkbox ch1=new Checkbox("Cricket");
add(ch1);
}
}
 Example:2(RadioButton)
import [Link].*;
import [Link].*;
public class AptRadio extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
CheckboxGroup cg =new CheckboxGroup();
Checkbox cmale=new Checkbox("Male",cg,false);
add(cmale);
Checkbox cfemale=new Checkbox("Female",cg,false);
add(cfemale);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Choice
 Usage: The Choice(Combobox) class can be used to add a drop-down list of items to a container
 Package: [Link]
 Subclass of: [Link]
 Common Methods:
 void addItemListener (ItemListener Handler):- Configures an event handler for the choice
box.
 void insert (String Item, int Index): Inserts the item into this choice at the specified position.
 int getSelectedIndex (): Returns the index of the selected item.
 void setBackground (Color BackgroundColor): Sets the background color of the choice box.
 void setFont (Font TextFont): Sets the font for this component.
 void setForeground (Color TextColor): Sets the color of the text for the choice box.
 void Select (int Selection): Sets the index of the selected item.
 Arguments:
 BackgroundColor: The color to be used for the background of the choice box.
 Index: Position where the item will be inserted.
 Item: A String to be listed in the choice box.
 Handler: The object which handles action events from this choice box.
 Selection: The index of the selected item.
 TextColor: The color to be used for the text of the choice box.
 TextFont: The font to be used for the text of the choice box.
 Example:-
import [Link].*;
import [Link].*;
public class AptChoice extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Choice ch=new Choice();
[Link]("India");
[Link]("USA");
add(ch);
}
}

 List
 Usage: The List class can be used to add a list of items with several visible rows to a container.
 Package: [Link]
 Class: [Link]
 Parent Classes
 [Link]
 [Link]
 [Link]
 Common Public Methods
 void addItemListener (ItemListener Handler) : Specifies an event handler for the list.
 void add (String Item) : Inserts the item into this choice at the next position.
 void add (String Item, int Index) : Inserts the item into this choice at the specified position.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 int getSelectedIndex (): Returns the index of the selected item.


 void setBackground (Color BackgroundColor): Sets the background color of the list.
 void setFont (Font TextFont) : Sets the font for this component.
 void setForeground (Color TextColor) : Sets the color of the text for the list.
 void Select (int Selection): Sets the index of the selected item.
 Arguments
 BackgroundColor: The color to be used for the background of the list.
 Index: Position where the item will be inserted.
 Item: A String to be listed in the list.
 Handler: The object which handles action events from this list.
 Multiselect: If true, multiple items can be selected.
 Selection: The index of the selected item.
 TextColor: The color to be used for the text of the list.
 TextFont: The font to be used for the text of the list.
 Example:-
import [Link].*;
import [Link].*;
public class AptList extends Applet
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
List lt=new List();
[Link]("A");
[Link]("B");
[Link]("C");
add(lt);
}
}

 Scrollbar
 Usage: The Scrollbar lets the user graphically select a value by sliding a knob within a bounded
interval.
 Package: [Link]
 Subclass of: [Link]
 Common Methods:
 addAdjustmentListener (AdjustmentListener Handler): Configures an event handler for the
scrollbar.
 getValue (): Returns the value of the scrollbar setting.
 setBackground (Color BackgroundColor): Sets the background color of the scrollbar.
 setMaximum (int Max): Sets the maximum value of the scrollbar.
 setMinimum (int Min): Sets the minimum value of the scrollbar.
 setValue (int Value): Sets the current value of the scrollbar.
 Arguments:
 BackgroundColor: The color to be used for the background of the field.
 Handler: The object which handles action events from this field.
 Max: The maximum value of the scrollbar.
 Min: The minimum value of the scrollbar.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Orientation: The orientation of the scrollbar.


[Link]: Orients the scrollbar horizontally.
[Link]: Orients the scrollbar vertically.
 Value: The current value of the scrollbar.
 Example:
import [Link].*;
import [Link].*;
public class AptScroll extends Applet
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Scrollbar vs,hs;
public void init()
{
vs = new Scrollbar([Link]);
hs = new Scrollbar([Link]);
add(vs);
add(hs);
}
}
 Difference between Applet and Stand-alone Application
 An applet is a program written in the Java programming language that can be included in an HTML
page, much in the same way an image is included. An application is a standalone Java program that
runs as a true application, outside of a browser. Both require a JVM (Java Virtual Machine). 
 An applet runs under the control of a browser, whereas an application runs stand-alone, with the
support of a virtual machine. As such, an applet is subjected to more stringent security restrictions
in terms of file and network access, whereas an application can have free reign over these
resources. 
 Applets are great for creating dynamic and interactive web applications, but the true power of Java
lies in writing full blown applications. With the limitation of disk and network access, it would be
difficult to write commercial applications (though through the user of server based file systems, not
impossible). However, a Java application has full network and local file system access, and its
potential is limited only by the creativity of its developers

 Extra Example:

Example 1: Write a program to Scroll the scrollbar and value display in textbox.
import [Link].*;
import [Link].*;
import [Link].*;

public class AptScroll extends Applet implements AdjustmentListener


{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Scrollbar vs,hs;
TextField t1;

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

TextField t2;
public void init()
{
vs = new Scrollbar([Link]);
t1 = new TextField(2);
hs = new Scrollbar([Link]);
t2 = new TextField(2);
add(vs);
add(t1);
add(hs);
add(t2);
[Link](this);
[Link](this);
}

public void adjustmentValueChanged(AdjustmentEvent ae)


{
int val = [Link]();
[Link]([Link](val));

int val1 = [Link]();


[Link]([Link](val1));
}

 Example 2: Write a program using ActionListener Event of a button.


import [Link].*;
import [Link].*;
import [Link].*;
public class Actionevent extends Applet implements ActionListener
{
public void init()
{
/*
<Applet CODE="[Link]" width="100" height="100">
</Applet>
*/
Button bt1=new Button("ok");
add(bt1);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
setBackground([Link]);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example 3: Write a program to add two numbers using Textbox.


import [Link].*;
import [Link].*;
import [Link].*;
public class AptSum extends Applet implements ActionListener
{
public int c;
TextField t1,t2,t3;
public void init()
{
// <Applet CODE="[Link]" width="100" height="100"></Applet>
Button bt=new Button("Sum");
add(bt);
t1=new TextField(20);
add(t1);
t2=new TextField(20);
add(t2);
t3=new TextField(20);
add(t3);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
c=[Link]([Link]())+[Link]([Link]());
[Link](" " +c);
}
}

 Example 4: Write a program using Mouse Event.

import [Link].*;
import [Link].*;
import [Link].*;
public class AptMouse extends Applet implements MouseListener,MouseMotionListener
{
// <Applet CODE="[Link]" width="100" height="100"></Applet>
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
setBackground([Link]);
}
public void mouseEntered(MouseEvent me)
{
setBackground([Link]);
}
public void mouseExited(MouseEvent me)
{

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

setBackground([Link]);
}
public void mousePressed(MouseEvent me)
{
setBackground([Link]);
}
public void mouseReleased(MouseEvent me)
{
setBackground([Link]);
}
public void mouseDragged(MouseEvent me)
{
setBackground([Link]);
}
public void mouseMoved(MouseEvent me)
{
setBackground([Link]);
}
}

 Example 5: Write a program using FocusListener event.


import [Link].*;
import [Link].*;
import [Link].*;
public class AptFocus extends Applet implements FocusListener
{
TextField t1,t2,t3,t4,t5;
public void init()
{
// <Applet CODE="[Link]" width="100" height="100"></Applet>
t1=new TextField(12);
t2=new TextField(13);
t3=new TextField(14);
t4=new TextField(15);
t5=new TextField(15);
add(t1);
add(t2);
add(t3);
add(t4);
add(t5);
[Link](this);
}
public void focusGained(FocusEvent e)
{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
if(a<b && a<c)
{
[Link](" "+a);

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

}
else if(b<a && b<c)
{
[Link](" " +b);
}
else
{
[Link](" " +c);
}
}
public void focusLost(FocusEvent e)
{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
if(a>b && a>c)
{
[Link](" "+a);

}
else if(b>a && b>c)
{
[Link](" " +b);
}
else
{
[Link](" " +c);
}
}
}

 Example 6: Write a program using ItemListener event


import [Link].*;
import [Link].*;
import [Link].*;
public class AptItem extends Applet implements ItemListener
{
//<Applet CODE="[Link]" width="100" height="100"></Applet>
public void init()
{
Checkbox ch1=new Checkbox("Red");
add(ch1);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
setBackground([Link]);
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example 7: Write a program of Applet life cycle.


import [Link].*;
import [Link].*;
public class AptCycle extends Applet
{
// <Applet CODE="[Link]" width="100" height="100"> </Applet>
String msg;
public void init()
{
msg="inti";
}
public void start()
{
msg=msg + "start";
}
public void paint(Graphics g)
{
[Link](msg,10,10);
}
public void stop()
{
[Link]("stop");
}
public void destroy()
{
[Link]("destroy");
}
}

 Example 8: Write a program of calculator using applet.


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

public class AptCal extends Applet implements ActionListener


{
// <applet code=[Link] height=400 width=500></applet>
TextField t1,t2,t3;
Button bt1,bt2,bt3,bt4;
public void init()
{
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField(15);

bt1=new Button("Add");
bt2=new Button("Sub");
bt3=new Button("Mul");
bt4=new Button("Div");

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

add(bt1);
add(bt2);
add(bt3);
add(bt4);
add(t1);
add(t2);
add(t3);

[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
int a,b,c;
a=[Link]([Link]());
b=[Link]([Link]());
if([Link]()==bt1)
{
c=a+b;
[Link](" "+ c);
}
else if([Link]()==bt2)
{
c=a-b;
[Link](" "+ c);
}
else if([Link]()==bt3)
{
c=a*b;
[Link](" "+ c);
}
else
{
c=a/b;
[Link](" "+ c);
}
}
}

 Example 9: Write a program to implement Menu Bar using Frame.


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

public class MainWindow1 extends Frame


{
public MainWindow1()
{
super("Menu Window");
setSize(400, 400);

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

FileMenu fileMenu = new FileMenu(this);


MenuBar mb = new MenuBar();
[Link](fileMenu);
setMenuBar(mb);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exit();
}
}
);
}
public void exit()
{
setVisible(false);
dispose();
[Link](0);
}
public static void main(String args[])
{
MainWindow1 w = new MainWindow1();
[Link](true);
}
class FileMenu extends Menu implements ActionListener
{
MainWindow1 mw;
public FileMenu(MainWindow1 m)
{
super("File");
mw = m;
MenuItem mi;
add(mi = new MenuItem("Open"));
[Link](this);
add(mi = new MenuItem("Close"));
[Link](this);
add(mi = new MenuItem("Exit"));
[Link](this);
}

public void actionPerformed(ActionEvent e)


{
String item = [Link]();
if ([Link]("Exit"))
[Link]();
else
[Link]("Selected FileMenu " + item);
}
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

 Example 10: Write a program using KeyListener event

public class keyboard extends Applet implements KeyListener


{
//<Applet CODE="[Link]" width="100" height="100"> </Applet>

String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Realeased");
}
public void keyTyped(KeyEvent ke)
{
msg +=[Link]() ;
repaint();
}
public void paint(Graphics g)
{
[Link](msg,100,200);
}
}

 Example 11: Write a program to Throw Exception Using Scanner Class


import [Link].*;
class Throw3
{
public static void main(String[] args) throws Exception
{
String s;
Scanner x=new Scanner([Link]);
[Link]("Enter String");
s=[Link]();
if([Link]("hello"))
{
[Link]("Both string are same");
}
else
{
throw new Exception("Nomatch Exception");
}
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

11. APPLET, EVENT HANDLING, SWINGS:


Applet:
• Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a Web document.
A simple applet program:

import [Link].*;
import [Link].*;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("A Simple Applet", 20, 20);
}
}

Program explanation:
• Applet must be declared as public, because it will be accessed by code that is outside
the program.
• Inside SimpleApplet, paint( ) is declared.
• This method is defined by the AWT and must be overridden by the applet.
• paint( ) is called each time that the applet must redisplay its output.
void drawString(String message, int x, int y)
• Notice that the applet does not have a main( ) method.
• Unlike Java programs, applets do not begin execution at main( ).
• In fact, most applets don’t even have a main( ) method.
• Instead, an applet begins execution when the name of its class is passed to an applet viewer
or to a network browser.

Two ways in which you can run an applet:


• Executing the applet within a Java-compatible web browser.
• Using an applet viewer, such as the standard tool, appletviewer.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• An applet viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
• To execute an applet in a web browser, you need to write a short HTML text file that contains
a tag that loads the applet.
• Currently, Sun recommends using the APPLET tag for this purpose.
• Here is the HTML file that executes SimpleApplet:

<applet code="MyApplet" width=200 height=60> This comment contains an APPLET tag


</applet> that will run an applet called MyApplet in
a window that is 200 pixels wide and 60
pixels hight.

Faster way of executing an applet :


• Include the applet code in your program itself

import [Link].*;
import [Link].*;
/* Execution procedure:
<applet code="SimpleApplet" width=200 1) Compile your program.
height=60> </applet> 2) Execution :
*/ C:\AppletViewer [Link]
public class SimpleApplet extends Applet
{ public void paint(Graphics g) {
[Link]("A Simple Applet", 20, 20);
}
}

Two Types of Applets


There are two varieties of applets

1) Applet:-These applets use the Abstract Window Toolkit(AWT) to provide the graphic
user interface

2) JApplet:-The second type of applet is JApplet are those based on the Swing
[Link] applet use the Swing classes to provide the GUI.
Because JApplet inherits Applet ,all the features of Applet are also available in JApplet .

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Applet Basics
• All applets are subclasses (either directly or indirectly) of Applet.
• Applets are not stand-alone programs. Instead, they run within either a web browser or
an applet viewer.
• Execution of an applet does not begin at main().
• Output to your applet’s window is not performed by [Link].
• Rather, in non-Swing applets, output is handled with various AWT methods, such as
drawString(),Which outputs a string to a specified X,Y location.

The Applet Class:


• Applet provides all necessary support for applet execution, such as starting and stopping.
• It also provides methods that load and display images, and methods that load and play
audio clips.
• Applet extends the AWT class Panel.
• In turn, Panel extends Container, which extends Component.
• Thus, Applet provides all of the necessary support for window-based activities.

Method Description
void destroy( ) Called by the browser just before an applet is terminated.
Your applet will override this method if it needs to perform
any cleanup prior to its destruction.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip
found at the location specified by url.
URL getCodeBase( ) Returns the URL associated with the invoking applet.
URL getDocumentBase( ) Returns the URL of the HTML document that invokes the
applet.
Image getImage(URL url) Returns an Image object that encapsulates the image found at
the location specified by url.
String getParameter(String paramName) Returns the parameter associated with paramName.
null is returned if the specified parameter is not found.
void init( ) Called when an applet begins execution. It is the first method
called for any applet.
boolean isActive( ) Returns true if the applet has been started. It returns false if
the applet has been stopped.
void play(URL url) If an audio clip is found at the location specified by url, the
clip is played.
void play(URL url, String clipName) If an audio clip is found at the location specified by url with
the name specified by clipName, the clip is played.
void resize(int width, int height) Resizes the applet according to the dimensions specified by
width and height.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Applet Architecture
• An applet is a window-based program. As such, its architecture is different from the so called
Normal, console-based programs.
There are a few key concepts you must understand:
• First, applets are event driven. An applet waits until an event occurs.
• The AWT notifies the applet about an event by calling an event handler that has been
provided by the applet. Once this happens, the applet must take appropriate action and then
quickly return control to the AWT.
• Second, the user initiates interaction with an applet.
• The user interacts with the applet as he or she wants, when he or she wants.
• These interactions are sent to the applet as events to which the applet must respond.

• For example, when the user clicks a mouse inside the applet's window, a mouse-clicked
event is generated.
• If the user presses a key while the applet's window has input focus, a keypress event
is generated.

An Applet Skeleton
• All but the most trivial applets override a set of methods that provides the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its execution.

• Four of these methods are init( ), start( ), stop( ), and destroy( ) these are defined
by Applet.
• Another, paint( ), is defined by the AWT Component class. Applets do not need to override
those methods because they do not use.
Here is an example of Applet program with all basic functions

import [Link].*; public void stop(){


import [Link].*; [Link]("inside Stop");
/* <applet code="AppletTest1" width=200 height=200> }
</applet> */ public void destroy() {
public class AppletTest1 extends Applet [Link]("inside destroy");
{ }
public void init() { public void paint(Graphics g)
[Link]("inside init"); {
} [Link]("Hello Applet", 20,20);
public void start(){ }
[Link]("inside start"); }
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Applet Initialization and Termination


• init( ) :- The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.
• start( ) :- The start( ) method is called after init( ). Whereas init( ) is called once the first time
an applet is loaded, start( ) is called each time an applet's HTML document is displayed
onscreen.
• paint( ) :- The paint( ) method is called each time your applet's output must be redrawn.
• stop( ) :- The stop( ) method is called when a web browser leaves the HTML
document containing the applet when it goes to another page,

• destroy( ) :- The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory.
Simple Applet Display Methods
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]

• To set the background color of an applet's window, use setBackground( ).


• To set the foreground color (the color in which text is shown, for example),
use setForeground( ).
These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor)
void setForeground(Color newColor )

A simple applet that sets the foreground and background colors and outputs a string:
import [Link].*; public void start() {
import [Link].*; msg += " Inside start( ) --";
/* <applet code="Sample" width=300 height=50> }
</applet> */ // Display msg in applet window.
public class Sample extends Applet{ public void paint(Graphics g) {
String msg; msg += " Inside paint( ).";
public void init() { [Link](msg, 10, 30);
setBackground([Link]); }
setForeground([Link]); }
msg = "Inside init( ) --";
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Requesting Repainting
• Whenever your applet needs to update the information displayed in its window, it simply
calls repaint( ).
• The repaint( ) method is defined by the AWT.
• It causes the AWT run-time system to execute a call to your applet's update( ) method,
which, in its default implementation, calls paint( ).
• For example, if part of your applet needs to output a string, it can store this string in a String
variable and then call repaint( ).
• Inside paint( ), you will output the string using drawString( ).
• The repaint( ) method has four forms.

The simplest version of repaint( ) is shown here:



void repaint( ) This version causes the entire window to be repainted.

The following version specifies a region that will be repainted:


void repaint(int left, int top, int width, int height)
• Here, the coordinates of the upper-left corner of the region are specified by left and top,
and the width and height of the region are passed in width and height. These dimensions
are specified in pixels.
• Calling repaint( ) is essentially a request that your applet be repainted sometime soon.
• Multiple requests for repainting that occur within a short time can be collapsed by the AWT in
a manner such that update( ) is only called sporadically.

void repaint(long maxDelay)


void repaint(long maxDelay, int x, int y, int width, int height )
• Here, maxDelay specifies the maximum number of milliseconds that can elapse
before update( ) is called.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

A Simple Banner Applet

• To demonstrate repaint( ), a simple banner applet is developed.


• This applet scrolls a message, from right to left, across the applet’s window.
• Since the scrolling of the message is a repetitive task, it is performed by a separate thread,
created by the applet when it is initialized.
The banner applet is shown here:
(This applet creates a thread that scrolls the message contained in msg right to left across the applet's
window)

import [Link].*; // Entry point for the thread that runs the
import [Link].*; banner.
/* public void run() {
<applet code="SimpleBanner" width=300 height=50> char ch;
</applet> // Display banner
*/ for( ; ; ) {
public class SimpleBanner extends Applet implements try {
Runnable repaint();
{ [Link](250);
String msg = " A Simple Moving Banner."; ch = [Link](0);
Thread t = null; msg = [Link](1, [Link]());
int state; msg += ch;
boolean stopFlag; if(stopFlag)
break;
// Start thread } catch(InterruptedException e) {}
public void start() { }// end of for
t = new Thread(this); } // end of run
stopFlag = false; // Pause the banner.
[Link](); public void stop() {
} stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
[Link](msg, 50, 30);
}}

• First, notice that SimpleBanner extends Applet, as expected, but it also implements Runnable.
• The AWT run-time system calls start( ) to start the applet running.
• Inside start( ), a new thread of execution is created and assigned to the Thread variable t.
• Then, the boolean variable stopFlag, which controls the execution of the applet, is set to false.
• Next, the thread is started by a call to [Link]( ).

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• Remember that [Link]( ) calls a method defined by Thread, which causes run( ) to
begin executing.
• It does not cause a call to the version of start( ) defined by Applet.
• These are two separate [Link] run( ), the characters in the string contained in msg
are repeatedly rotated left.
• Between each rotation, a call to repaint( ) is made. This eventually causes the paint( )
method to be called and the current contents of msg is displayed.
• Between each iteration, run( ) sleeps for a quarter of a second.
• The net effect of run( ) is that the contents of msg is scrolled right to left in a
constantly moving display.
• The stopFlag variable is checked on each iteration. When it is true, the run( )
method terminates.

Using the Status Window

• An applet can also output a message to the status window of the browser or applet viewer on
which it is running.
• To do so, call showStatus( ) with the string that you want displayed.
The following applet demonstrates showStatus( ):

// Using the Status Window.


import [Link].*;
import [Link].*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends
Applet{ public void init() {
setBackground([Link]);
}
// Display msg in applet window.
public void paint(Graphics g) {
[Link]("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The HTML APPLET Tag

• The APPLET tag is used to start an applet from both an HTML document and from an applet
viewer.
• An applet viewer will execute each APPLET tag that it finds in a separate window, while web
browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on
a single page.
The syntax for the standard APPLET tag is shown here.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>

Let’s take a look at each part now:

CODEBASE:- CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applet's executable class file (specified by the CODE
tag).

CODE:- CODE is a required attribute that gives the name of the file containing your applet's compiled
.class file.

ALT:- The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but can't currently run Java applets.

NAME:- NAME is an optional attribute used to specify a name for the applet instance. To obtain an
applet by name, use getApplet( ), which is defined by the AppletContext interface.

WIDTH and HEIGHT:- WIDTH and HEIGHT are required attributes that give the size (in pixels) of
the applet display area.

ALIGN:- ALIGN is an optional attribute that specifies the alignment of the applet.

VSPACE and HSPACE:- These attributes are optional. VSPACE specifies the space, in pixels, above
and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

PARAM NAME and VALUE:- The PARAM tag allows you to specify applet-specific arguments in an
HTML page. Applets access their attributes with the getParameter( ) method.

Passing Parameters to Applets

• To retrieve a parameter, use the getParameter( ) method.


• It returns the value of the specified parameter in the form of a String object.
Here is an example that demonstrates passing parameters:

import [Link].*; param =


import [Link].*; getParameter("fontSize"); try {
/* if(param != null) // if not found
<applet code="PDemo" width=300 height=80> fontSize =
<param name=fontName value=Courier> [Link](param); else
<param name=fontSize value=14> fontSize = 0;
<param name=accountEnabled value=true> } catch(NumberFormatException e)
</applet> */ { fontSize = -1;
public class PDemo extends Applet{ }
String fontName;
int fontSize; param = getParameter("accountEnabled");
boolean active; if(param != null)
// Initialize the string to be displayed. active = [Link](param).booleanValue();
public void start() { }
String param; // Display parameters.
fontName = getParameter("fontName"); public void paint(Graphics g) {
if(fontName == null) [Link]("Font name: " + fontName, 0, 10);
fontName = "Not Found"; [Link]("Font size: " + fontSize, 0, 26);
[Link]("Account Active: " + active, 0, 58);
}
}

getDocumentBase( ) and getCodeBase( )

• You will create applets that will need to explicitly load media and text. Java will allow
the applet to load data from the directory holding the HTML file that started the applet
• (The document base) and the directory from which the applet's class file was loaded (the
code base).

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

A Simple Program showing document base

// Display code and document


bases. import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="Bases" width=300
height=50> </applet> */
public class Bases extends Applet{
// Display code and document bases.
public void paint(Graphics g)
{ String msg;
URL url = getCodeBase(); // get code
base msg = "Code base: " + [Link]();
[Link](msg, 10, 20);
url = getDocumentBase(); // get document
base msg = "Document base: " + [Link]();
[Link](msg, 10, 40);
}}

AppletContext and showDocument( )

• To allow your applet to transfer control to another URL, you must use the showDocument( )
method defined by the AppletContext interface.
• AppletContext is an interface that lets you get information from the applet's execution
environment.
• The context of the currently executing applet is obtained by a call to the getAppletContext(
) method defined by Applet.
• Within an applet, once you have obtained the applet's context, you can bring
another document into view by calling showDocument( ).

• There are two showDocument( ) methods. The method showDocument(URL) displays


the document at the specified URL.
• The method showDocument(URL, where) displays the specified document at the
specified location within the browser window.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Event Handling: (changing activity ex: mouse event or keyboard event):


• Event handling is integral to the creation of applets and other types of GUI-based programs
• Without the event handling mechanism it is not possible to write the GUI codes.
• Events are supported by a number of packages, including [Link], [Link],
and [Link].

• The Delegation Event Model: Delegation event model, which defines standard and
consistent mechanisms to generate and process events.

Working of Delegation event model: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event.
Once an event is received, the listener processes the event and then returns.

Events
• In the delegation model, an event is an object that describes a state change in a source.

• Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
• Many other user operations could also be cited as examples.

• Event may be generated when a timer expires, a counter exceeds a value, software
or hardware failure occurs, or an operation is completed.
• You are free to define events that are appropriate for your application.

1) Event Sources
• A source is an object that generates an event.
• Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notifications about
a specific type of event.
• Each type of event has its own registration method.

Multi casting: (Registering more than one event )


Here is the general form:
public void addTypeListener(TypeListener el) (Multi casting means more than one listener)

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• For example, the method that registers a keyboard event listener is called addKeyListener( ).
• The method that registers a mouse motion listener is called addMouseMotionListener( ).
• When an event occurs, all registered listeners are notified and receive a copy of the
event object. This is known as multicasting the event.

Unicasting (Registering only one event)


public void addTypeListener(TypeListener el) throws
[Link] (unicasting)

Unregistering an Event:
• A source must also provide a method that allows a listener to unregister an interest in
a specific type of event.
The general form of such a method is this:
public void removeTypeListener(TypeListener el)
• you would call removeKeyListener( ).

2) Event Listeners
• A listener is an object that is notified when an event occurs. It has two major requirements.
• First, it must have been registered with one or more sources to receive notifications
about specific types of events.
• Second, it must implement methods to receive and process these notifications.
• For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.

Event Classes
• At the root of the Java event class hierarchy is EventObject, which is in [Link]. It is
the superclass for all events.
• It’s one constructor is shown here:
constructor: EventObject(Object src)
Note: Here, src is the object that generates this event.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

EventObject contains two methods:


getSource( ) and toString( ).
1) The getSource( ) method
• returns the source of the event. Its general form is shown here:
constructor: Object getSource( )
2) toString( ) returns the string equivalent of the event.

AWTEvent:
• The class AWTEvent, defined within the [Link] package, is a subclass of EventObject.
• It is the superclass (either directly or indirectly) of all AWT-based events used by
the delegation event model.
NOTE:
To summarize:
• EventObject is a superclass of all events.
• AWTEvent is a superclass of all AWT events that are handled by the delegation event
model.
• Commonly used constructors and methods in each class are described in the
following sections:
The Action Event Class
• An Action Event is generated when a button is pressed, a list item is double-clicked, or
a menu item is selected.
• The Action Event class defines four integer constants that can be used to identify
any modifiers associated with an action event:
• ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK.
• In addition, there is an integer constant, ACTION_ PERFORMED, which can be used to
identify action events.
Classes in [Link]:
Event Class Description
Action Event Generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or becomes
visible.
ContainerEvent Generated when a component is added to or removed from a container.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

FocusEvent Generated when a component gains or loses keyboard focus.


InputEvent Abstract superclass for all component input event classes.
ItemEvent Generated when a check box or list item is clicked: also occurs when a
choice selection is made or a checkable menu item is selected or
deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or
released; also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved.
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified.
iconified. opened, or quit.

The KeyEvent Class (used for keyboard events)


• A KeyEvent is generated when keyboard input occurs.
• There are three types of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.
• The first two events i.e KEY_PRESSED, KEY_RELEASED are generated when any key
is pressed or released.
• The last event i.e. KEY_TYPED occurs only when a character is generated
NOTE: Remember, not all key presses result in characters. For example, pressing SHIFT
does not generate a character.
• There are many other integer constants that are defined by KeyEvent.

• For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers and letters.
Here are some others:
VK_ALT VK_DOWN VK_LEFT VK_RIGHT
VK_CANCEL VK_ENTER VK_PAGE_DOWN [Link]
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP

• The VK constants specify virtual key codes and are independent of any modifiers, such
as control, shift, or alt.

KeyEvent class is a subclass of InputEvent


Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
• Here, src is a reference to the component that generated the event.
• The type of the event is specified by type.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• The system time at which the key was pressed is passed in when.
• The modifiers argument indicates which modifiers were pressed when this key event
occurred. (ALT, SHIFT, CTRL)
• The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
• The character equivalent (if one exists) is passed in ch.
• If no valid character exists, then ch contains CHAR_UNDEFINED.
• For KEY_TYPED events, code will contain VK_UNDEFINED.

KeyEvent class methods:

• The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar( ), which returns the character that was entered, and getKeyCode( ),
which returns the key code.
Their general forms are shown
here: char getKeyChar( )
int getKeyCode( )
• If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.
When a KEY_TYPED event occurs when no valied key is pressed , getKeyCode( ) returns
VK_UNDEFINED.
Key board event program:

// Demonstrate the key event handlers. public void keyPressed(KeyEvent ke) {


import [Link].*; showStatus("Key Down");
import [Link].*; }
import [Link].*;
/* public void keyReleased(KeyEvent ke) {
<applet code="SimpleKey" width=300 height=100> showStatus("Key Up");
</applet> }
*/ public void keyTyped(KeyEvent ke)
public class SimpleKey extends { msg += [Link]();
Applet implements KeyListener { repaint();
String msg = ""; }
int X = 10, Y = 20; // output coordinates // Display keystrokes.
public void init() { public void paint(Graphics g)
addKeyListener(this); { [Link](msg, X, Y);
} }
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The MouseEvent Class (used for keyboard events):


• There are eight types of mouse events.
• The MouseEvent class defines the following integer constants that can be used to
identify them:
MOUSE_CLICKED The user clicked the mouse.
[Link] The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
[Link] The mouse moved.
MOUSE_PRESSED The mouse was pressed.
[Link] The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.

MouseEvent is a subclass of InputEvent.


Here is one of its constructors:
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks,
boolean triggersPopup)
1. The coordinates of the mouse are passed in x and y.
2. The click count is passed in clicks.
3. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this
platform.
• Two commonly used methods in this class are getX( ) and getY( ). These return the X and Y
coordinates of the mouse within the component when the event occurred.
• Their forms are shown here: int getX( ), int getY( )
• Alternatively, you can use the getPoint( ) method to obtain the coordinates of the
mouse. It is shown here:

• Point getPoint( ) : It returns a Point object that contains the X,Y coordinates in its integer
members: x and y.
• The getClickCount( ) method obtains the number of mouse clicks for this event.
Its signature is shown here: int getClickCount( )
• The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform.
Its form is shown here:
boolean isPopupTrigger( )

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Also available is the getButton( ) method, shown here:


int getButton( )
• It returns a value that represents the button that caused the event. The return value will be one
of these constants defined by MouseEvent:
NOBUTTON BUTTON1 BUTTON2 BUTTON3

• Java SE 6 added three methods to MouseEvent that obtain the coordinates of the
mouse relative to the screen rather than the component.
They are shown here:
1. Point getLocationOnScreen( )
2. int getXOnScreen( )
3. int getYOnScreen( )

Sources of Events: these are the classes which can be used in the place of src.
Event Source Description
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
Menu Item Generates action events when a menu item is selected; generates item events
when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.

• Event Listener Interfaces


• The ActionListener Interface
KeyListener Defines three methods to recognize when a key is pressed, released, or
typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The KeyListener Interface


• This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are
invoked when a key is pressed and released, respectively.
• The keyTyped( ) method is invoked when a character has been entered.
• For example, if a user presses and releases the A key, three events are generated in
sequence: key pressed, typed, and released.
• If a user presses and releases the HOME key, two key events are generated in sequence:
key pressed and released.

The MouseListener Interface:


• This interface defines five methods.
• If the mouse is pressed and released at the same point, mouseClicked( ) is invoked.
• When the mouse enters a component, the mouseEntered( ) method is called.
• When it leaves, mouseExited( ) is called.

• The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively.
The general forms of these methods are shown here:
1. void mouseClicked(MouseEvent me)
2. void mouseEntered(MouseEvent me)
3. void mouseExited(MouseEvent me)
4. void mousePressed(MouseEvent me)
5. void mouseReleased(MouseEvent me)

The MouseMotionListener Interface


• This interface defines two methods. The mouseDragged( ) method is called multiple
times as the mouse is dragged.
• The mouseMoved( ) method is called multiple times as the mouse is
moved. Their general forms are shown here:
1. void mouseDragged(MouseEvent me)
2. void mouseMoved(MouseEvent me)

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• Now that you have learned the theory behind the delegation event model and have had
an overview of its various components, it is time to see it in practice.

Using the delegation event model is actually quite easy. Just follow these two steps:

• 1. Implement the appropriate interface in the listener so that it will receive the type
of event desired.
• 2. Implement code to register and unregister (if necessary) the listener as a recipient
for the event notifications.

Handling Mouse Events:


• To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces.

Working of the mouse event Applet program:


• It displays the current coordinates of the mouse in the applet’s status window.
• Each time a button is pressed, the word “Down” is displayed at the location of the
mouse pointer.
• Each time the button is released, the word “Up” is shown.
• If a button is clicked, the message “Mouse clicked” is displayed in the upperleft corner of
the applet display area.
• As the mouse enters or exits the applet window, a message is displayed in the upper-left
corner of the applet display area.
• When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.
• Notice that the two variables, mouseX and mouseY, store the location of the mouse when a
mouse pressed, released, or dragged event occurs.
• These coordinates are then used by paint( ) to display output at the point of
these occurrences.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Working of the mouse event Applet program:

// Demonstrate the mouse event public void mouseExited(MouseEvent me) {}


handlers. import [Link].*;
import [Link].*; public void mousePressed(MouseEvent me) {}
import [Link].*;
/* public void mouseReleased(MouseEvent me) {
<applet code="MouseEvents" width=300 }
height=100> </applet>
*/ public void mouseDragged(MouseEvent me) {
public class MouseEvents extends Applet }
implements MouseListener, MouseMotionListener
{ public void mouseMoved(MouseEvent me) {
String msg = ""; }
int mouseX = 0, mouseY = 0; // coordinates of mouse public void paint(Graphics g) {
public void init() { [Link](msg, mouseX, mouseY);
addMouseListener(this); }}
addMouseMotionListener(this);
}
// Handle mouse clicked. Note: It is compulsory to define all the
public void mouseClicked(MouseEvent me) above functions as we are implementing
{ mouseX = 0; mouseY = 10; the interfaces (MouseMotionsListener &
MouseListener ).
msg = "Mouse
clicked."; repaint(); But it is not compulsory to write some
} functionality in the body, we can keep the
body of the functions as empty, as we had
public void mouseEntered(MouseEvent me) {} done here.

Explanation of program :
• The MouseEvents class extends Applet and implements both the MouseListener and
MouseMotionListener interfaces.
• These two interfaces contain methods that receive and process the various types of
mouse events.
• Notice that the applet is both the source and the listener for these events.
• This works because Component, which supplies the addMouseListener( )
and addMouseMotionListener( ) methods, is a superclass of Applet.
• Being both the source and the listener for events is a common situation for applets.
• Inside init( ), the applet registers itself as a listener for mouse events.
• This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as
mentioned, are members of Component.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

They are shown here:


void addMouseListener(MouseListener ml)
void addMouseMotionListener(MouseMotionListener mml)
addMouseListener(this);
addMouseMotionListener(this)
• The two methods are the part of the Component class which is used to register the
Mouse events.
The Original Methods of Component class are:
void addMouseListener(MouseListener ml)
void addMouseMotionListener(MouseMotionListener mml)

Adapter Classes:
• Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener interface.
• You can define a new class to act as an event listener by extending one of the adapter classes
and implementing only those events in which you are interested.
• For example, the MouseMotionAdapter class has two methods, mouseDragged( )
• and mouseMoved( ), which are the methods defined by the MouseMotionListener interface.
• If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ).
• The empty implementation of mouseMoved( ) would handle the mouse motion events
for you.

Adapter Classes:
• Commonly Used Listener Interfaces Implemented by Adapter Classes

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• The following example demonstrates an adapter. It displays a message in the status bar of
an applet viewer or browser when the mouse is clicked or dragged.
• However, all other mouse events are silently ignored.
• The program has three classes.
• AdapterDemo extends Applet.
• Its init( ) method creates an instance of MyMouseAdapter and registers that object to
receive notifications of mouse events.

• It also creates an instance of MyMouseMotionAdapter and registers that object to


receive notifications of mouse motion events.
• Both of the constructors take a reference to the applet as an argument.
• MyMouseAdapter extends MouseAdapter and overrides the mouseClicked( ) method.
• The other mouse events are silently ignored by code inherited from the MouseAdapter class.

• MyMouseMotionAdapter extends MouseMotionAdapter and overrides the


mouseDragged( ) method.
• The other mouse motion event is silently ignored by code inherited from the
MouseMotionAdapter class.
Program below here shows the example of an adapter class:

// Demonstrate an adapter. // Handle mouse clicked.


import [Link].*; public void mouseClicked(MouseEvent me) {
import [Link].*; AD_obj.showStatus("Mouse clicked");
import [Link].*; }
/* }
<applet code="AdapterDemo" width=300 height=100>
</applet> class MyMouseMotionAdapter extends
*/ MouseMotionAdapter {
public class AdapterDemo extends Applet { AdapterDemo AD_obj;
public void init() { public
addMouseListener(new MyMouseAdapter(this)); MyMouseMotionAdapter(AdapterDemo obj)
addMouseMotionListener(new {
MyMouseMotionAdapter(this)); AD_obj= obj
} }
} // Handle mouse dragged.
class MyMouseAdapter extends MouseAdapter { public void mouseDragged(MouseEvent me)
AdapterDemo AD_obj; {
public MyMouseAdapter(AdapterDemo obj) AD_obj.showStatus("Mouse dragged");
{ }
AD_obj= obj }
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Inner Classes:

• To understand the benefit provided by inner classes, consider the applet shown in
the following listing.
• It does not use an inner class. Its goal is to display the string “Mouse Pressed” in the status

bar of the applet viewer or browser when the mouse is pressed.


Program below Does not uses the Inner Class

// This applet does NOT use an inner class MyMouseAdapter extends MouseAdapter
class. import [Link].*; { MousePressedDemo mousePressedDemo;
import [Link].*; public MyMouseAdapter(MousePressedDemo
/*<applet code="MousePressedDemo" width=200 mousePressedDemo) {
height=100></applet>*/ [Link] = mousePressedDemo;
}
public class MousePressedDemo extends Applet public void mousePressed(MouseEvent me)
{ public void init() { { [Link]("Mouse
addMouseListener(new MyMouseAdapter(this)); Pressed.");
} }
} }

Program showing the use of Inner classes:

// Inner class demo. public void init() {


import [Link].*; addMouseListener(new MyMouseAdapter());
import [Link].*; }
/* class MyMouseAdapter extends MouseAdapter
<applet code="InnerClassDemo" width=200 { public void mousePressed(MouseEvent me) {
height=100> showStatus("Mouse Pressed");
</applet> }
*/ }
public class InnerClassDemo extends Applet { }

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Anonymous Inner Classes:


• An anonymous inner class is one that is not assigned a name. This section illustrates how
an anonymous inner class can facilitate the writing of event handlers.

// Anonymous inner class demo.


import [Link].*;
import
[Link].*; /*
<applet code="AnonymousInnerClassDemo" width=200
height=100> </applet>
*/
public class AnonymousInnerClassDemo extends Applet
{ public void init() {
addMouseListener ( new MouseAdapter() { public void mousePressed(MouseEvent me)
{ showStatus("Mouse Pressed"); }} );
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Swings:
• Although the AWT is still a crucial part of Java, its component set is no longer widely used
to create graphical user interfaces.
• Today, most programmers use Swing for this purpose.
• Swing is a set of classes that provides more powerful and flexible GUI components than does
the AWT.
• Simply put, Swing provides the look and feel of the modern Java GUI.

Two Key Swing Features:


• Two key features: lightweight components and a pluggable look and feel.

Swing Components Are Lightweight:


• With very few exceptions, Swing components are lightweight. This means that they are
written entirely in Java and do not map directly to platform-specific peers.

Components and Containers:


• A component is an independent visual control, such as a push button or slider.
• A container holds a group of components.
• Thus, a container is a special type of component that is designed to hold other components.
• Furthermore, in order for a component to be displayed, it must be held within a container.
• Thus, all Swing GUIs will have at least one container.

• Because containers are components, a container can also hold other containers. This
enables Swing to define what is called a containment hierarchy, at the top of which must be
a top-level container.

Components:
• Swing components are derived from the JComponent class
• JComponent provides the functionality that is common to all components. For example,
JComponent supports the pluggable look and feel.
• JComponent inherits the AWT classes Container and Component.
• All of Swing’s components are represented by classes defined within the
package [Link].

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Components:
Table shows the class names for Swing components (including those used as containers).

JApplet J Button JCheckBox JCheckBoxMenultem


JColorChooser JComboBox JComponent JDesktopPane
JDialog JEditorPane JFileChooser JFormattedTextReld
J Frame JlnternalFrame JLabel JLayeredPane
JList JMenu JMenuBar JMenultem
JOptionPane JPanel JPasswordField JPopupMenu
JProgressBar JRadioButton JRadioButtonMenultem JRootPane
JScrollBar JScrollPane JSeparator JSlider
JSpinner JSplitPane JTabbedPane JTable
JTextArea JTextReld JTextPane JTogglebutton
JToolBar JToolTip JTree JViewport
JWindow

Containers:
• Swing defines two types of containers.
• The first are top-level containers: JFrame, JApplet,
• JWindow, and JDialog.
• These containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container.
• Unlike Swing’s other components, which are lightweight, the top-level containers are
heavyweight.
• This makes the top-level containers a special case in the Swing component library.
• Furthermore, every containment hierarchy must begin with a top-level container.
• The one most commonly used for applications is JFrame.
• The one used for applets is JApplet.
• The second type of containers supported by Swing are lightweight containers.
• Lightweight containers do inherit JComponent.
• An example of a lightweight container is JPanel, which is a general-purpose container.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The Top-Level Container Panes:


• Each top-level container defines a set of panes. At the top of the hierarchy is an instance of
JRootPane.
• JRootPane is a lightweight container whose purpose is to manage the other panes.
• It also helps manage the optional menu bar. The panes that comprise the root pane are
called the glass pane, the content pane, and the layered pane.

The Swing Packages

[Link] [Link] [Link]


[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link]

A Simple Swing Application:


• Swing programs differ from both the console-based programs and the AWT-based programs they
use a different set of components and a different container hierarchy than does the AWT.

import [Link].*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
[Link](275, 100); // Give the frame an initial size.
// Terminate the program when the user closes the application.
[Link](JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel(" Swing means powerful GUIs."); // Create a text-based label.
[Link](jlab); // Add the label to the content pane.
[Link](true); // Display the frame.
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
[Link](new Runnable() { public void run() { new SwingDemo(); }});
}
}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

A Simple Swing Application Explanation:


• It begins by creating a JFrame, using this line of code:
JFrame jfrm = new JFrame("A Simple Swing Application");
• This creates a container called jfrm that defines a rectangular window complete with a title
bar; close, minimize, maximize, and restore buttons; and a system menu.

Next, the window is sized using this statement:


[Link](275, 100);
• The setSize( ) method (which is inherited by JFrame from the AWT class Component)
sets the dimensions of the window, which are specified in pixels.
Its general form is shown here:
void setSize(int width, int height)
setDefaultCloseOperation( )
As the Program Uses this Line:
[Link](JFrame.EXIT_ON_CLOSE);
• By default, when a top-level window is closed (such as when the user clicks the close
box), the window is removed from the screen, but the application is not terminated.
• While this default behavior is useful in some situations, it is not what is needed for
most applications.
• Instead, you will usually want the entire application to terminate when its top-level window is
closed.
• There are a couple of ways to achieve this. The easiest way is to call
setDefaultCloseOperation( ),
• general form of setDefaultCloseOperation( ) is shown here:
void setDefaultCloseOperation(int what)
• The value passed in what determines what happens when the window is closed.
• There are several other options in addition to JFrame.EXIT_ON_CLOSE.
They are shown here:
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
[Link](jlab);

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

General form of add( ) is shown here:


Component add(Component comp);
[Link](true);
• The setVisible( ) method is inherited from the AWT Component class. If its argument is true,
the window will be displayed.
• Otherwise, it will be hidden.
• By default, a JFrame is invisible, so setVisible(true) must be called to show it.
• Inside main( ), a SwingDemo object is created, which causes the window and the label to be
displayed.
• Notice that the SwingDemo constructor is invoked using these lines of code:
[Link]( new Runnable(){ public void run() { new SwingDemo(); }} );
• This sequence causes a SwingDemo object to be created on the event dispatching thread rather
than on the main thread of the application.
• Here’s why. In general, Swing programs are event-driven.
• For example, when a user interacts with a component, an event is generated.
• An event is passed to the application by calling an event handler defined by the application.
However, the handler is executed on the event dispatching thread provided by Swing and
not on the main thread of the application.
• Thus, although event handlers are defined by your program, they are called on a thread
that was not created by your program.
• To avoid problems (including the potential for deadlock), all Swing GUI components must be
created and updated from the event dispatching thread, not the main thread of the application.
• However, main( ) is executed on the main thread.
• Thus, main( ) cannot directly instantiate a SwingDemo object.
• Instead, it must create a Runnable object that executes on the event dispatching thread and
have this object create the GUI.
• To enable the GUI code to be created on the event dispatching thread, you must use one
of two methods that are defined by the SwingUtilities class.
• These methods are invokeLater( ) and invokeAndWait( ).
They are shown here:
static void invokeLater(Runnable obj)
static void invokeAndWait(Runnable obj)throws InterruptedException, InvocationTargetException

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

• Here, obj is a Runnable object that will have its run( ) method called by the event
dispatching thread.
• The difference between the two methods is that invokeLater( ) returns immediately, but
invokeAndWait( ) waits until [Link]( ) returns.
• You can use one of these methods to call a method that constructs the GUI for your Swing
application, or whenever you need to modify the state of the GUI from code not executed
by the event dispatching thread.
• You will normally want to use invokeLater( ), as the preceding program does.
• However, when constructing the initial GUI for an applet, you will need to use
invokeAndWait( ).

Event handling with swings:


• Swing uses the same events as does the AWT, and these events are packaged in
[Link].
• Events specific to Swing are stored in [Link].
Program showing event handling with Swings:

import [Link].*;
import [Link].*;
import [Link].*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
// Specify FlowLayout for the layout
manager. [Link](new FlowLayout());
[Link](220, 90); // Give the frame an initial size.
// Terminate the program when the user closes the
application.
[Link](JFrame.EXIT_ON_CLOSE);
JButton jbtnAlpha = new JButton("Alpha"); // Button Alpha
JButton jbtnBeta = new JButton("Beta"); // Button Beta
// Add action listener for Alpha.
[Link]( new
ActionListener() {
public void actionPerformed(ActionEvent ae)
{ [Link]("Alpha was pressed."); }}
);

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

// Add action listener for Beta. public static void main(String args[]) {
[Link](new ActionListener() { // Create the frame on the event dispatching
public void actionPerformed(ActionEvent ae) { thread.
[Link]("Beta was pressed."); [Link](new Runnable()
} { public void run() {
}); new EventDemo();
}
// Add the buttons to the content });
pane. [Link](jbtnAlpha); }
[Link](jbtnBeta); }

// Create a text-based label.


jlab = new JLabel("Press a button.");

// Add the label to the content


pane. [Link](jlab);

// Display the frame.


[Link](true);
}

Program explanation:
• The [Link] package is needed because it contains the FlowLayout class, which supports
the standard flow layout manager used to lay out components in a frame.
• JButton provides the addActionListener( ) method, which is used to add an action listener.
(JButton also provides removeActionListener( ) to remove a listener, but this method is not
used by the program.

Create a Swing Applet


• JApplet is a top-level container, it includes the various panes.
• This means that all components are added to JApplet’s content pane in the same way
that components are added to JFrame’s content pane.
Swing applets use the same four lifecycle methods:
• init( ), start( ), stop( ), and destroy( ). Of course, you need override only those methods
that are needed by your applet.
Note:
• Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet
will not normally override the paint( ) method.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

A simple Swing Applet Program

// A simple Swing-based applet // Make two buttons.


import [Link].*; jbtnAlpha = new JButton("Alpha");
import [Link].*; jbtnBeta = new JButton("Beta");
import [Link].*; // Add action listener for Alpha.
/* [Link](new
This HTML can be used to launch the applet: ActionListener() {
<object code="MySwingApplet" width=220 public void actionPerformed(ActionEvent le) {
height=90> [Link]("Alpha was pressed.");
</object> }
*/ });
public class MySwingApplet extends JApplet { // Add action listener for Beta.
JButton jbtnAlpha; [Link](new
JButton jbtnBeta; ActionListener() {
JLabel jlab; public void actionPerformed(ActionEvent le) {
// Initialize the applet. [Link]("Beta was pressed.");
public void init() { }
try { });
[Link](new Runnable () { // Add the buttons to the content pane.
public void run() { add(jbtnAlpha);
makeGUI(); // initialize the GUI add(jbtnBeta);
} // Create a text-based label.
}); jlab = new JLabel("Press a button.");
} catch(Exception exc) { // Add the label to the content pane.
[Link]("Can't create because of "+ exc); add(jlab);
} }
} }
// This applet does not need to override start(),
//stop(), or destroy().
private void makeGUI() {
// Set the applet to use flow layout.
setLayout(new FlowLayout());

Swing Applet Program Explanation:


• the init( ) method initializes the Swing components on the event dispatching thread by setting
up a call to makeGUI( ).
• Notice that this is accomplished through the use of invokeAndWait( ) rather than
invokeLater( ).
• Applets must use invokeAndWait( ) because the init( ) method must not return until the
entire initialization process has been completed.
• In essence, the start( ) method cannot be called until after initialization, which means that
the GUI must be fully constructed.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

12. NETWORKING:
INTRODUCTION TO NETWORKING.

One of the most important reasons that Java is the premier language for network programming are the
classes defined in the [Link] package.

They provide an easy-to-use means by which programmers of all skill levels can access
network resources.

It is important to emphasize that networking is a very large and at times complicated topic.

NEWORKING BASICS:

At the core of Java’s networking support is the concept of a socket.

A socket identifies an endpoint in a network.

A server process is said to “listen” to a port until a client connects to it.


A server is allowed to accept multiple clients connected to the same port number, although each session is
unique.

Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing
protocol that breaks data into small packets and sends them to an address across a network,
which does not guarantee to deliver said packets to the destination.

Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary to reliably transmit data.

A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.

THE NETWORKING CLASSES & INTERFACES:



Java supports TCP/IP both by extending the already established stream I/O interface, by adding the
features required to build I/O objects across the network.

Java supports both the TCP and UDP protocol families.

TCP is used for reliable stream-based I/O across the network.

UDP supports a simpler, hence faster, point-to-point datagram-oriented model.

The classes contained in the [Link] package are shown here:


Authenticator Inet6Address ServerSocket
CacheRequest InetAddress Socket
CacheResponse InetSocketAddress SocketAddress

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

ContentHandler InterfaceAddress(AddedbyJavaSE6) SocketImpl


CookieHandler JarURLConnection SocketPermission
CookieManager (AddedbyJavaSE6.) MulticastSocket URI
DatagramPacket NetPermission URL
DatagramSocket NetworkInterface URLClassLoader
DatagramSocketImpl PasswordAuthentication URLConnection
HttpCookie (Added by Java SE 6.) Proxy URLDecoder
HttpURLConnection ProxySelector URLEncoder
IDN (Added by Java SE 6.) ResponseCache URLStreamHandler
Inet4Address SecureCacheResponse

The [Link] package’s interfaces are listed here:


ContentHandlerFactory DatagramSocketImplFactory SocketOptions
CookiePolicy(Added by JavaSE6.) FileNameMap URLStreamHandlerFactory
CookieStore(Added by JavaSE 6.) SocketImplFactory

InetAddress:

The InetAddress class is used to encapsulate both the numerical IP address and the domainname for
that address.

You interact with this class by using the name of an IP host, which is more convenient and understandable
than its IP address.

The InetAddress class hides thenumber inside. InetAddress can handle both IPv4 and IPv6 addresses.

Two methods of InetAddress


a)Factory method b)Instance method

Factory Methods:

The InetAddress class has no visible constructors.

To create an InetAddress object, you have to use one of the available factory methods. Factory
methods are merely a convention whereby static methods in a class return an instance of that
class.

Three commonly used InetAddress factory methods are shown here:


1) static InetAddress getLocalHost( ) throws UnknownHostException

2) static InetAddress getByName(String hostName) throws UnknownHostException


3)static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur


The getLocalHost( ) method simply returns the InetAddress object that represents the localhost.

The getByName( ) method returns an InetAddress for a host name passed to it. If thesemethods are unable to
resolve the host name, they throw an UnknownHostException.

The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that
a particular name resolves to. It will also throw an
UnknownHostException

InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an
InetAddress object. Either an IPv4 or an IPv6 address can be used.
// Demonstrate InetAddress.
import [Link].*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{ InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}

Here is the output produced by this program.


default/[Link]
[Link]/[Link]

Instance Methods:

The InetAddress class also has several other methods, which can be used on the objects returned by the
methods just discussed. Here are some of the most commonly used methods.
boolean equals(Object other) Returns true if this object has the same Internet address as other.

byte[ ] getAddress( ) Returns a byte array that represents the object’s IP address in
network byte order.
String getHostAddress( ) Returns a string that represents the host address associated with
the InetAddress object.
String getHostName( ) Returns a string that represents the host name associated with
the InetAddress object.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

boolean isMulticastAddress( ) Returns true if this address is a multicast address. otherwise it


returns false.

String toString( ) Returns a string that lists the host name and the IP address for
convenience.

TCP/IP CLIENT SOCKETS.



TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point,stream-based connections
between hosts on the Internet.

A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine
or on any other machine on the Internet.

There are two kinds of TCP/IP sockets in Java:


a) One is for servers
b) The other is for clients.

The ServerSocket class is designed to be a “listener,” which waits for clients toconnect before doing
anything. Thus, ServerSocket is for servers.

The Socket class is for clients. It is designed to connect to server sockets and initiate protocol
exchanges. Because client sockets are the most commonly used by Java applications, they are
examined here.

The creation of a Socket object implicitly establishes a connection between the client and server.

There are no methods or constructors that explicitly expose the details of

establishing that connection. Here are two constructors used to create client sockets:

Socket(String hostName, int port) Creates a socket connected to the named host
throws UnknownHostException,IOException and port.

Socket(InetAddress ipAddress, int port Creates a socket using a preexisting


)throws IOException InetAddress object and a port.

Socket defines several instance methods. For example, a Socket can be examined at any time for the
address and port information associated with it, by use of the following methods:
InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket
object. It returns null if the socket is not connected
int getPort( ) Returns the remote port to which the invoking Socket object is
connected. It returns 0 if the socket is not connected.
int getLocalPort( ) Returns the local port to which the invoking Socket object is
bound. It returns –1 if the socket is not bound

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here.
Each can throw an IOException if the socket has been invalidated by a loss of connection.
InputStream getInputStream( ) Returns the InputStream associated with the
throws IOException. invoking socket.
OutputStream getOutputStream( ) Returns the OutputStream associated with
throws IOException. The invoking socket.

Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ), which
returns true if the socket is bound to an address; and isClosed( ), which returns true if the socket is
closed.

URL:

The World Wide Web. The Web is a loose collection of higher-level protocols and file formats, all
unified in a web browser.

One of the most important aspects of the Web is that Tim Berners-Lee devised a scaleable way to locate all
of the resources of the Net.

Once you can reliably name anything and everything, it becomes a very powerful paradigm. The Uniform
Resource Locator (URL) does exactly that.

The URL provides a reasonably intelligible form to uniquely identify or address information on the Internet.


URLs are ubiquitous; every browser uses them to identify information on the Web. Within
Java’s network class library, the URL class provides a simple, concise API to access
information across the Internet using URLs.
All URLs share the same basic format, although some variation is allowed.
Here are twoexamples:
[Link] and
[Link]

A URL specification is based on four components.



The first is the protocol to use, separated from the rest of the locator by a colon
(:).Common protocols are HTTP, FTP, gopher, and file, although these days almost
everything is being done via HTTP (in fact, most browsers will proceed correctly if you
leave off the “[Link] from your URL specification).

The second component is the host name or IP address of the host to use; this is delimited on the left by double
slashes (//) and on the right by a slash (/) or optionally a colon (:).

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur


The third component, the port number, is an optional parameter, delimited on the left from the host name by a
colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined
HTTP port; thus, “:80” is redundant.) .

The fourth part is the actual file path. Most HTTP servers will append a file named
[Link] or [Link] to URLs that refer directly to a directory resource. Thus,
[Link] is the same as
[Link]
Java’s URL class has several constructors; each can throw a MalformedURLException.
One commonly used form specifies the URL with a string that is identical to what you see displayed in
a browser:
URL(String urlSpecifier) throws MalformedURLException
The next two forms of the constructor allow you to break up the URL into its component parts:

URL(String protocolName, String hostName, int port, String path)
throws MalformedURLException

URL(String protocolName, String hostName, String path)
o throws MalformedURLException
Another frequently used constructor allows you to use an existing URL as a reference context and then
create a new URL from that context. Although this sounds a little contorted, it’s really quite easy and
useful.

URL(URL urlObj, String urlSpecifier) throws MalformedURLException.
The following example creates a URL to Osborne’s download page and then examines its properties:
// Demonstrate URL.
import [Link].*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("[Link] " +
[Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Ext:" + [Link]());
}}

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur
When you run this, you will get the following output:
Protocol: http
Port: -1
Host: [Link]
File: /downloads
Ext:http:/ /[Link]/downloads

URLConnection:

URLConnection is a general-purpose class for accessing the attributes of a remote resource.

Once you make a connection to a remote server, you can use URLConnection to inspect the properties of the
remote object before actually transporting it locally.

These attributes are exposed by the HTTP protocol specification and, as such, only make sense for URL
objects that are using the HTTP protocol.
URLConnection defines several methods. Here is a sampling:
int getContentLength( ) Returns the size in bytes of the content associated with the
resource. If the length is unavailable, –1 is returned.

String getContentType( ) Returns the type of content found in the [Link] is the
value of the content-type header [Link] null if the
content type is not available
long getDate( ) Returns the time and date of the response represented in
terms of milliseconds sinceJanuary 1, 1970 GMT.

long getExpiration( ) Returns the expiration time and date of the resource
represented in terms of milliseconds since January 1, 1970
GMT. Zero is returned if the expiration date is unavailable
String getHeaderField(intidx) Returns the value of the header field at index idx. (Header
field indexes begin at 0.) Returns null if the value of idx
exceeds the number of fields.
String getHeaderField(String Returns the value of header field whose name is specified
fieldName by fieldName. Returns null if the specified name is not
found.
String getHeaderFieldKey(intidx) Returns the header field key at index idx. (Header field
indexes begin at 0.) Returns null if the value of idx exceeds
the number of fields.

Map<String, List<String>> Returns a map that contains all of the header fields and
getHeaderFields( ) values.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

long getLastModified( ) Returns the time and date, represented in terms of


milliseconds since January 1, 1970 GMT, of the last
modification of the resource. Zero is returned if the last-
modified date is unavailable.

InputStream getInputStream( ) Returns an InputStream that is linked to the resource. This


throws IOException stream can be used to obtain the content of the resource

HttpURLConnection.

Java provides a subclass of URLConnection that provides support for HTTP connections.

This class is called HttpURLConnection.

You obtain an HttpURLConnection in the same way just shown, by calling
openConnection( ) on a URL object, but you must cast the result to
HttpURLConnection. (Of course, you must make sure that you are actually opening an
HTTP connection.) Once you have obtained a reference to an HttpURLConnection
object,you can use any of the methods inherited from URLConnection.

You can also use any of the several methods defined by HttpURLConnection.

Here is a sampling:
static boolean getFollowRedirects( ) Returns true if redirects are automatically followed and
false otherwise. This feature is on by default.
String getRequestMethod( ) Returns a string representing how URL requests are
made. The default is GET. Other options, such as POST,
are available.
String getResponseMessage() Returns the response message associated with the
throws IOException response code. Returns null if no message is available.
An IOException is thrown if the connection fails.
static void setFollowRedirects If how is true, then redirects are automatically followed.
(boolean how) If how is false, redirects are not automatically followed.
By default, redirects are automatically
void setRequestMethod Sets the method by which HTTP requests are made to
(String how) that specified by how. The default method is GET, but
throws ProtocolException other options, such as POST, are available. If how is
invalid, a ProtocolException is thrown

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The URI Class



Arelatively recent addition to Java is the URI class, which encapsulates a Uniform
ResourceIdentifier (URI). URIs are similar to URLs. 

In fact, URLs constitute a subset of URIs. AURI represents a standard way to identify a resource. AURL
also describes how to access the resource.

Cookies:

The [Link] package includes classes and interfaces that help manage cookies and can be used to create a
stateful (as opposed to stateless) HTTP session.

The classes are CookieHandler, CookieManager, and HttpCookie. The interfaces are CookiePolicy
and CookieStore.

TCP/IP Server Sockets:



Java has a different socket class that must be used for creating server applications.

The ServerSocket class is used to create servers that listen for either local or

remote client programs to connect to them on published ports.


ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will register itself
withthe system as having an interest in client connections.

The constructors for ServerSocket reflect the port number that you want to accept connections on
and, optionally, how long you want the queue for said port to be.

The queue length tells the system how many client connections it can leave pending before it should simply
refuse connections.

The default is 50. The constructors might throw an IOException under adverse conditions.

Here are three of its constructors:


ServerSocket(int port) throws Creates server socket on the specified port
IOException with a queue length of 50.
ServerSocket(int port, int Creates a server socket on the specified port
maxQueue) with a maximum queue lengt
throws IOException
ServerSocket(int port, int Creates a server socket on the specified port
maxQueue, with a maximum queue length of maxQueue.
InetAddress localAddress) On a multihomed host, localAddress specifies
throws IOException the IP address to which this socket binds.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

ServerSocket has a method called accept( ), which is a blocking call that will wait for a
client to initiate communications and then return with a normal Socket that is then used for
communication with the client.

Inet4Address and Inet6Address.



Java has included support for IPv6 addresses. Because of this, two
subclasses of InetAddress were created: Inet4Address and Inet6Address.

Inet4Address represents a traditional-style IPv4 address.

Inet6Address encapsulates a new-style IPv6 address. Because they are subclasses of InetAddress,
an InetAddress reference can refer to either.

This is one way that Java was able to add IPv6 functionality without
breaking existing code or adding many more classes

For the most part, you can simply use InetAddress when working with IP addresses because it can accommodate
both styles.

Remote Method Invocation (RMI):



Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a method
of a Java object that executes on another machine.

This is an important feature, because it allows you to build distributed applications.

A Simple Client/Server Application Using RMI


This section provides step-by-step directions for building a simple client/server application by using
RMI.
The server receives a request from a client, processes it, and returns a result.

Step One: Enter and Compile the Source Code.


This application uses four source files.

The first file, [Link], defines the remote interface that is provided
by the server.

It contains one method that accepts two double arguments and returns their sum.

All remote interfaces must extend the Remote interface, which is part of
[Link]. Remote defines no members.

Its purpose is simply to indicate that an interface uses remote methods.

All remote methods can throw a RemoteException.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

The second source file, [Link], implements the remote interface.



Theimplementation of the add( ) method is straightforward.

All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make
objects available from remote machines.

The third source file, [Link], contains the main program for the server machine.

Its primary function is to update the RMI registry on that machine.

This is done by using the rebind( ) method of the Naming class (found in [Link]).

That method associates a name with an object reference.

The first argument to the rebind( ) method is a string that names the server as “AddServer”.

Its second argument is a reference to an instance of AddServerImpl.

The fourth source file, [Link], implements the client side of this distributed
application.

[Link] requires three command-line arguments.

The first is the IP address or name of the server machine.

The second and third arguments are the two numbers that are to be summed.

Step Two: Generate a Stub



In the context of RMI, a stub is a Java object that resides on the client machine.

Its function is to present the same interfaces as the remote server.

Remote method calls initiated by the client are actually directed to the stub.


The stub works with the other parts of the RMI system to formulate a request that is sent to the remote
machine.

A remote method may accept arguments that are simple types or objects. In the latter case, the object may have
references to other objects.

All of this information must be sent to the remote machine. That is, an object passed as an argument to a
remote method call must be serialized and sent to the remote machine.

If a response must be returned to the client, the process works in reverse. Note that the serialization and
deserialization facilities are also used if objects are returned to a client.

To generate a stub, you use a tool called the RMI compiler, which is invoked from the command line,
as shown here:
rmic AddServerImpl

This command generates the file AddServerImpl_Stub.class. When using rmic, be sure that CLASSPATH is
set to include the current directory.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

Step Three: Install Files on the Client and Server Machines.



Copy [Link], AddServerImpl_Stub.class, and [Link] to a directory on the client
machine.

Copy [Link], [Link], AddServerImpl_Stub.class, and
[Link] to a directory on the server machine.

Step Four: Start the RMI Registry on the Server Machine.



Java SE 6 provides a program called rmiregistry, which executes on the server machine.

It maps names to object references. First, check that the CLASSPATH environment variable includes the
directory in which your files are located.

Then, start the RMI Registry from the command line, as shown here:
start rmiregistry
When this command returns, you should see that a new window has been created. You need to leave
this window open until you are done experimenting with the RMI example

.Step Five: Start the Server.



The server code is started from the command line, as shown here:
java AddServer

Recall that the AddServer code instantiates AddServerImpl and registers that object with the name
“AddServer”.

Step Six: Start the Client.



The AddClient software requires three arguments: the name or IP address of the
server machine and the two numbers that are to be summed together.

You may invoke it from the command line by using one of the two formats shown here:
java AddClient server1 8 9 java
AddClient [Link] 8 9

In the first line, the name of the server is provided. The second line uses its IP address ([Link]).

Datagrams.

TCP/IP-style networking is appropriate for most networking needs.

It provides a serialized,predictable, reliable stream of packet data.

 Datagrams provide an alternative. Datagrams are bundles of information passed between machines.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur


Once the datagram has been released to its intended target, there is no assurance that it will arrive or even
that someone will be there to catch it.

Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that
whoever sent it is still there to receive a response.

Java implements datagrams on top of the UDP protocol by using two classes: the

DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or
receive the DatagramPackets.

DatagramSocket:
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException


The first creates a DatagramSocket bound to any unused port on the local computer.

The second creates a DatagramSocket bound to the port specified by port.

The third constructs a DatagramSocket bound to the specified port and InetAddress.


The fourth constructs a DatagramSocket bound to the specified SocketAddress.
SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress.

InetSocketAddress encapsulates an IP address with a port number.

All can throw a SocketException if an erroroccurs while creating the socket.

DatagramSocket defines many methods.


Two of the most important are send( ) and receive( ), which are shown
here: void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException

 The send( ) method sends packet to the port specified by packet.



The receive method waits for a packet to be received from the port specified by packet and returns the result.
 Other methods give you access to various attributes associated with a DatagramSocket.

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

InetAddress getInetAddress( ) If the socket is connected, then the address is [Link],


null is returned.
int getLocalPort( ) Returns the number of the local port.
int getPort( ) Returns the number of the port to which the socket isconnected. It
returns –1 if the socket is not connected to a port.
boolean isBound( ) Returns true if the socket is bound to an address. Returns false
otherwise.
boolean isConnected( ) Returns true if the socket is connected to a server. Returns false
otherwise.
void setSoTimeout(int millis) throws Sets the time-out period to the number of milliseconds passed in
SocketException millis.

DatagramPacket.
DatagramPacket defines several constructors. Four are shown here:

DatagramPacket(byte data[ ], int size)


DatagramPacket(byte data[ ], int offset, int size)
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)


The first constructor specifies a buffer that will receive data and the size of a packet. It
is used for receiving data over a DatagramSocket.

The second form allows you to specify an offset into the buffer at which data will be stored.

The third form specifies a target address and port, which are used by a DatagramSocket to determine where
the data in the packet will be sent.

The fourth form transmits packets beginning at the specified offset into thedata.

Think of the first two forms as building an “in box,” and the second two forms
as stuffing and addressing an envelope.
DatagramPacket defines several methods, including those shown here.
InetAddress getAddress( ) Returns the address of the source (for datagrams being
received) or destination (for datagrams being sent).
byte[ ] getData( ) Returns the byte array of data contained in the
datagram. Mostly used to retrieve data from the
datagram after it has been received.
int getLength( ) Returns the length of the valid data contained in the
byte array that would be returned from the getData( )

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

method. This may not equal the length of the whole


byte array.
int getOffset( ) Returns the starting index of the data.
int getPort( ) Returns the port number.
void setAddress(InetAddress ipAddress Sets the address to which a packet will be sent. The
address is specified by ipAddress.
void setData(byte[ ] data) Sets the data to data, the offset to zero, and the length
to number of bytes in data.
void setData(byte[ ] data, int idx, int size) Sets the data to data, the offset to idx, and the length to
size.
void setLength(int size) Sets the length of the packet to size.
void setPort(int port) Sets the port to port.

A Datagram Example:
The following example implements a very simple networked communications client and server.
Messages are typed into the window at the server and written across the network to the client side,
where they are displayed.
/ Demonstrate datagrams.
import [Link].*; class
WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new
byte[buffer_size]; public static void TheServer()
throws Exception { int pos=0;
while (true) {
int c = [Link]();
switch (c) {
case -1:
[Link]("Server
Quits."); return;
case '\r':
break;
case '\n':
[Link](new DatagramPacket(buffer,pos,
[Link](),clientPort));
pos=0;

[Link] Institute of Technology-560056


Core Java(IS52) Satish B Basapur

break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer,
[Link]); [Link](p);
[Link](new String([Link](), 0, [Link]()));
}
}
public static void main(String args[]) throws Exception
{ if([Link] == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}

This sample program is restricted by the DatagramSocket constructor to running between


two ports on the local machine. To use the program, run

java WriteServer
in one window; this will be the client. Then
run java WriteServer 1

This will be the server. Anything that is typed in the server window will be sent to the
client window after a newline is received.

[Link] Institute of Technology-560056

You might also like