Você está na página 1de 129

1.

OBJECT ORIENTED PROGRAMMING


Object oriented programming is an approach for programming organization and
development.

OOP allows us to decompose a problem into a number of entities called

objects and then build Data and Methods around these entities.
The Combination of Data and Methods make up an object.
OBJECT = DATA + METHODS

Features of Object Oriented approach are:

Emphasis is on the DATA rather than PROCEDURE.

Programs are devided into objects

Data Structures are designed such that they characterize the objects.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through methods

New Data and Methods can be easily added.

It follows BOTTOM UP PROGRAM design.

Benefits of OOPs

Through inheritance we can eliminate redundant code and extend the use of existing
classes.

The principle of the Data Hiding helps the programmer to build secure programs that
cannot be accessed by other programs

Software complexity

It is possible to have multiple objects

Applications of OOPs

Real time systems and in Simulation and modeling.

Hyper text.

Artificial Intelligence(AI) Systems.

CAD System.

Object Oriented Databases.

Office Automation Systems.

1|OOPS Through Java- GRK

OOP is a new way of organizing code and data that gives increased control over the
complexity of software development process.

OOP is only a method of designing and

implementing software. OOP has nothing to do with any programming language. A


programming language that supports OOP makes it easier to implement the Object Oriented
techniques.
There are three basic concepts underlying OOPS

DATA ABSTRACTION AND ENCAPSULATION

INHERITENCE

POLYMORPHISM

DATA ABSTRACTION
Abstraction refers to the act of representing essential features without including the
background details or explanation.

The process of defining a data type, often called an

abstract data type (ADT), together with the principle of data hiding is called data abstraction.
The term Abstract Data Type refers to a programmer defined Data type together with a
set of operations that can be performed on that data.
ENCAPSULATION
The wrapping up of the data and methods into a single unit is known as Encapsulation.
The data is not accessible to the outside world and only those methods which are wrapped in
the classes can access it. These methods provide the interface between the objects data and
the program. This insulation of the data from direct access by the program is called Data
Hiding. It deals with
OBJECTS
OBJECTS :

CLASSES

DATA

Objects are the basic runtime entities in an Object Oriented system. It is an

entity which contains related set of Data Fields of a class to which contains related set of Data
Fields of a class to which it is referring. It is a variable to store data.
PERSON
NAME
BASIC PAY
SALARY()
TAX()
Representation of an object

2|OOPS Through Java- GRK

Class : A class is a collection of members. The entire set of data and code of an object can
be made as user defined data type using the concept of a class. Once a class has been
defined, we can create any number of objects belonging to that class.
Classes are user defined data types and behave like the built-in types of Programming
Language.

Ex: Mango, Apple and Orange are objects of class Fruits

Data :

Both methods and variables in an object are known as Data.

Methods:

Method is a group of statements that perform some action within an object and
also operate on an object.

INHERITANCE:
Inheritance is the process by which objects of one class acquires the properties of
objects of another class. It is the process of defining a new object in terms of an old one. It
imposes a hierarchical relationship among classes in which a child class inherits from its
parent.
The parent class is known as base class and the child class is the derived class.

The

concept of deriving a class from more than one base class is called multiple inheritance.
POLYMORPHISM:
The quality of having more than one form. It refers to the fact that a single operation
can have different behavior in different objects.

Ex 1: Shape Draw()
Circle Object
Box Object
Draw(Circle)
Draw(Box)

Triangle Object
Draw(Triangle)

Hexagon Object
Draw(Hexagon)

Ex 2:

+
+

Addition of two Integers


Concatenation of two strings

Dynamic Binding:
Binding refers to the linkage of procedure call to the code to be executed in response
to the call.

Dynamic binding means that the code associated with a given procedure call is

not known until the time of the call at runtime.


Inheritance.

3|OOPS Through Java- GRK

It is associated with Polymorphism and

2. INTRODUCTION TO JAVA

Simple
Object Oriented
Secured
Portable
Multithreaded

Distributed
High Performance

Interpreted

Java was developed by a team led by James Gosling at Sum Microsystems. Most of the
Programming Languages are either compiled or interpreted. But Java is both compiled and
interpreted. Java is characterized by the following features.
SIMPLE:

Java is a simple language. It contains an extensive set of library routines and

predefined classes.
OBJECT ORIENTED: Java allows us to focus on the data. Objects are defined by using
classes in Java. The process of creating an object of the class is called instantiation. Classes
are arranged in a hierarchy so that a child class can inherit properties and behaviors from its
parent class.
DISTRIBUTED :

It is designed to support applications on network. Java contains an

extensive library of routines for handling TCP/IP protocols including FTP and HTTP.
INTERPRETED :

when we compile java source code, it generates Java Byte code instead

of native machine code as with most compilers. Java source code is device independent. It
runs on any machine that has a java interpreter.
SECURE:

Java is used in a networked and distributed environment when java

applications are invoked applets cannot read or write local files without the user knowledge
and permission.
PORTABLE: The Java compiler is written in java with the java runtime system written in
ANSI C to ensure the highest level of portability. It is portable to new hardware and operating
system.
HIGH PERFORMANCE:

Java performs well and meets the requirements for the most

applications. The speed is more than adequate for most interactive applications.
MULTITHREADED:

Java is capable of performing more than one task at a time.

Multithreading is particularly useful in graphical user interface (GUI) and network


programming.

A java application can play a sound file, while prompting the user for input. It

improves real-tune behavior of the application.

4|OOPS Through Java- GRK

ARCHITECTURE NEUTRAL:The java application source code is converted into code that can
be run on multiple platforms. It saves development time. We can run java on any platform
with a Java Virtual Machine (JVM).
DYNAMIC:

Java was designed to adopt to an evolving environment. We can freely add

new methods and properties in a class without affecting their clients.


JAVA AND C

Java does not include the C unique statement keywords goto, sizeof and typedef

Java does not contain the data types struct, union and enum.

Java does not define the type modifiers keywords auto, register, signed and unsigned.

Java does not support an explicit pointer type.

Java does not have a preprocessor and therefore we cannot use #define, #include and
#ifdef statements.

Java does not support any mechanism for defining variable arguments to function.

Java adds new operators such as instanceof and >>>

Java adds labeled break and continue statements.

Java requires that the functions with no arguments must be declares with empty
parenthesis and not with the void keyword as done in C.

JAVA AND C++

Java does not support operator overloading

Java does not have template classes as in C++.

Java does not support multiple inheritance of classes. This is accomplished using a
new feature called interface.

Java does not support global variables. Every variable and method is declared within
a class and forms part of that class.

Java does not use pointers.

There are no headers files in Java.

Java has replaced the destructor function with a finalize() function.

5|OOPS Through Java- GRK

JAVA APPLICATIONS AND APPLETS


Java programs are of two types.
1. APPLICATIONS

2. APPLETS

Applications are stand alone programs written using high-level languages. They can
be executed from any computer with a java interpreter and are ideal for developing software.
Every Java Program must have at least one class. The class contains a method called main()

JAVA PROGRAM STRUCTURE

Documentation Section

Suggestible

Package Statement

Optional

Import Statements

Optional

Interface Statements

Optional

Class Definitions

Optional

Main Method Class


{

Essential
main method definition

Documentation Section:
It comprises a set of comment lines giving the name of the program and other
details.Java uses three styles of comments
//

Single Line Comments

6|OOPS Through Java- GRK

/* ..*/

Multi Line Comments

/** ..*/

Documentation Comment

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.

Ex : package student ;

A first simple program:


/* This is a simple java program */

class example
{
public static void main(String args[ ])
{
System.out.println(Welcome to Java Programming );
}
}

Import Statements:
The next thing after a package statement may be a number of import statements. It is
similar to # include statements in C.
Ex : import student.test ;
This statement instructs the interpreter to load the test class contained in the package
student.

Using import statements, we can have access to classes that are part of other

packages.
Interface Statements :
An interface is like a class but includes a group of method declarations. It is used only
when we wish to implement the multiple inheritance feature in the program.
Class Definitions :
A java program may contain multiple class definitions. Classes are the primary and
essential elements of a java program.
Main Method Class :
Since every java stand alone program requires a main method to start its execution,
this class is essential part of a java program.
The main method creates objects of various classes and establishes communications
between them. The name of the file must be the name of the class with
Java is case sensitive language.

7|OOPS Through Java- GRK

.class extension.

JAVA TOKENS
A Java Program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Smallest individual
units in a program are known as tokens.
In simple terms, a java program is a collection of tokens, comments and white spaces.
Java Language includes five types of tokens. They are :

Reserved Keywords

Identifiers

Literals

Operators

Separators

Java Character Set :


The smallest units of java language are the characters used to write java tokens.
These characters are defined by the Unicode Character Set . The Unicode is a 16-bit
character coding system and currently supports more than 34,000 derived from 24 languages.
We mostly use ASCII character set.

KEYWORDS :
Java language has reserved 60 words as keywords. Since keywords have specific
meaning in java, we cannot use them as names of variables, classes, methods and so on
All keywords are to be written in lower case letters.

abstract
int
continue
public
default
void
native
volatile
new

case
protected
extends
super
import
byte
package
class
private

else
static
for
throw
long
char
return
double
short

float
try
implements
break
switch
do
synchronized
finally
this

The following are the VALUES defined by java


null
false
true

8|OOPS Through Java- GRK

if
Boolean
interface
catch
throws
final
transient
instanceof
while

IDENTIFIERS :
Identifiers are programmer designed tokens.

They are used for naming classes,

methods, variables, objects, packages and interfaces in a program.

They follow the following rules :

They can have alphabets, digits, underscore( _ ) and Dollar sign ($) characters.

They must not begin with a digit.

Uppercase and lowercase letters are distinct as java is case sensitive language.

They can be of any length.

It should not be a keyword.

White space is not allowed within a variable.

A variable for a data type name cannot be used for another data type.

A variable can be declared only once.

Variable names can be of any length.

VARIABLE
A variable is an identifier that denotes a storage location used to store a data value. The
value of a variable may change during the execution of the program.

Java developers have followed some naming conventions :

Names of all public methods and instance variables start with a leading lowercase
letter. Ex: average( ), sum( )

When more than one word are used in a name, the second and subsequent words are
marked with a Uppercase letters.

Ex: totalMarks( )

All private and local variables use only lower case letters. Ex: length

All Classes and Interfaces start with a leading uppercase letter.

Ex:

Student, HelloJava

Variables that represent constant values use all uppercase letters and underscores
between word.

Ex: TOTAL,

MAX_AMOUNT

CONSTANTS :
Literals in java are a sequence of characters (digits, letters and other characters) that
represent constant values to be stored in variables.

9|OOPS Through Java- GRK

Java language specifies five major types of literals. They are


1. Integer Constants
2. Floating point Constants
3. Character Constants
4. String Constants
5. Boolean Constants
Constants refer to fixed values that do not change during the execution of a program.
INTEGER CONSTANTS
An Integer constant refers to a sequence of digits. There are three types of integers namely :
Decimal Integer

0 to 9

JAVA CONSTANTS

Ex : 123, 345, -89, 0


Octal Integer
NUMERIC CONSTANTS

CHARACTER CONSTANTS

0 to 7

Ex : 0123, 0345, -089


Hexadecimal Integer
0 to 9,A,B,C,D,E,F

INTEGER
CONSTANTS

REAL
CONSTANTS

CHARACTER
CONSTANTS

STRING
CONSTANTS

Ex : 0X12A, 0x3E5, -0xBF89


A sequence of digits preceded

by Ox or OX is considered as hexa decimal integer. They may also include alphabets A


through F. These letters A through F represents the numbers 10 to 15.
Real constants
The numbers that are represented by fractional part are called Real or Floating point
Constants.

These numbers are shown in decimal notation, having a whole number followed

by a decimal point and the Fractional part, which is an integer.

Ex: 0.002354, 12.0365

A real number may also be expressed in exponential notation.


Ex:

215 X 10 23

215E23 or 215e23

215 X 10 -23

215-E23 or 215e-23

The General form for Exponential representations is

Mantissa e Exponent

Or

10 | O O P S T h r o u g h J a v a - G R K

Mantissa E Exponent

The Mantissa portion may be expressed in Decimal notation or Floating Point notation. But
the exponent is an integer with an optional plus or minus sign.
Ex: 0.065e4,

12e-5

Single character constant


Single character constant contains a single enclosed within a pair of single quote marks. Ex:
x , X , 5 , 1 , & , $ , _
Java supports some special backslash character constants that are used in output methods.
Some of them are -- \b

\r

blank space

\t

tab

\n

new line

single quote

Double quote

\f

form feed

carriage return

\\

back slash

These character constants are known as escape sequences.


String constant :
A string constant is a sequence of characters enclosed between double quotes.

The

characters may be alphabets, digits, special characters and blank spaces.


Ex: Hello Java , 2008

OPERATORS :
An operator is a symbol that takes one or more arguments and operates on them to
produce a result.
An Operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations. Java operators can be classified into :

Arithmetic Operators

Relational Operators

<

<=

> >= ==

Logical Operators

||

&&

Assignment Operators

+=

-=

Increment or Decrement Operators ++

--

Conditional Operators

? :

Bitwise Operators

&

11 | O O P S T h r o u g h J a v a - G R K

/ %
!=

*=

/=

%=

<<

>> >>>

Special Operators

instanceof

(.)

ARITHEMATIC OPERATORS :
Integer Arithmetic :

When both the operands in a single Arithmetic expression are integers,

the expression is called an integer expression. Integer Arithmetic always yields an integer
value. For modulo division, the sign of the result is always the sign of the first operand. Ex :
-17 % 3 = -2

-17 % -3 = -2

17 % -3 = 2

17 % 3 = 2

Real Arithmetic :

It involves only real operations

a/b (decimal truncated)

Mixed Mode Arithmetic: When one of the operands is real and the other is integer, the
expression is called mixed-mode arithmetic expression.
If either operand is of the real type, then the other operand is converted to real and
real arithmetic is performed. The result will be a real.
Ex :

12/10.0

1.2

12/10

Conditional Operators: The character pair ? : is a ternary operator available in java.


Expression1? Statement1 : Statement2
Ex :
Special Operators:
instanceof:

x=(a>b) ? a : b ;

Java supports special operators such as instanceof and ( . )

This operator allows us to determine whether the object belongs to a particular

class or not.
Dot Operator:

a=15; b=56;

Ex:

s1 instanceof student;

The ( . ) Operator is used to access the instance methods and variables of a

class object.

Ex:

s1.name

s1.display( )

ARITHEMATIC EXPRESSIONS :
An arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of the language. Expressions are evaluated using an assignment
statement.
Variable=expression;
Precedence of Arithmetic Operators:

Ex: x=a*b+c;
An arithmetic expression without any parenthesis

will be evaluated from left to right using the rules of precedence.


High Priority

* / %

Low Priority

OPERATOR PRECEDENCE MAP

12 | O O P S T h r o u g h J a v a - G R K

+-

Operator

Description

Associativity Rank

Member Selection

Left to right

()

Function call

[]

Array element reference

Operator

Description

Associativity Rank

Unary minus

Right to left

++

Increment

--

Decrement

Logical negation

Ones Complement

(type)

Casting

Multiplication

Left to right

Division

Modulus

Addition

Left to right

Substraction

<<

Left shift

Left to right

>>

Right shift

>>>

Right shift with zero fill

<

Less than

Left to right

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

13 | O O P S T h r o u g h J a v a - G R K

instanceof Type comparison


==

Equality

Left to right

!=

Inequality

&

Bitwise AND

Left to right

Bitwise XOR

Left to right

Bitwise OR

Left to right

10

&&

Logical AND

Left to right

11

||

Logical OR

Left to right

12

?:

Conditional operator

Left to right

13

Assignment operators

Right to left

14

op =

Shorthand assignment

Right to left

15

SEPARATORS :
Separators are symbols used to indicate where groups of code are divided and
arranged.
Parentheses( )-

Used to enclose parameters in method definition.

Braces { }

Define a block of code of classes, methods and local scopes.

Brackets [ ]

Used to declare array types

Semicolon ;

Used separate statements

Period .

Used to separate package names from sub packages and classes.

14 | O O P S T h r o u g h J a v a - G R K

JAVA STATEMENTS
A statement is an executable combination of tokens ending with a semicolor( ; ) mark.
Statements are usually executed in sequence in the order in which they appear.
Java implements several types of statements
Expression Statement:
Java has seven types of expression statements; Assignment, Pre-Increment, PostIncrement, Pre-Decrement, Post-Decrement, Method call and Allocation
Expressions.
JAVA STATEMENTS

EXPRESSION
STATEMENTS

LABELLED
STATEMENTS
SELECTION
STATEMENTS

CONTRONL
STATEMENTS
ITERATION
STATEMENTS

SYNCHRONIZATION

GUARDING
STATEMENTS

STATEMENTS

JUMP
STATEMENTS

IF

WHILE

BREAK

IF ELSE

DO

CONTINUE

SWITCH CASE

FOR

RETURN

Labelled Statements:
These are used for handling issues with multithreading.
Guarding Statements:
They are used for safe handling of code that may cause exceptions. The statements
use the keywords try, catch and finally.
Selection Statements:
These select one of several control follows.
Iteration Statements:
These specify how and when looping will take place.
Jump Statements:
They pass control to the beginning or end of the current block, or to a labeled
statement.

15 | O O P S T h r o u g h J a v a - G R K

DATA TYPES
Data Types specify the size and type of values that can be stored.

INTEGER TYPES:
Java supports four types of integers. Java does not support the concept of unsigned
types.

byte

1 byte

short

2 bytes

int

4 bytes

long

8 bytes

FLOATING POINT TYPES:


It holds numbers containing fractional parts.

float

4 bytes

double

8 bytes

Floating point numbers are treated as double precision quantities. To force them to be
in single precision mode, we must append f or F to the numbers.
Ex: 1.23 f, 7.125e6F

CHARACTER TYPES:
Java provides a a character data type called char. It assumes a size of 2 bytes.
Hence it supports more than 65000 characters (2
set.

char

2 bytes

16 | O O P S T h r o u g h J a v a - G R K

16

) which is known as UNICODE character

DATA TYPES

NONPRIMITIVE (DERIVED)

PRIMITIVE (INTRINSIC)

NUMERIC

INTEGER
TYPES

CLASSES

NON NUMERIC
TYPES

FLOATING POINT

CHARACTER
TYPES

INTERFACES

ARRAYS

BOOLEAN

BOOLEAN TYPE:
It is used to test a particular condition during the execution of the program. It takes
only two values :

true

boolean

or

false

1 byte

DECLARATION OF VARIABLES:
Declaration does three things.

It tells the compiler what the variable name is.

It specifies what type of data the variable will hold.

The place of declaration decides the scope of the variable.

A variable must be declared before it is used in the program.


The general form of declaration of variable is :

type variable1, variable2, variable3,.;


Ex:

int x, y, z=10;
char c1,c2=A,c3;

GIVING VALUES TO VARIABLES:

17 | O O P S T h r o u g h J a v a - G R K

A variable must given a value after it has been declared but before it is used in an
expression. It can be achieved in two ways :
1. By using an assignment statement.
2. By using a read statement.
ASSIGNMENT STATEMENT:

VariableName = value ;

The general form of assignment is

Ex: count=10 ;

Ch=A ;

It is possible to assign a value to a variable at the time of its declaration.

type name = value ;


Ex:

int count=0 ;

char = % ;

The process of giving initial values to variables s know as the initialization.

READ STATEMENT:
We may also give values to variables interactively through the keyboard.
1. As command line arguments.
2. Using readLine( ) method

EXAMPLE TO SHOW FOR INPUT AT RUNTIME

import java.io.DataInputStream ;
class Abc
{
public static void main(String args [ ])
{
DataInputStream dis=new DataInputStream(System.in);
int

x;

float y ;
try

{
System.out.println(Enter an Integer);
n=Integer.parseInt(dis.readLine( ));

System.out.println(Enter a floating point number);


18 | O O P S T h r o u g h J a v a - G R K

x=Float.valueOf( dis.readLine( )).Floatvalue( );


}
catch (Exception e) { }
System.out.println(n=+n);
System.out.println(x=+x);
}
}

19 | O O P S T h r o u g h J a v a - G R K

CONTROL STATEMENTS
IF STATEMENT:
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements.
If ( test expression)
{ statements }
It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression is true or false, it transfers the control to a particular statement.
The if statement may be implemented in different forms depending on the complexity
of conditions.

Simple if statement
If else statement
Nested

if

..

TRUE

Test Condition

else

statement

Statement block
FALSE

Else if ladder

Next Statement

SIMPLE IF STATEMENT
The general form of a
simple if statement is

Next Statement
FLOW CHART OF SIMPLE IF STATEMENT

If ( test condition)
{statement block; }
statement x;
If

the

test

TRUE

FALSE

Test Condition

expression is true, the


statement-block will be
executed,

otherwise

True block stmts

False block stmts

the statement block


will be skipped and the

Next Statement

execution will jump to


the statement x.
Ex :

if (radium >=

FLOW CHART OF SIMPLE IF.ELSE STATEMENT

0)
20 | O O P S T h r o u g h J a v a - G R K

{ area = radius * radius *(22/7); }

IF ELSE STATEMENT :
It is an extension of the simple if statement. The general form is

if(test expression)
{
true block of statement(s);
}
else
{
false block of statement(s);
}
statement X;
If the test expression is true, then the true block statement(s) immediately following
the if statements are executed, otherwise the false block statement(s) are executed. In
either the case, either true-block or false-block will be executed, not both.
Ex :

if (radium >= 0)

area = radius * radius *(22/7);


System.out.println(area);

else
System.out.println( Negative number not allowed);

NESTING OF IF ELSE STATEMENTS :


If statements inside another if there exists any other if statement, it is called nested if
statement.
Ex :

if (i >= k)
{
if (j >= k)

21 | O O P S T h r o u g h J a v a - G R K

System.out.println( I and j are greater than k ) ;


}

else

System.out.println( I is less than k ) ;

TRUE

FALSE

Test condition I
Statement 1

FALSE

TRUE

Test condition 2
Statement 3
Statement 2

Statement 1
FLOW CHART OF SIMPLE NESTED IF.ELSE STATEMENT

THE ELSE IF LADDER:


The conditions are evaluated from the top down onwards.

As soon as the true

condition is found, the statement associated with it is executed and the control is transferred
to the statement x.
if ( condition 1)
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition 4)
statement ;
..
else if (condition N)

22 | O O P S T h r o u g h J a v a - G R K

statement N;
Ex:

if (marks > 79)


Grade = A;
else if (marks > 59)
Grade = B;
else if (marks > 49)
Grade = C;
else if (marks > 39)
Grade = D;
Else grade= fail;

THE SWITCH STATEMENT:


Java provides a switch statement to handle multiple conditions efficiently. The switch
statement tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed.
The general form of the switch statement is
Switch ( expression )
{
case

value 1:

block 1;

break;

case

value 2:

block 2;

break;

case

value 3:

block 3;

break;

case

value 4:

default :

block 4;

break;

default block break;

}
The expression is an integer expression or character. The break statement at the end
of each block signals the end of a particular case and causes on it from the switch statement.
Ex:

switch (grade)
{
case A

System.out.prinln(Distinction); break;

case B

System.out.prinln(First class); break;

23 | O O P S T h r o u g h J a v a - G R K

case C

System.out.prinln(Second Class); break;

Default :

System.out.prinln(Average); break;

THE ? : OPERATOR
This operator is popularly known as the conditional ternary operator. It is combination
of ? and :, takes three operands. The general form is
Condition expression ? expression 1 : expression 2;
The condition expression is evaluated first..

If the result is true, expression 1 is

evaluated, otherwise expression 2 is evaluated.


Ex: z = (x > y) ? x : y;

LOOP STATEMENTS :
The process of repeatedly executing a block of statements is known as looping. If a
loop continues forever, it is called an infinite loop. A program loop consists of two segments,
one known as the body of the loop and the other known as the control statement.
The control statement tests certain conditions and then directs the repeated execution
of the statements contained in the body of the loop. Depending on the position of the control
statement in the loop, a control structure may be classified as
1. Entry controlled loop
2. Exit controlled loop

ENTRY

ENTRY

BODY
OF
THE LOOP

FALSE
TEST CONDITIONS

TRUE

BODY
OF
THE LOOP

ENTRY CONTROL
LOOP

24 | O O P S T h r o u g h J a v a - G R K

FALSE
TRUE
TEST CONDITIONS

EXIT CONTROL
LOOP

Java language provides three types of loop structures.


1. The WHILE loop
2. DO WHILE loop
3. FOR loop

THE WHILE LOOP STATEMENT :


The simplest of all the three looping statement in java is while statement. The syntax is

while (test condition)


{

Body of the while loop

The while is an entry controlled loop statement. The test condition is evaluated and if
the condition is true, then the body of the loop is executed. The repeated execution of the
body continues until the test condition finally becomes false and the control is transferred out
of the loop. The body of the loop may not be executed at all, if the condition is false.

THE DO WHILE LOOP STATEMENT:


The body of the loop is executed at least once. The
general form is
At the end of the loop, the test condition in the while
statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again.

Do
{
Body of the loop
}
while (test condition)

When the condition becomes false, the loop will be terminated.

Since the test

condition is evaluated at the bottom of the loop, the do while loop is an exit controlled loop
and therefore the body of the loop is always executed at least once.
Ex: do {
sum=sum+10;
}while ( sum > 100)

THE FOR STATEMENT :


The for loop is an entry controlled loop. The for loop causes the loop of the body to be
repeated for a fixed number of times. The syntax of the for loop is as follows:

For ( initialization ; condition ; increment / decrement )


25 | O O P S T h{r oBody
u g hof Jloop
a v }a - G R K

Since the condition is tested always at the beginning of the loop, the body of the loop
will not be executed at all if the condition fails at the start.
Ex:

int i;
For ( i=0 ; i<100 ; i++ )
{ System.out.prinln(i); }

NESTING OF FOR LOOPS :


They are composed of an outer loop with one or more inner loops. The loops should
be properly indented so as to enable the reader to easily determine which statements are
contained within each for statement.

Ex:

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

for (j = 0 ; j < 10 ; j ++ )

Inner
loop

Outer
loop

}
}

KEY WORDS BREAK AND CONTINUE :


Two statements break and continue can be used in the loop constructs to provide the
loop with additional control.
Break This keyword immediately ends the innermost loop that contains it.
Continue -

This keyword only ends the current iteration. Program control goes to
the next cycle of the loop

Example for Break

class TestBreak
{
26 | O O P S T h r o u g h J a v a - G R K

public static void main(String args[ ])


{
int sum=0,c=0;
do {

Output:
The sum is 15

c++;
sum=sum+c;
if (sum==5) break;
}
while ( c < 5)

System.out.println(The sum is +sum);


}}

Example for Continue

class TestContinue
{

puplic static void main(String args[ ])


{
int sum=0,c=0;
do

c++;
if (c==2) continue
sum=sum+c;
}

while ( c < 5)

System.out.println(The sum is +sum);


}
}

LABELLED LOOPS:

27 | O O P S T h r o u g h J a v a - G R K

Output:
The sum is 13

In Java, we can give a label to a block of statements. A label is any valid java variable
name or identifier. To give a label to a loop, place it before the loop with a colon at the end.

Ex:

class ContinueBreak
{

public static void main(String args[ ])


{

loop1: for ( int i=1; i<100; i++)


{
System.out.println( ) ;
if ( i<=100) break ;
for ( int j=1; j<100 ; j++)
{
System.out.println( * ) ;
If (j==1)
Continue loop1:

28 | O O P S T h r o u g h J a v a - G R K

Output:
*
**
***
****
*****
..........
********
*

METHODS
METHOD :

A method is a collection of statements that are grouped together to perform an

operation. The general form of a method declaration is

access specifier Type method name ( parameters list)


{
body of method
}
Method declarations have five basic parts;
1. The name of the method (method name)
2. The type of the value the method returns (type)
3. The scope of the method where it can be called (access specifiers)
4. A list of parameters (parameter list)
5. The body of the method
A method can have a list of parameters formal parameters in the method specification.
When a method is called, these formal parameters are replaced by variables or data, which
are referred to as actual parameters.
Parameters are optional. The method body contains a collection of statements that define
what the method does.
Ex:

priivate protected int max ( int num1, int num2)


{
if (num1 > num2 )
return num1;
else
return num2;
}
The method terminates when a return statement is executed.

CALLING A METHOD :

29 | O O P S T h r o u g h J a v a - G R K

There are two ways to call a method. It depends on weather the method returns a
value or not. If the method returns a value, a call to the method is treated as value.
Ex:

int large = max (3,4)

It calls the method max and assigns the result of the method to the larger variable. If
the method does not return a value, it is treated as statement.
Ex:

System.out.println(Welcome);

When a program calls a method, program control is transferred to the called method.
A called method returns control to the caller when its return statement is executed or when its
method ending brace is reached.
Ex:

public class TextMax


{
public static void main(String args[ ])
{
int n1=5, n2=10, n3;
n3=max(n1,n2);

System.out.println( The maximum of +n1+ and +n2+ is +n3 ) ;


}
static int max (int a, int b)
{
if (a>b)

return a;

else

return b;

}
}
PASSING PARAMETERS :
The power of a method is its ability to work with parameters. When calling a method,
we must provide actual parametes, which must be given in the same order as their respective
formal parameters in the method specification. This is known as parameter order association.
Ex:

void nprintln(String msg, int n)


{

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

30 | O O P S T h r o u g h J a v a - G R K

{ System.out.println(msg);}
We can use nprintln(Hello

, 5) to print Hello 5 times. Hello and 5 are the

ACTUAL PARAMETERS. Whereas msg

and n are FORMAL PARAMETERS.

PASS BY VALUE :
When invoking a method with a parameter of primitive data type, such as int, the value
of the actual parameter is passed to the method. This is referred to as PASS BY VALUE.
The actual variable outside the method is not affected, regardless of the changes made to the
formal parameter inside a method.
Ex:

class TestPassByValue
{

public static void main(String args[ ])


{
int x=3 ;
System.out.prinln(Before call x is +x ) ;
Nprinln(Hello , x);
System.out.prinln(After call x is +x) ;
}
static void nprinln(String msg, int n)
{

while ( n>0)

{
System.out.prinln(msg);
n--;
}}}
Java passes the value of x to n

OVER LOADING METHODS :


Two method having the same name, but with different parameter profiles is called
method overloading.
The max ( ) method works only with the int data types. But if we need to find which of
two floating point numbers has maximum value, then we have to create another method with
the same name but with different no of parameters.

31 | O O P S T h r o u g h J a v a - G R K

double max(double a, double b)


{

if (a > b)
return a ;
else return b ;

}
If you call max( ) with int parameters, the max ( ) method with int parameters will be
invoked. If you call max ( ) with double parameters, the method with double parameters will b
invoked. This is referred to as method overloading.
Ex:

class TestMethodOverload
{

public static void main(String args[ ])


{
System.out.prinln( The max of 5 and 8 is +max(5,8));

System.out.prinln( The max of 5.2 and 8.1 is +max(5.2,8.1));


}
static double max(double a, double b)
{

if (a>b) return a;
else return b;

} }
static int max(int a, int b)
{

if (a>b) return a;
else return b;

} }
CREATING METHODS IN SEPARATE CLASSES:
We can create methods in separate classes so that they can be used by other classes.
Ex:

class TestSquareRoot
{

public static void main(String args[ ])


{

System.out.prinln(The square root for 9 is + SquareRoot.sqrt(9.0);


32 | O O P S T h r o u g h J a v a - G R K

}}
class SquareRoot
{ public static double sqrt(double d)
{
double diff, nextGuess, lastGuess=1.0;
do

{
nextGuess = (lastGuess + (n/lastGuess)) * 0.5;
diff= nextGuess lastGuess ;
lastGuess = nextGuess ;
if (diff < 0)

OUTPUT:
N.G
5
3.4
3.0235
3.0
3.0

diff = - diff;

} while ( diff >= 0.001);


return nextGuess ;

DIFF
4
-1.6
-0.3765
-0.0235
0

L.G
5
3.4
3.0235
3.0
3.0

}}

RECURSION :
The process of a method calling itself directly or indirectly is called recursion. It is a
powerful mathematical concept.
Ex:

The Fibonacci series problem.

succession.

The Fibonacci series begins with two is in

13

21

34

Each subsequent number is the sum of the previous two numbers in the series. The
series can be derived using recursion as follows :
Fib ( 1 ) =1 ;

Fib ( 2 ) =1 ;

Fib ( n ) = Fib ( n 2 ) + Fib ( n 1 )

where n > 2

For a recursive method to terminate the problem eventually must be reduced to a


stopping case.
Ex: public class TestFibonacci

{
public static void main(String args[ ])
{
int n=Integer.parseInt(args[a]);
System.out.println( Fibonacci Number at index +n+ is +fib(n));
33 | O O P S T h r o u g h J a v a - G R K

}
public static long fib(long n)
{

if ( ( n==1) || (n==2)) return 1;


else return fib(n-1) + fib(n-2);

}}
OUTPUT:
If n is 5 the series number is 5
Fib ( 5 ) = fib ( 4 ) + fib ( 3 )

Fib(3) + fib (2)


(1)

Fib(2) + fib (1)


(1)
(1)

Fib(2) + fib (1)


(1)
(1)

One or more base classes (Simplest cases) are used to stop recursion.

Every recursive call reduces the original problem into a base case.

34 | O O P S T h r o u g h J a v a - G R K

MODIFIERS :
Java provides the modifiers to control access to data, methods and classes. The
following are frequently used modifiers :
STATIC :

Defines data and methods as class members. It represents class wide


information that is shared by all instances of the class.

PUBLIC:

Defines classes, methods and data in such a way that all programs can
access them.

PROTECTED:

Defines data and methods in such a way that any class in the same
package or any subclass of that class can access them, even if the class is
in a different package.

PRIVATE :

Defines methods and data in such a way that they can be accessed by the
declaring class, but not by subclasses or other classes.

Action

access

Public

Protected

Default

Private protected

private

Location

Modifier

Same class

Yes

Yes

Yes

Yes

Yes

Subclass in same package

Yes

Yes

Yes

Yes

same Yes

Yes

Yes

Other

classes

in

package
Subclass in other package

Yes

Non-subclasses in

Yes

Yes

other package

35 | O O P S T h r o u g h J a v a - G R K

Yes

3. OBJECTS AND CLASSES:


Object is an entity which contains related set of data fields of a class to which it is
referring.

Certain properties define an object and

certain behaviors define what it does.

These

properties are known as data fields and objects


behaviors are defined by methods.

Data Field 1
Object

Data Field 2

Ex: A Circle object has a data field radius which is a property. One behavior of a circle is that
its area can be computed. Classes are structures that define objects . A class for an object
contains a collection of method and data definitions. Ex:

class Circle
{
double radius=1.0;
double area( )
{
return( radius * radius * 3.1415);
}
}
This class is different from all other classes. The circle class does not have a main( )
method. Therefore we cannot run this class. It is merely used to declare and create circle
objects.
The class that contain main( ) method is referred to as main class. An object is an
instance of a class. The creation of an object for a class is referred to as instantiation. In
order to declare an object, we must declare a class variable that represents that object.
class name object name;

Ex: Circle mycircle;

It declares a variable mycircle to be an instance of the Circle Class. The declaration of


an object simply associates the object with a class. It does not create the object. We must
use new operator for allocating memory space for it.
Object Name = new Class Name( );
Ex: mycircle = new Circle( );

36 | O O P S T h r o u g h J a v a - G R K

We can combine declaration and instantiation together in one statement as


classname object name=new ClassName( );
Ex: Circle mycircle=new Circle( );
After an object is created, it can access all of its data and methods by using dot
notation.
Objectname.data

References objects data

Objectname.method References objects method.


Ex:

mycircle.readius;
mycircle.area( )

Example:

Class TestClass {
Public static void main( String args[]) {
Circle mycircle=new Circle( );
System.out.println(The
radius
+mycircle.r);
System.out.println(The
area
+mycircle.area( ));
} }

is
is

class Circle
{
double r=20.0;
double area( ) {
return( r*r*3.1415);
}
}

CONSTRUCTORS
A Constructor initializes an object immediately after its creation. It has the same name
as the class in which it resides and is syntactically similar to a method.
Ex: Circle(double r)
{
radius = r;
}
Constructors are special methods that donot require a return type, not even void.
Ex: mycircle =new Circle(7.0) It assigns 7.0 to radius
Example:

37 | O O P S T h r o u g h J a v a - G R K

Class TestConstructor {
public static void main (String s[])
{
Circle c1=new Circle(6.0);
Circle c2=new Circle( );
System.out.println(The area of Circle c1 is
+c1.area( ));
System.out.println(The area of Circle c2 is
+c2.area( ));
}
}

class Circle {
double radius;
Circle (double r) {
radius=r;
}
Circle ( ) {
radius=2.0;
}
double area ( ) {
return(radius * radius * 3.1415);
}
}

OVERLOADING CONSTRUCTORS
The name of the constructor will be same but have different parameters. Ex:

class Box {
double width, height, depth;
Box( double w, double h, double d) {
width=w; height=h; depth=d;
}
Box( double l ) {
width=height=depth=l;
}
Box ( ) {
width=l; height=l; depth=l;
}
double volume( ) {
return (width * height * depth);
} }

class OverloadConstructor {
public static void main(String args[])
Box b1=new Box( );
Box b2=new Box(10);
Box b3=new Box(10,20,30);
double vol = b1.volume( );
System.out.println(Volume of Box
+vol);
vol = b2.volume( );
System.out.println(Volume of Box
+vol);
vol = b3.volume( );
System.out.println(Volume of Box
+vol);
} }

38 | O O P S T h r o u g h J a v a - G R K

1 is
2 is
3 is

4. INHERITANCE
The mechanism of deriving a new class from an existing class is called inheritance.
The old class is known as the base class, super class or parent class and the new one is
called the subclass, child class or derived class.
The inheritance allows subclasses to inherit all the variables and methods of their
parent classes.
Inheritance takes different forms
1. Single Inheritance (only one super class)
2. Multiple Inheritance (Several super classes)
3. Hierarchical Inheritance (one super class, many sub classes)
4. Multilevel Inheritance (Derived from a derived class)

B
Single Inheritance

Multiple Inheritance

Hierarchical Inheritance

C
Multilevel Inheritance

Defining a subclass:
The class derived form the super class is called the subclass. The syntax of sub class
is as follows..
class subclass name extends superclassname
{
variables declaration;
methods declaration;
}

39 | O O P S T h r o u g h J a v a - G R K

The keyword extends signifies that the properties of the superclassname are extended
to the subclass.
The subclass will contain its own variables and methods in addition with the variables
and methods of super class.

SUBCLASS CONSTRUCTOR:
A subclass constructor is used to construct the instance variables of both the subclass
and the super class. It uses keyword super to invoke the constructor method of the super
class.
The keyword super is used submit to the following conditions.

Super is used only within a subclass constructor.

The call to super class constructor must appear as the first statement within the
subclass constructor.

The parameters in the super call must match the order and type of the instance
variable declared in the super class.

Ex:

class Room {
int length;
int breadth;
Room( int x, int y) {
length=x;
breadth=y;
}
int area( ) {
return (length * breadth);
} }
class BedRoom extends Room{
int height;
BedRoom ( int x, int y, int z)
{
super(x,y);
height=z;
}
int volume( )
{
return( length * breadth * height);
}
}

40 | O O P S T h r o u g h J a v a - G R K

class InherTest
{
public static void main(String
args[])
{
BedRoom
br1=new
BedRoom(10,20,30);
int area1 = br1.area( );
//
super class method
int vol = br1.volume( );
//
sub class method
System.out.println(Area of the
Bedroom is +area1);
System.out.println(Volume
of
the Bedroom+vol);
}
}

OVERRIDING METHODS :
A method defined in a superclass is inherited by its subclass and is used by the
objects created by the sub class.
When we define a method in the subclass that has the same name, same arguments
and same return type as the method in the super class. Then, when that method is called, the
method defined in the subclass is invoked and executed instead of one in the super class.
This is known as overriding methods.
Example:

Class SuperA {
int x;
SuperA(int x) {
this.x=x;
}
void display( ) {
System.out.println(SuperA x= +x);
} }
class SubA extends SuperA {
int y;
SubA(int x, int y) {
super(x);
this.y=y;
}
void display( ) {
System.out.println(SuperA x=+x);
System.out.println(SubA y=+y);
} }

41 | O O P S T h r o u g h J a v a - G R K

class OverRideTest
{
public static void main(String
args[])
{
SubA s1=new SubA(10,20);
s1.display( );
}
}

FINAL VARIABLES AND METHODS:


All methods and variables can be overridden by default in sub classes. If we want to
prevent the subclasses form overriding the methods of superclass, we can declare them as
final using the keyword final as a modifier.
final int n=10;
final void display( );
The value of a final variable can never be changed.
FINAL CLASSES:
A class that cannot be subclasses is called a final class. It can be done by using
keyword final.
final class A
final class B extends C
Declaring a class final prevents any unwanted extensions to the class.
ABSTRACT METHODS AND CLASSES:
Abstract classes are like regular classes with data and methods, but we cannot create
instance of abstract classes using new operator. Abstract classes usually contain abstract
methods.
Abstract method is a method structure without any implementation. Its implementation
is provided by its subclass.
Abstract classes are declared using the abstract modifier. When a class contains one
or more abstract methods, it should also be declared abstract.
We can not use abstract classes to instantiate objects directly.
The abstract methods of an abstract class must be defined in its subclass.
We cannot create objects of abstract classes, but we can declare reference to abstract
class. Classes from which objects can be instantiated are called concrete classes.
Ex:

42 | O O P S T h r o u g h J a v a - G R K

Abstract class A
{
abstract void callme( );
void callme2( )
{
System.out.println(This is a concrete
method);
}
}
class B extends A
{
void callme( )
{
System.out.println(B s implementation of
class A Method);
}
}

class AbstractDemo
{
public static void main(String
args[])
{
B b=new B( );
B bb=b;
// one more
reference created for the same
entity or instance
b.callme( );
b.callme2( );
bb.callme( );
// same as
b.callme( )
bb.callme2( );
// same as
b.callme2( );
}
}

INTERFACES MULTIPLE INHERITANCE

Classes in Java can not have more than one


superclass.

Java provides an alternate approach


know as Inheritance

interface Interface_Name
{
variable declaration;
method declaration;
}

to

support

the

Ex:
interface Area {
Final static float pie=3.1415;
float compute (float x, float y);
void show( );
}

concept of multiple
Inheritance.

Java class cannot be a subclass of more than

one super class, it can implement more than one interface.

Interfaces define only abstract methods and final fields. This means that interfaces do
not specify any code to implement methods and contain only constants (data fields)
So it is the responsibility of the class that implements interface to define the code of
method.
The syntax is.
Here interface is the keyword and interface name is any valid java identifier (class name).

Variables are declared as follows:

static final type variable_name = value;

43 | O O P S T h r o u g h J a v a - G R K

All variables are declared as constants. Method declaration will contain only a list of
methods without any body statements.
The syntax is :
Return_type Method_name (parameter_list);

EXTENDING INTERFACES :
An interface can be sub interfaced
from another interfaces. It is achieved by
using the keyword extends.
The interface Item would inherit both
the constants code and name into it. All the
variables in an interface are treated as
constants although the keywords final and

Interface_name1 extends name1 {


body of name 2
}
Ex:
Interface ItemConstants {
int n=100;
String name=Java;
}
interface Item extends ItemConstants {
void display( );
}

static are not present.


When an Interface extends two or more interfaces, they are separated by commas.
Sub interfaces cannot define the methods declared in the super interfaces.
Example:
Class Student {
int roll;
void getNumber( int n ) {
roll = n;
}
void putNumber( ) {
System.out.println(Roll no is :+roll);
}}
class Test extends Student {
float marks1, marks2;
void getMarks(float m1, float m2) {
marks1=m1;
marks2=m2;
}
void putMarks( ) {
System.out.println(Marks Obtained :);
System.out.println(Marks1
=+marks1);
System.out.println(Marks2
=+marks2);
}}

interface sprorts {
float sportwt = 6.0f;
void putwt( );
}
class Results extends Test implements Sports {
float total;
public void putwt( ) {
System.out.println(Sport
weight
is
+sprotwt);
}
void display( ) {
total=marks1+marks2+sportwt;
putNumber( ); putMarks( ); putwt( );
System.out.println(Total score is +total);
} }
class MultipleInherTest {
public static void main(String args[ ] ) {
Results s1=new Results( );
s1.getNumber(1234);
s1.getMarks(80.3, 79.6);
s1.display( );
}}

IMPLEMENTING INTERFACES:

44 | O O P S T h r o u g h J a v a - G R K

Interfaces are used as super classes whose properties are inherited by classes.
The Syntax is

class classname implements InterfaceName


{
body of class name
}
A more general form of implementation is

class classname extends superclass implements interface1, interface2.


{
body of class name }

THE THIS KEYWORD:

The this keyword refers to the object that is currently executing.

this.varName(name of the instance variable)

This keyword allows one constructors to explicitly invoke another constructor in the
same class

this(args)

It must be the first line in a constructor

45 | O O P S T h r o u g h J a v a - G R K

Ex:
public class Circle
{
private double r;
public Circle(double r)
{
this.r=r;
}
public Circle( )
{
this(1.0);
}
double FindArea( )
{
return (r * r * Math.PI);
}
}

Ex: class ThisDemo


{
double a;
double b;
double c;
ThisDemo(double x, double y, double z)
{
this.a=x;
this.b=y;
this.c=z;
}

46 | O O P S T h r o u g h J a v a - G R K

MULTITHREADED PROGRAMMING
Multithreading is a conceptual programming where a program is divided into two or
more sub programs and which can be implemented at the same time in parallel.
Java programs that we have seen so far contain only a single sequential flow of
control. The program begins, runs through a sequence of executions and finally ends
At any given point of time, there is only one statement under execution.
A thread is similar to a program that has a single flow of control. It has a beginning, a
body and an end and executes commands sequentially. All main programs can be called
single threaded program.
Java supports multhreading.

Java enables us to use multiple flows of control in

developing programs. Each flow of control is known as a thread that runs in parallel to others.
A program that contains multiple flows of control is known as multithreaded program.

The Threads A, B and C run concurrently and share the resources jointly.

Class A
{
.

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

Begin
Body

Start

End

Single Threaded Program

Main Thread

Start

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

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

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

Thread A

Thread B

Thread B

Multi Threaded Program


CREATING THREADS:
Threads are implemented in the form of objects that contain a method called run( ).
The run ( ) method is the heart and soul of any Thread. It makes up the entire body of the
thread and is only method in which the threads behavior can be implemented.
Public void run( )
{
.

47 | O O P S T h r o u g h J a v a - G R K


}
The run( ) method should be invoked by an object of the concerned thread. This can
be achieved by creating the thread and initiating it with the help of another thread method
called start( ).
A new thread can be created in two ways
By creating a thread class

define a class that extends Thread class and override its

run( ) method.
By converting a class to a Thread Define a class that implements runnable interface.

EXTENDING THE THREAD CLASS :


We can make our class runnable as a thread by extending the class Thread
In includes 3 steps:
Declare the class as extending the Thread class
Implement the run( ) method.
Create a thread object and call the start ( ) method to initiate the thread execution.
class MyThread extends Thread
{
public void run( )
{
..
..
}
}
class TestThread
{
public static void main(String args[])
{
MyThread a=new MyThread( );
a.start( );

48 | O O P S T h r o u g h J a v a - G R K

}
}
It causes the thread to move into the runnable state. Then, the java runtime will
schedule the thread to run by invoking its run( ) method. Now the thread is said to be in
running state.
Example:

Class A extends Thread {


public void run( ) {
for (int i=0;i<5;i++) {
System.out.println(Thread A i= +i);
}
System.out.println(Exiting from A);
} }
class B extends Thread {
public void run( ) {
for (int i=0;i<5;i++) {
System.out.println(Thread B i= +i);
}
System.out.println(Exiting from B);
} }

class ThreadTest
{
public static void main(String args[])
{
new A( ).start( );
B b=new B( );
b.start( );
}
}

STOPPING AND BLOCKING A THREAD:


STOPPING A THREAD:
Whenever we want to stop a thread from running further, we may do so by calling its
stop( ) method.
a Thread.stop( );
It causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of the its method.
BLOCKING A THREAD:
A Thread can also be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following Thread methods
sleep ( )

blocked for a specified time

suspend ( )

blocked until further orders

wait ( )

blocked until certain condition occurs

They cause the thread to go into the blocked state. It returns to runnable state by using
resume( ) and notify( ).

49 | O O P S T h r o u g h J a v a - G R K

LIFE CYCLE OF A THREAD


During the life time of a thread, there are many states it can enter.

Born
start ( )

Runnable
sleep
interval
expires

resume ( )
Assign to processor
notify( )
yield ( )

Wait

Running

Sleep

Dead

Suspend

1. New born state


2. Runnable State
3. Running state
4. Blocked state
5. Dead State
NEW BORN STATE :
When we create a thread object, the thread is born and is said to be in new born state
at this state, we can do only one of the following things with it.

Schedule it for running using start( ) method

Kill it using stop ( ) method.

If scheduled, it moves to the runnable state.

RUNNABLE STATE:
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. If all threads have equal priority then they are given time slots for
execution in round robin fashion i.e. First cum First serve manner.
RUNNING STATE

50 | O O P S T h r o u g h J a v a - G R K

Running means that the processor has given its time to the thread for its execution. A
running thread may stop it process in one of the following situations.

suspend ( )

resume( )

sleep( time )

time is in milliseconds

wait ( )

notify ( )

BLOCKED STATE
A Thread is said to be blocked when it is prevented from entering into the runnable
state and subsequently the running state.

This happens when the thread is suspended,

sleeping or waiting in order to satisfy certain requirements.


DEAD STATE
Every thread has a life cycle. A running thread ends its life when it has completed
executing its run ( ) method. It is a natural death. A thread can be killed by sending the stop
message to it at any time.

THREAD PRIORITY
In java, each thread is assigned a priority, which affects the order in which it is
scheduled for running. The Threads of the same priority are given equal treatment by the
java scheduler and therefore, they share the processor on a first cum first serve basis
We can set the priority of a thread using
setPriority( )
Threadname.setPriority( int number);
The Thread class defines several priority constants

MIN_PRIORITY = 1

NORM_PRIORITY = 5

MAX_PRIORITY = 10

The default setting is NORM_PRIORITY. Method getPriority( ) returns the threads


priority

51 | O O P S T h r o u g h J a v a - G R K

Example:

Class A extends Thread


{
public void run( ) {
for ( int i=1; i <= 5; i++)
{
if ( i==1) yield( );
System.out.println(From Thread
i=+i);
}
System.out.println(Exit from A);
}
}

A:

class B extends Thread


{
public void run( ) {
for ( int j=1; j <= 5; j++)
{
if ( j= =3) stop( );
}
System.out.println(Exit from B);
}
}
class C extends Thread
{
public void run( ) {
for ( int k=1; k <= 5; k++) {
if ( k==1)
try{
sleep( ) ;
}cathch(InterruptedException ie){
System.out.println(Thread
C
blocked);
}
System.out.println(Exit from C);
} }

is

class ThreadMethods
{
public static void main(String args[])
{
A a = new A( );
B b = new B( );
C c = new C ( );
System.out.println(Start Thread A);
a.start( );
System.out.println(Start Thread B);
b.start( );
System.out.println(Start Thread C);
c.start( );
System.out.println(End of main
Thread);
} }
output
Start Thread A
Start Thread B
Start Thread C
From Thread B: j=1
From Thread B: j=2
A: i=1
A: i=2
End of main thread
From Thread C: k=1
From Thread B: j=3
A: i=3
A: i=4
A: i=5
Exit From A
From Thread C: k= 2
C: k= 3
C: k= 4
C: k= 5
Exit From C

THREAD SYNCHRONIZATION
Java uses monitors to perform synchronization. So far, we have seen threads that use
their own data and methods provided inside their run( ) methods. When we try to use data

52 | O O P S T h r o u g h J a v a - G R K

and methods outside the thread, they may compete for the same resources and may lead to
serious problems. Suppose one thread may try to read a record from a file while another is
still writing to the same file. Java enables us to overcome this problems using a technique
know as Synchronization.
When we declare a method synchronized, java creates a monitor and hands it over
to the Thread that calls the method first time. As long as the thread holds the monitor no other
thread can enter the synchronized method.
A monitor is like a key and the thread that holds the key can only open the lock. A
method is declared synchronized as

synchronized void update ( )


{
.
}
Whenever a thread has completed its work of using synchronized method, it will
handover the monitor to the next thread that is ready to use the same resource.
If there are several synchronized methods, only one synchronized method may be
active on an object at once, all other threads attempting to invoke a synchronized methods
must wait.

DEADLOCK:

Deadlock is an error that can be encountered in multithreaded programs. It occurs when two
or more threads wait indefinitely . for each other to relinquish licks. Assume that thread holds
a lock on object1 and waits for a lock on object2. Thread2 holds a lock on object2 and waits .
For a lock on object1. Neither of these threads may proceed.

Thread A

Synchronized method2( )
{
Synchronized method1( )
{

------

53 | O O P S T h r o u g h J a v a - G R K

------

}
}

Thread B
{
Synchronized mehtod1()
{
synchronized mehtod2()
{--------------}
}
}

IMPLEMENTING THE RUNNABLE INTERFACE

We can create threads in two ways one by using the extended thread class and
another by implementing the runnable interface. The runnable interface declares the run()
method that is required for implementing threads in our programs.
1. Declare the class as implementing the runnable interface
2. Implement the run() method
3. Create a thread by defining an object that is instantiated form this runnable class as
the target of the thread.
4. call the threads start() method to run the thread.

Ex. Class A implements runnable {


public void run() {
for(int i=1;i<5;i++) {
System.out.println(thread a:+i);

54 | O O P S T h r o u g h J a v a - G R K

}
System.out.println(A end of thread A):
} }

class RunnableTest {
public static void main(Sting as[]) {
A a=new A()
Thread t=new Thread(a);
t.start();
System.out.println(End of main thread):
} }

output
end of main thread
thread A=1
Thread A=2
.
.
.
Thread A=5
End of Thread A

DAEMON THREADS:
A daemon thread is a thread that runs for the benefit of other threads. Daemon
threads run in the background when processor time is available . Unlike conventional user
threads, daemon threads do not prevent a program form terminating.

The garbage

collector in a daemon thread. We designate a thread as a daemon with the method call

setDaemon(true);

55 | O O P S T h r o u g h J a v a - G R K

When only daemon threads remain in a program, the program exits. If a thread
is to be a daemon , it must be set as such before its start method is called or an
IllegalThreadState Exception is thrown.

56 | O O P S T h r o u g h J a v a - G R K

EXCEPTION HANDLING
An Exception is an indication that a problem occurred during the programs execution.
Some common examples of exceptions are an out-of-bounds array subscript,
arithmetic overflow, division by zero, invalid method parameters.
Events that occurred during the execution of a program and disrupt the normal flow of
control are called Exceptions (Runtime errors)
Java provides the capability to let the programmer to handle the runtime errors by
using exception handling

EXCEPTIONS AND EXCEPTION TYPES


Runtime errors occurs for various reasons. When a runtime error occurs, java raises
an exception.
Java exception handling is managed via five keywords: try, catch, throw, throws and
Finally

Program statements that we want to monitor for exceptions are contained within a try
block. If

an exception occurs within the try block, it is thrown. We can catch the

exception(using catch) and handle it in some rational manner. System-generated exceptions


are automatically thrown by the java run-time systems. To manually throw an exception, we
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 before a method

returns is put in a finally block. The general form of an exception handling block is
try{
Block of code to monitor for errors
} catch(Exception Type( )) {
Exception handler For Exception Type1
}
catch(Exception Type2) {
Exception handler For Exception Type2
}

57 | O O P S T h r o u g h J a v a - G R K

finally {
block of code to be executed before
try block ends
}
Here, exception type is the type of exception that has occurred .

EXCEPTION TYPES
All exception types are subclasses of the built-in class throwable. Throwable consists of two
subclasses
1.Exception
2.Error
The exception class describes the errors caused by the program. These errors can be
handled by our program. It has many subclasses.

RUNTIME EXCEPTION: programming errors such as accessing an out-of-bound array,


numeric errors and bad casting.
Ex. Arithmetic Exception, Illegal Argument Exception, IndexOutOfBoundsException
IOEXCEPTION: It describes errors related to I/O operations such as invalid input and opening
a nonexistent file.
Ex: EOFException, FileNotFoundException
AWT EXCEPTION: It describes errors caused by Awt operations

The error class describes internal system errors, which rarely occur. We can only
terminate the program. The most common compile time error are:

Missing semicolons

Missing or mismatch of brackets in classes and methods

Missing double quotes in strings

Bad references to objects

Incompatible types in assignments

Use Of un Declared Variables

58 | O O P S T h r o u g h J a v a - G R K

The most common run time errors are:

Dividing an integer by zero

Accessing an element that is out of the bounds of an array

Trying to store a value into an array of an incompatible type

Passing a parameter that is not in a valid range or value for a methods

Trying to illegally change the state of a thread

USING TRY AND CATCH

The default exception handlers provided by the java run time system is useful for
debugging , but we will usually want to handle an exception our self. It provides two benefits
first, it allows us to fix the error. Second, it prevents the program from automatically
terminating.
To guard against and handle a run time error, simply enclose the code inside a try
block. Immediately following the try block, include a catch clause that specifies the exception
type we wish to catch.
Once an exception is thrown, program control transfers out of the try block into the
catch block.

MULTIPLE CATCH CLAUSES:

In some causes, more than one exception could be raised by a single piece of code
.To handle this types. We can specify two or more catch clauses. Each catching a different
type of exceptions. When an exception is thrown, each catch statement is inspected in order
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are by passed and execution continuous after the try/catch
block.

59 | O O P S T h r o u g h J a v a - G R K

Throwable
Exception
ClassNotFoundE

Assertion

CloneNotFound

ThreadDeath

NoSuchMethod

VirtualMachine

Instantiation

Internal

IO

OutOfMemory

Interrupted

StackOverFlow

NoSuchField

UStackOverFlow

Illegalccess
RunTimeException

Arithmetic

Error

Linkage

nOutOfMemory
knInternal
ClassCirularity
own

ArrayStore

ClassFormat

ClassCast

ExceptionIniInitialize

IllegalArgument

ThreadDeath

IllegalThreadState
NumberFormat

IllegalMonitorState
IllegalState
IndexOutOfBound
ArrayIndexOutOfBound

StringIndexOutOfBound

NegativeArraySIze

NullPointer
Security
UnSupportedOperation

60 | O O P S T h r o u g h J a v a - G R K

NInCompatibleClassChange
tANoSuchMethod
oCExceptionIniInitialize
ngNoSuchFieldVirtual
Machine
UNoClassDefFound
e

Verify
UnSatisfiedLink

Ex:

Class Multicatch{
Public static void main(String args[]){
Try{
Int a=args.length();
System.out.print(a++a);
Int b=42/a;
Int c[]={2,3};
C[3]=99;
}
catch(ArithmeticException ae){
System.out.print(divide by zero:+ae);
}
catch(ArrayIndexOutOfBoundsException e){
Sysem.out.println(array index outof bounds exception );
}
System.out.print(after try/catch blocks);
}
}

WHEN EXCEPTION HANDLING SHOULD BE USED:

To process only exceptional situations where a method is unable to complete its task
for reasons it cannot control. To process exception from components that are not geared to
handling those exceptions directly. To process exceptions from software components such as
methods, libraries and classes that are likely to be widely used and where those components
can not handle their own exceptions.
To handle exceptions in uniform manner project wide on large projects.
THROWING AN EXCEPTION:

61 | O O P S T h r o u g h J a v a - G R K

The throw statement is executed to indicate that an exception has occurred. This is
called throwing an exception. A throw statements specifies an object to be thrown. The
operand of a throw can be of any class derived from class Throwable.
When an exception is thrown, control exits the current try block and proceeds to an
appropriate catch handler after the try block.
CATCHING AN EXCEPTION:
Exception handlers are contained in catch blocks. Each catch block starts with the
keyword catch followed by parenthesis containing a class name (specifying the type of
exception to be caught) and a parameter name.
When an exception is caught, the code in the catch block is executed. A catch that
catches an Exception object means to catch all exceptions.
catch (Exception e)
It must always be placed last in the list of exception handlers following a try block, or a
syntax error occurs.
When we use multiple catch statements, it is important to remember that exceptions
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 super class.

RETHROWING AN EXCEPTION :
It is possible that the catch handler that catches an exception may decide it cannot
process the exception or it may want to let the some other catch handler handle it.
In this case, the handler that received Exception e can simply rethrow the exception
with statement
throw e ;
Such a throw rethrows the exceptions to the next enclosing try block.

NESTED TRY STATEMENTS:


The try statements can be nested. That is, a try statement can be inside the block of
another try. If an inner try statement does not have a catch handler for particular exceptions,

62 | O O P S T h r o u g h J a v a - G R K

the next try statements catch handlers are inspected for a match. If no catch statement
matches, then the java run time system will handle the Exception.
Ex:

class NestTry
{
public static void main(String args[])
{
try
{
int a =args.length( );
int b=42/a;
System.out.println(a = +a);
Try
{
if (a==1)
a=a/(a-a);
if (a==20
{
int c[]={1,2,3};
c[5]=100;
}
} catch(ArrayIndexOutBoundsException e)
{
System.out.println(Array index out of bound :+e);
}
}
catch(ArithmeticException e)
{
63 | O O P S T h r o u g h J a v a - G R K

System.out.println(divide by zero :+e);


}
}
}

output

java NestTry
divide by zero : java.lang.ArithmeticException

java NestTry ONE


a=1
ArrayIndexOutOfBoundsException

THROW
So far we have been catching exceptions that are thrown by the java run time system.
However it is possible for us to thorw an exception explicitly, using the throw statement. The
general form of throw is
throw ThrowableInstance
Throwable Instance must be an object of type throwable or a subclass of Throwable
There are 2 ways for obtaining a throwable object.
1. Using a parameter into a catch clause
2. Creating one with the new Operator

64 | O O P S T h r o u g h J a v a - G R K

Class ThrowDemon {
static void demoprog( ) {
try {
throw
new
NullPointerException(demo);
} catch(NullPointerException e) {
System.out.println(Caught inside);
throw e;
} }

public static void main(String args[]) {


try {
demoprogr( );
} catch(NullPointerException e) {
System.out.println(Recaught);
} } }
output:
caught inside
recaught

Example:

THROWS:
If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that Exception.
It can be done by using throws clause in the methods declaration. A throws clause
lists the types of Exceptions that a method might throw.
The general form of a method declaration that includes a throws clause
Type method_name (parameter list) throws Excepions list
{
.
}
Here Exception_list is a comma separated list of exception that a method can throw.

65 | O O P S T h r o u g h J a v a - G R K

Class FinalBlockDemo {
static void ProcA( ) {
try {
System.out.println(Inside proc A);
Throw new RuntimeException(demo);
} finally
{
System.out.println(Proc A is Finally);
} }
static void procB( ) {
try {
System.out.println(Inside procB);
Return;
} finally
{
System.out.println(ProcBs finally);
}}

static void procC( ) {


try {
System.out.println(Inside proc C);
} finally {
System.out.println(Proc C s finally);
} }
public static void main(String s[]) {
try {
procA( )
}catch (Exception e) {
System.out.println(Exception
caught); }
procB( );
procC( );
} }
output
inside proc A
Proc As Finally
Exception caught
inside proc B
Proc Bs Finally
inside proc C
Proc Cs Finally

FINALLY BLOCK:
The finally block is optional. If it is present it is placed after the last of a try blocks
catch blocks.
The finally block will execute whether or not an exception is thrown. If an Exception is
thrown, the finally block will execute even if no catch statement matches the exception.
Ex:

USING PRINT STACK TRACE AND GET MESSAGE:


Exceptions derive from class Throwable it is placed after the last of a try blocks catch
blocks.
The finally block will execute whether or not an exception is thrown. If an exception is
thrown, the finally block will execute even if no catch statement matches the exception.
Ex:

66 | O O P S T h r o u g h J a v a - G R K

class FinalBlockDemo {

public static void main(Sting args[]) {


try {
procA( );
} catch(Exception e)
{
System.out.println(Exception
caught);
}

static void porcA( ) {


try {
System.out.println(Inside Proc A);
throw new RuntimeException(demo);
} finally
{
System.out.println(Proc As finally);
} }

procB( );
procC( );
}
}

static void procB( ) {


try{
System.out.println(Inside procB);
Return;
} finally
{
System.out.println(Proc Bs finally);
} }
static void procC( ) {
try {
System.out.println(Inside procC);
} finally
{
System.out.println(Proc Cs finally;
} }

output
inside procA
Proc As finally
Exception caught
inside procB
Proc Bs finally
inside procC
Proc Cs finally

USING PRINT STACK TRACE AND GET MESSAGE:

Exceptions derive from class Throwable. Class Throwable offers a printStackTrace


method that prints the method call stack.

There are two constructors for class Exception.

Public Exception( )

takes no arguments

Public Exception(String str)

It takes str . We can get str by calling getMessage


method.

Ex:

public class UsingExceptions {


public static void main(String as[]) {
try {
method1();
} catch(Exception e) {
67 | O O P S T h r o u g h J a v a - G R K

System.out.println(e.getmessage());
e.kprintStacktrace();
} }

public static void method1() throws Exception {


method2();
}

public static void method2() throws Exception {


method3();
}
public static void mathod3() throws Exception {
throw new Exception(Exception throw in method3);
} }

output

exception thrown in method3


java.lang.Exception: Exception thrown in method3
at using exceptions.method3(using exceptions.java:28)
at using exceptions.method2using exceptions.java:23
at using exceptions.method1using exceptions.java18)
at using exceptions.main (using exceptions.java:8)

THROWING OUR OWN EXCEPTIONS:


We can throw our own exceptions . We can do this by using the keyword throw as
follows
Throw new Throwable-subclass.

68 | O O P S T h r o u g h J a v a - G R K

Ex:

class MyException extends Exception {


MyException (String msg) {
super(msg);
} }

class TestMyExc {
public static void main(String as[]) {
int x=5;y=1000;
try {
float z=(float)x/(float)y;
if(z<.01)
{
throw new MyException(number is too small);
}
} catch(MyExcetpion e) {
System.out.println(caught my exception);
System.out.prinln(e.getMessage( ));
}
finally {
System.out.println(iam always here):
} } }

output

caught MyException
number is too small
I am always here

69 | O O P S T h r o u g h J a v a - G R K

PACKAGES
A package is a collection of classes. It provides a convenient way to organize those
classes. We can put the classes in packages and distribute the packages to their programs.
Ex: java.io package
Packages are hierarchical and can have packages within other packages.
Ex: java.io.DataInputStream
DataInputstream is a class in the package io and that io is a package within the
package java.

Java packages are classified into two types

Java API packages

User defined packages

JAVA API PACKAGES;


It provides a large number of classes grouped into different packages according to
functionality

java
lang

util

io

awt

net

applet

These are the frequently used API packages

Java.lang:

It support classes. They are used by java compiler and therefore they are
automatically imported. They include classes for primitive types, strings,
math functions, threads and exceptions.

70 | O O P S T h r o u g h J a v a - G R K

Java.util :

StringTokenizer, random numbers etc

Java.io:

I/O support classes

Java.awt:

It contains set of classes for implementing GUI. They include classes for
windows, buttons, menus and so on.

Java.net :

classes for networking

Java.applet:

classes for creating and implementing applets

There are two ways of accessing the classes stored in a package. The first approach
is to use fully qualified class name
Ex: java.io.DataInputStream
The hierarchy is represented by separating the levels with dots.
If we want to access many classes contained in a package we can achieve it as
Import packagename.*;

This statements must appear at the top of the file, before any class declarations

CREATING USER DEFINED PACKAGES:


We must first declare the name of the package using the package keyword followed by
the package name. This must be first statement in a java source file.

Ex: package <package_name>


public class <classname>
{
-}
It must be saved as classname. Java and located in a directory name packagename
The following steps are followed for creating a package
1. declare the package at the beginning of a file using the form

71 | O O P S T h r o u g h J a v a - G R K

package packagename;
2. define the class that is to be put in the package and declare it public.
3. create a subdirectory under the directory where main source files are stored.
4. store the listing as classname.java file in the subdirectory created.
5. compile the file. This creates.class file is the subdirectory.

ACCESSSING A PACKAGE:

Java system package can be accessed either using a fully qualified classname or
using a shortcut approach through the import statements
import packagename[.packagename].classname;

ADDING A CLASS TO A PACKAGE:


It is simple to add a class to an existing package. Consider the following package
Package p1;
Public class A
{
..

}
the package p1 contains one public class by name A. suppose we want to add another class
B to this package.

This can be done as follows


1. define the class and make it is public
2. place the package statement before class definition

package p1;
public class B
{

72 | O O P S T h r o u g h J a v a - G R K


.
}
3. save this as B.java file under directory p1
4. compile B.java file

ex:

package pack;
public class simple {
public void ds( ) {
System.out.println(This is simple class2);
} }

import pack.simple;
class packdemo {
public static void main(String as[]) {
simple a=new simple();
a.ds();
} }
THE MATH PACKAGE:
The math class contains the methods needed to perform basic mathematical functions.
Two useful constants, PI and E(the base of the natural logarithms ) are provided in the math
class
The methods in the math class can be categorized as trigonometric methods,
exponent methods and miscellaneous methods.

TRIGONOMETRIC METHODS;
The math class contains the following trigonometric methods

73 | O O P S T h r o u g h J a v a - G R K

public static double sin(double a);


public static double cos(double a);
public static double tan(double a);
public static double asin(double a);
public static double acos(double a);
public static double atan(double a);

EXPONENT METHODS:
public static double exp(double a);
// return e raised to the power of a;
public static double log(double a);
// return the natural logarithm of a;
public static double pow(double b);
// return e raised to the power of b;
public static double sqrt(double a);
// return the square root of a;

THE MIN( ), MAX( ), ABS( ) AND RANDOM( ) METHODS:


The min( ) and max() function return the minimum and maximum numbers between
two numbers (int, long, float or double);
The abs( ) function returns the absolute valve of the number
The random( ) function grnerates a random double floating point number between 0
and 1
All methods and data in the math class are static.

74 | O O P S T h r o u g h J a v a - G R K

APPLET PROGRAMMING
Applets are small java programs that are primarily used in internet computing. An
applet developed locally and stored in a local system is known as a local applet.
A remote applet is that which is that which is developed by someone else and stored
on a remote computer connected to the internet.
In order to locate and load a remote applet we must know the applets address on the
web. This address is known as Uniform Resource Locator (URL) and must be specified in the
applets HTML document.

The steps involved in developing and testing an applet are

Building an applet code (.java file)

Creating an executable applet (.class file)

Designing a web page using HTML tags.

Preparing <APPLET> tag.

Incorporating <APPLET> tag into the web page.

Creating HTML file.

Testing the applet code.

It is essential that our applet code uses the services of two classes, namely, Applet
and Graphics from the java class library.
The applet class which is contained in the java applet package provides life and
behavior to the applet through its methods such as init( ), start( ), and paint( ).
The paint( ) method of the applet class when it is called actually the result of the applet
code on the screen.
public void paint(Graphics g)
The applet code imports the java.awt package that contains the Graphics class.

The General Form of an Applet is


import java.awt.*;
import java.applet.*;
--- --public class appletclassname extends Applet {
------

75 | O O P S T h r o u g h J a v a - G R K

public void paint(Graphics g) {


-----

}}

The applet class name is the main class for the applet.

APPLET LIFE CYCLE:

The applet states include

Born or initialization state

Running state

Idle state

Dead or destroyed state

INITIALIZATION STATE:Applet enters the initialization state when it is first loaded. This is achieved by calling
the init( ) method of applet class. The applet is born. If occurs only once in the applets life
cycle.
Public void init()
{
----}
RUNNING STATE:Applet enters the running state when the system calls the state() method of applet
class. If occurs automatically after the applet is initialized.
Public void start( )
{
- - - -- }
IDLE OR STROPPED STATE:An applet become idle when it is stopped from running. Stopping occurs automatically
when we leave the page containing the currently running applet we can also do so by calling
the stop( ) method explicitly.

76 | O O P S T h r o u g h J a v a - G R K

public void stop( )


{
--------}
DEAD STATE:-An applet is said to be dead when if is remove from memory. This occurs
automatically by invoking the destroy() method when we quit the browser.
public void destroy ()
{
-

------

------

}
DISPLAY STATE:Applet moves to the display state whenever it has to perform same output operations
on the screen. The paint () method is called to accomplish this task.
public void paint(Graphics g)
{
-

- - --

---

}
Almost every applet will have a paint () method.

77 | O O P S T h r o u g h J a v a - G R K

THE ABSTRACT WINDOW TOOLKIT CLASS HIERARCHY:Java has a rich set of classes to help us build graphical user interfaces. We can use
various GUI-building classes, such as Frames, Panels, Buttons, Labels, Text Fields and
Menus to construct user interfaces. These classes are grouped in the packages java.awt,
java.awt.event and java.applet called the Abstract Window Toolkit (AWT)

Object

AwtEvent

Container

Panel

Font

Button

Window

Font Metrics

Label

Component

Text Component

Text Field

Color

List

Text Area

Graphics

Choice

Layout Manager

Check box

Frame

CheckboxGroup
Menu component
COMPONENT:This is a super class of all AWT user interface classes
CONTAINER:It is used to group components. A container can be embedded in another container. A
layout manager is used to position and place the components in the desired location and style
in a container.
WINDOW:They are simple containers that do not have a title bar or any of the other buttons.
FRAME:They are windows that include all of these common windowing features such as
buttons and title bar.
FRAMES:A frame is a top-level window with a title. All the graphical elements in java
applications must be placed in a frame.
Es:-

import java.awt.*;
public class MyFrame

78 | O O P S T h r o u g h J a v a - G R K

{
public static void main(String s[])
{
Frame f=new Frame(Test Frame);
f.setSize (400,300);
f.setVisible (true);
}}
We can use the following two constructors to a frame object
Frame f=new Frame (String title)
Frame f= new Frame ()
It declares and creates a Frame object F that is untitled.
The frame is not displayed until f.setVsisible (true) method is applied
Output:-

TestFrame

__
EVENT-DRIVEN PROGRAMMING
EVENTS:- An Event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a GUI.
Some of the activities that cause events to be generated are pressing a button,
entering a character via keyboard, selecting as item in a list and clicking the mouse.
Events may also occur due to a Software or hardware Failures.
EVENT SOURCES:- A source is an object that generates an event sources may generate
more that one type of event.
A source must register Listeners in order for the listeners to receive notifications about
a specific type of event.

The General Form is

79 | O O P S T h r o u g h J a v a - G R K

Public void addType Listener (TypeListener el)


Type is the name of the event
el is the reference to event Listener
Ex:-

addKeyListener( )
addMouseMotionListener( )

EVENT LISTENER: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 type of events.
Second, it must implement methods to receive and process those notifications.

EVENT CLASS

LISTENER INTERFACE

LISTENERMETHODS(HANDLERS)

ActionEvent

ActionListener

actionperformed(ActionEvent)

ItemEvent

ItemListener

itemStateChaged(ItemEvent)

KeyEvent

KeyListener

keyPressed (KeyEvent)
key Released (KeyEvent)
keyTyped (KeyEvent)

MouseEvent

MouseListener

mousePressed (MouseEvent)
mouseEntered (MouseEvent)
mouseReleased (MouseEvent)
mouseExited (MouseEvent)
mouseClicked (MouseEvent)

MouseMotionListener

mouseDragged (MouseEvent)
mouseMoved (MouseEvent)

MOUSE EVENT HANDLING:It consists of MouseListener and MouseMotionListener event-Listeenr interfaces for
handling MouseEvents.
The mouse event handling methods takes a MouseEvent object as its argument.
A MouseEvent object contains information about the mouseEvent that occurred,
including the x and y co-ordinates of the location where the event occurred.

80 | O O P S T h r o u g h J a v a - G R K

MouseListener and MouseMotionListener interface methods


public void mousePressed (MouseEvent e) //MouseListener
------

It is called when a mouse button is pressed with the Mouse cursor on a

component.
public void mouseClicked (MouseEvent e) //MouseListener
------

It is called when a mouse button is pressed and released on a component

without moving the Mouse cursor.


public void MouseReleased (MouseEvent e)
------

It is called when a mouse button is released after being pressed. It is preceded

by a MousePressed event.
public void MouseEntered (MouseEvent e)
------

It is called when mouse cursor enters the bounds of a component.

public void MouseDragged (MouseEvent e)


------

It is called when the mouse button is pressed and the mouse is moved.

public void mouseMoved (MouseEvent e)


------

It is called when the mouse is moved with the Mouse cursor on a component.

public void MouseExited (Mouse Event e)


------

It is called when the Mouse cursor leaves the bounds of a component.

KEYBOARD EVENT HANDLING:It contains key Listener event-listener interface for handling key events. Key events are
generated when keys on the keyboard are pressed and released.
A class that implements KeyListener must provide definitions for methods keyPressed,
keyReleased and keyTyped each of which receives a keyEvent as its argument.
Class KeyEvent is a subclass of InputEvent. Method Key Pressed is called in response
to pressing any key. Method Key Typed is called in response to pressing any key that is not
an action key (e.g an arrow key, Home, End, Page up, Page down, NumLock, Caps Lock,
Pause etc).
Method keyReleased :- It is called when the key is released after any keyPressed or
keyTyped event.
Ex:-

import java.awt.*;
Import java.awt.event.*;

81 | O O P S T h r o u g h J a v a - G R K

Import java.applet.*;
/*<applet code=simplekey width=300 height=200></applet>*/
public class simplekey extends Applet implements KeyListener {
String msg= ;
int x=10, y=20;
public void init() {
addKeyListener(this);
requestFocus(); }
public void KeyPressed (KeyEvent ke) {
show status (key up);}
public void keyTyped (KeyEvent ke) {
msg+=ke.gerKeychar();
repaint(); }
public void paint(Graphics g) {
g.drawstring(msg,x,y);
} }
OUTPUT:-

Applet

This is a test

__

Key Up

WORKING WITH GRAPHICS


The drawLine() method takes two pair of co-ordinates (x1,y1) and (x2,y2) as
arguments and draws a line between them.
g.drawLine(int startx, int starty, int endx, int endy)
g.drawLine(10,10,50,50);

82 | O O P S T h r o u g h J a v a - G R K

We can draw a rectangle using the drawRect() method. It takes four arguments. The
first two represent the x and y coordinates of the top left corner of the rectangle and the
remaining two represent the width and the height of the rectangle.
g.drawRect (int top, int left, int width, int height)
g.fillRect (int top, int left, int width, int height)
g.drawRect (10, 10, 50, 20);
g.fillRect (100, 50, 50, 30);
To draw a rounded rectangle, use drawRoundRect() or FillRoundRect() methods.
void drawRoundRect((int top, int left, int width, int height, int xdiam, int ydiam)
g.fillRoundRect((int top, int left, int width, int height, int xdiam, int ydiam)
A rounded rectangle has rounded corners. The diameter of the rounding are along the
x-axis is specified by xdiam. The diameter along the y-axis is specified by ydiam.
CIRCLES AND ELLLIPSES:The drawOval () method can be used to draw a circle or an ellipse.
It tales four arguments, the first two represent the top left corner of the imaginary
rectangle and the other two represent the width and height of the oval.
If the width and height are the same, the oval becomes a circle.
g.drawOval ((int top, int left, int width, int height)
g.fillOval ((int top, int left, int width, int height)
POLYGONS:Polygons are shapes with many sides. Ti is considered as a set of lines connected
together.
g.drawPolygon ((int x[], int y[], int numpoints)
g.fillPolygon ((int x[], int y[], int numpoints)
It takes three arguments
An array of integers containing x coordinates.
An array of integers containing y coordinates.
An integer for the total number of points.s
Ex:-

import java.awt.*;
Import java.applet.*;

83 | O O P S T h r o u g h J a v a - G R K

/*<applet code=HourGlass width=300 height=300></applet>*/


public class HourGlass extends Applet
{
public void paint(Graphics g)
{
int x points[]={30,200,30,200,30};
int y points[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
}
}
DRAWING ARCS:An arc is a part of an oval. The drawArc() method takes six arguments. The first four
are the same as the arguments for drawOval() method and the last two represent the starting
angle of the arc and the number of degrees (sweep angle) around the arc.
g.drawArc (int top, int left, int width, int height, int startangle, int sweepAngle)
g.fillArc (int top, int left, int width, int height, int startAngle, int sweepAngle)
Zero degree is on the horizontal at the 3o clock position. The arc is drawn counter
clockwise if sweep Angle is positive, and clockwise if sweep Angle is negative.

900
1800
00

1800

2700
g.drawArc(100,100,100,50,45,-135)

84 | O O P S T h r o u g h J a v a - G R K

450
1800
00
-1350

2700

WORKING WITH COLOR


Class color defines methods and constants for manipulating colors in a java program.

COLOR CONSTANTS
public final static color orange;
public final static color cyan;
Methods:public color (int r, int g, int b)
--- It creates a color based on red, green and blue contents expressed as integers from
0 to 255
public color(Float x, Float g, Float b)
---- 0.0 to 0.1
color gerColor()
public void setColor(Color c)
setBackfround (Color c)------ To set Background colors
setForefround ( Color c) ---- To set Foreground colors
we can use one of the 13 standard colors as constants in java.awt.color
black

blue

cyan

green

darkGray

lightGray

magenta

orange

pink

red

white

yellow

85 | O O P S T h r o u g h J a v a - G R K

The Font and FontMetrics Classes:We can set the font for the text and use font metrics to obtain font size. Fonts and font
metrics are encapsulated into two AWT classes: Font and FontMetrics
The syntax for setting a font is
Font f=new Font (name, style, size);
Font names are TimesRoman, Courier, Symbol, Sansserif
Styles are Font.PlAIN, Font.BOLD, Font.ITALIC. Font styles can be used in combination.
Eg:- Font.ITALIC+Font.BOLD
The font size is measured in points. A point is 1/72 of an inch.
Graphic methods serFont method sets the current drawing Font
Ex:- g.setFont(new Font(Serif, Font.BOLD,20)):
FontMetrics:- It is used to compute the exact length and width of a string. A FontMetrics is
measured by the following attributes.
Leading:-

Amount of space between lines of text.

Ascent:-

It is the height of a character form the baseline to the top.

Descent:-

It is the distance from the baseline to the bottom of a descending character

such as j,y and g.


Height:-

It is sum of leading, ascent and desent.

The instance methods to obtain Font information


public int getAscent()
public int gerDescent()
public int getLeading()
public int gerHeight(0]
public int stringWidth(String str)
To get a FontMetrics object for a specific Font
g.getFontMetrics (Font F);
g.gerFontMetrics();

// get FontMetrics for current font

86 | O O P S T h r o u g h J a v a - G R K

Leading

Base Line

By

Ascent

Descent

LABELS:It is the easiest control. A label is an object of type label and it contains a string, which
it displays. Labels are passive controls that do not support any interaction with the user.

87 | O O P S T h r o u g h J a v a - G R K

It defines the following constructors


Label() - - - blank label
Label(String str) --- label contains string
Label(String str, int how)------ label contains string specified by str using the alignment
specified by how.
The value of how must be one of these three contants
Label.LEFT,

Label.RIGHT,

Lable.CENTER

We can set or change the text in a label by using setText () method.


We can obtain the current Label by calling getText () method.
public void setText (String s)-- -

s specifies new Text

public string getText ()- - - - It returns a string for the label.


Public getAlignment ()
Public setAlignment (int Alignment)
BUTTONS:The most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed.

It defines two constructors


public Button( )

creates an empty button with no label.

public Button(String s)-

It creates a button with label s.

we can set the label of a button by calling setLabel( )


we can retrieve the label by calling getLabel( ) method.
Each time a button pressed an action event is generated. This is sent to the listeners.
Each listener implements the ActionListener interface. That interface defines the
actionPerformed () method, which is called when an event occurs.
Ex:-

import java.awt.*;
import java.applet.*;
/*<applet code=ButLabDemo width=300 height=400></applet>*/
public class ButLabDemo extends Applet implements ActionListener {
String msg= ;
Button yes,no;

88 | O O P S T h r o u g h J a v a - G R K

public void init() {


Label one=new Label(ONE);
Label two=new Label(TWO);
add(one); add(two);
yes=new Button(YES0;
no=new Button(NO);
add(yes); add(no);
yes.addActionListener(this);
no.addActionListener(this);
}
public void actionPerformed (ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals(YES))
msg=you pressed yes;
else if(str.equals(NO))
msg-you pressed No;
else
msg= you pressed nothing;
repaint();
}
public void paint (Graphics g) {
g.drawString(msg,20,100);
} }

CHECKBOXES:It is a control that is used to trun an option on or off. It consists of a small box that can
either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents.
We can change the state of a checkbox by clicking on it.

89 | O O P S T h r o u g h J a v a - G R K

It supports these contructors


Checkbox()-----

checkbox with blank label.

Checkbox (String s) -----

checkbox with label s

Checkbox(String s, Boolean on) ---- it allows us to set the initial state of checkbox.
Checkbox (String s, Boolean on, CheckboxGroup cbg) --- label specified by s and
group specified by cbg.
To retrieve current state of a checkbox, call the method gerState().
To set the state of a checkbox, call setState()
To set the label, call setLabel()
The listeners implements ItemListener interfaces. That interfaces defines the
itemStateChaged() method, which is called when a checkbox is clicked.
CHECK BOX GROUP:It is possible to create a set of mutually exclusive checkboxes in which one and only
one check box in the group can be checked at any one time.
These checkboxes are often called as radio buttons check boxes display a square that
is either checked of blank, and a check box in the group displays a circle that is either filled or
blank.
We can determine which checkbox in a group is currently selected by calling.
getSelectedCheckbox ()
we can set a checkbox by calling
serSelectedChecknbox ()
Ex:-

import java.awt.*;
import java.applet.*;
/*<applet code=CBGroup width=300 height=400></applet>*/
public class CBGroup extends Applet implements ItemListener {
String msg= ;
Checkbox win98, winNT, solaris;
CheckboxGroup cbg;
public void init() {
cbg-new checkbox Group();

90 | O O P S T h r o u g h J a v a - G R K

win98=new checkbox(Windows 98, cbg, true);


winNT=new checkbox(Windows NT, cbg, false);
Solaris=new checkbox(SOLARIS, cbg, false);
add(win 98);

add(wn NT);

add(Solaris);

win98.addItemListener (this);
winNT.addItemListener (this);
Solaris.addItemListener (this); }
public void itemStateChanged(ItemEvent ie) {
repaint()
}
public void paint (Graphics g) {
msg=Current selection : ;
msg+= cbg.getSelectedcheckbox().getLabel();
g.drawString (msg,10,100);
} }
OUTPUT:-

Windows 98
Windows NT
Solaris
Current Selection: Solaris
CHOICE CONTROLS:It is used to create a pop-up list of items from which the user may choose. It is like a
menu when the user clients on it, the whole list of choices pops up and a new selection can be
made.
Choice defines only default constructor, which creates an empty list.
To add a selection to a list, call add ()
void add (String s)
To determine currently selected item, we can call either getSelectedItem () or
getSelectedIndex ()

91 | O O P S T h r o u g h J a v a - G R K

String getSelectedItem () returns a string


int getSelectedIndex () returns an index of item

To obtain the number of items in the list, call


int getItemCount()
string getItem (int index)

It gets an item from the choice at the specified index.

public void select (int index)


public void select (String s) -- It selects the item
Each time a choice is selected, an itemevent is generated. It was sent to Listeners.
Each Listener implements item Listener interface. If defines itmeStateChaged () method.
LISTS:It provides a compact, multiple-choice, scrolling selection list.
A list object can be constructed to show any number of choices in the visible window.

List provides three constructors:List()

any one item to be selected at any one item.

List(int numRows)-

It specifies the number of entries in the list that will always be visible.

List(int numRows, Boolean Multipleselect) User may select two or more items at a time.
To add a item to the list , call add() method
void add(String s) - It add S at the last
void add(String s, int indes) it adds s at the specified index
To find the currently selected Item
String getSelectedItem( )
int getSelectedIndex( )
To find multiple selected items
String[ ] getSelectedItems ()
int[ ] getSelectedIndexes ()
To obtain the number of items in the list, call int getItemCount( ).
Ex:-

import java.awt.*;
import java.applet.*;

92 | O O P S T h r o u g h J a v a - G R K

import java.applet.event.*;
/*<applet code=ListDemo width=300 height=400></applet>*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg= ;
public void init()

os=new Lsit(4, true);


browser =new List (4,false);
os.add(win 98);

os.add(wn NT);

os.add(Solaris);

os.add(Dos); browser.add(JAVA); browser.add(C);


browser.add(ORACLE);

browser.add(VB);

browser.add(DBMS);

browser.add(NETSCAPE); browser.select(1);

add(os);

add(browser);

browser.addActionListener(this);

os.addActionListener(this);

}
public void actionPerformed(ActionEvent ae)
repaint()

public void paint (Graphics g) {


int idx[];
msg=Current os : ;
idx= os.getSelectedIndexes();
for(int i=0;i<idx.length;i++)
msg+= os.getItem (idx[i])+ ;
g.drawString (msg,10,100);
msg=Current browser : ;
msg+= browser.getSelectedItem ();
g.drawString (msg,10,150);
}

OUTPUT:-

93 | O O P S T h r o u g h J a v a - G R K

Win 98

Java

Win NT

Win XP

Oracle

Dos

VB

Current OS : Win NT
Current Language : VB
TEXT FIELD:It implements a single-line text entry area, usually called an edit control.

It is a

subclass of Textcomponent

It defines the following constructors


Textfield()
Textfield( int width)

It creates an empty text field with specified number of columns.

Textfield(String s)

it creates a text field with specified string s

Textfield(String s, int width) It creates a text field with specified strings and the column size
width.
To obtain the string currently contained in the text field, call
String getText ()
To set the text, call
void setText (String s)
We can select a portion of the text in a text field by
String getSelectedText( )
void select (int startindex, int endindex)
We can control whether the contents of a text filed may be modified by the user by
calling.
boolean isEditable()
vod setEditable (Boolean canEdit)
We can set the passwords by disable the echoing of characters as they are typed by
calling

94 | O O P S T h r o u g h J a v a - G R K

void setEchoChar (Char ch)


boolean echoCharIsSet()
Char getEchoChar()

TEXT AREA:Sometimes a single line of text input is not enough for a given task. To handle these
situations the AWT includes simple multiline editor called TextAtea.

The Constructors Are:TextArea()


TeatArea (int numLines, int numChars)
TeatArea (String s)
TeatArea (String s, int numLines, int numChars)
TeatArea (String s, int numLines, int numChars, int SBars) ------- numLines

specifies

the

height, in lines of the textArea. Numchars specifies the width, in charaters


We can specify the scroll bars for the TextArea scrollbars must be one of these values.
SCROLLBARS-BOTH
SCROLLBARS-HORIZONTAL-ONLY
SCROLLBARS-VERTICAL-ONLY
SCROLLBARS-NONE
TextArea adds text with the help of the following methods
void append(String s)
void insert (String s, int index)
void replaceRange(String s, int startindex, int endindex)
It replaces the characters from start index to end index with the replacement text
passed in s.
public int getRows()- It returns the number of rows in the textArea.
Ex:-

import java.awt.*;
import java.applet.*;
import java.applet.awt.*;
/*<applet code=TextAreaDemo width=300 height=400></applet>*/
public class TextAreaDemo extends Applet implements ActionListener

95 | O O P S T h r o u g h J a v a - G R K

{
TextField name,pss;
public void init()
{
Label namep=new Label(Name=, Label.RIGHT);
Label passp=new Label(PASSWORD=, Label.RIGHT);
name=new TextField (12);
pass=new TextField(8);
pass.setEchochat(*);
add(namep);
add(pssp);
add(name);
add(pass);
String str=There are two methods+one is concrete method.\n + other is abstract
method.\n;
TextArea t1=new TextArea(str, 50, 50);
Add(t1);
name.addActionListener(this);
pass.addActionListener(this);
}
public void actioPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString(Name: +name.getText(), 10, 100);
g.drawString(Select text : +name.getSelected Text(0, 10,100);
g.drawString(PASSWORD: +pass.getText(), 10,140);

96 | O O P S T h r o u g h J a v a - G R K

}
}
OUTPUT:-

Name:

JA VA

********

There are
two methods

Name :Java
Selected : VA
Password: 12312312

LAYOUT MANGERS
The AWT components are placed in containers. Each container has a layout manger
to arrange the AWT components within the container
The AWT provides Five Layout Managers.
1. FLOW LAYOUT
2. GRID LAYOUT
3. GRIDBAG LAYOUT
4. BORDER LAYOUT
5. CARD LAYOUT
The layout managers are defined by implementing the Layout manager interface. The
common methods are add() and remove(-. Use the add() method to add a component to a
container and the remove() method to remove a component form the container.
The Syntax to set the layout manager is
c.setLayout(new specific Layout());
The component c is a container, such as Frame, Panel or applet and specificLayout ()
is one of the five java layout managers.
FLOW LAYOUT:-

97 | O O P S T h r o u g h J a v a - G R K

It implements simple layout style. A small is left between each componet, above and
below as well as left and right.

The Constructors for Flow Layout are


FlowLayout()-

It centers components and leaves 5 pixels of space between each


component.

FlowLayout(int how)- It specifies how each component is arranged and a default gap of 5
pixels for both horizontal and vertical
The constant values for alignment(how) are
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
FlowLayout (int how, it horz, int vert)-

It specifies alignment, horizontal gap and vertical

gap. The gaps are distances in pixels between components.

BORDER LAYOUT:This class implements a common layout style for top-level windows. It has four narrow,
fixed-width components at the edges and one large area in the centre.
The four sides are referred to as north, south, east and west. The middle area is called
the center.

The constructors are


BorderLayout ()-

it constructs a new BorderLayout without horizontal of vertical gaps

BorderLayout(int hGap, int vGap)- It constructs a new BorderLayout with the specified
horizontal and vertical gaps between the components.
BorderLayout defines the following constants
BrderLayout.CENTER
BrderLayout.EAST
BrderLayout.NORTH
BrderLayout.SOUTH
BrderLayout.WEST
Ex:-

import java.awt.*;
import java.applet.*;
import java.util.*;

98 | O O P S T h r o u g h J a v a - G R K

/*<applet code=BorderDemo width=400 height=400></applet>*/


public class BorderDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button(This is across top), BorderLayout.NORTH);
add(new Button(This Botton Messgae), BorderLayout.SOUTH);
add(new Button(RIGHT), BorderLayout.EAST);
add(new Button(LEFT), BorderLayout.WEST);
String msg=There ae different + types of components\n + They are \n + Buttons
\n + Check boxes;
add (new TextArea(msg), BorderLayout.CENTER);
}
}

OUTPUT:-

Applet

This is across top

Left

There are different


types of
components. They
are buttons

__
Right

The footer message

GRID LAYOUT:It lays components in a two-dimensional grid. When we instantiate a GridLayout we


define the number of rows and columns.

99 | O O P S T h r o u g h J a v a - G R K

The components are placed in the grid from left to right starting with the first row then
the second and so on, in the order in which they are added.

The constructors are


GriLayout()

single-column grid layout

GridLayout( int rows, int columns)-

it creates new GridLayout with the specified number of


rows and columns

GridLayout(int rows, int columns, int hGap, int vGap)- it specifies horizontal and vertical gaps
between components.
Es:-

import java.awt.*;
import java.applet.*;
/*<applet code=GridDemo width=300 height=400></applet>*/
public class GridDemo extends Applet
{
static Final int n=4;
public void init()
setLayout(newGridLayout(n,n)0;
setFont(new Font(scanserif, Font.BOLD,20));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int k=i*n+j;
if(k>0)
add(new Button( +k));
}
}

}
}
OUTPUT:-

100 | O O P S T h r o u g h J a v a - G R K

Applet

__

10

11

12

13

14

15

4
8

101 | O O P S T h r o u g h J a v a - G R K

FILES AND STREAMS


A file is a collection of related records placed in a particular area on the disk. A record is
composed of several fields and a field is a group of characters. Characters in java are Unicode
characters composed of two bytes, each byte containing 8 binary digits, 1 or 0 storing and managing
data using files is known as file processing which includes tasks such as creating files, updating files
and manipulation of data. The process of reading and writing objects is called object serialization.
Record may be represented as a class object in java.

JAVA

100

72

ORACLE

200

160

Marks Field

File(3 Records)
C

150

Name Field

JAVA

100

140

Total Field

Record (3 Fields)

72

Field (4 Characters)

JAVA

0010 1100
Byte

1001 0011
Byte

Unicode Characters

DATA REPRESENTATION IN JAVA FILES

STREAMS:
A stream is an object that takes information from one source and sends it to another. There are
two kinds of streams
INPUT STREAMS:
OUTPUT STREAMS:

Which read data from source


Which write data to a destination

Source
102 | O O P S T h r o u g h J a v a - G R K

reads
Program

INPUT STREAMS

writes
Destination
Program
OUTPUT STREAMS

STREAM CLASSES :The java.io.package contains a large number of stream classes that provide capabilities for
processing all types of data. They are classified into two groups.

1.

Byte stream classes

2.

Character stream classes

BYTE STREAM CLASSES:


They are designed to provide functional features for creating and manipulation streams and
files for reading and writing bytes. There are two kinds of byte stream classes.
1. Input stream classes
2. Output stream classes

INPUT STREAM CLASSES :The input stream class defines methods for performing input functions such as

Reading bytes

Classing streams

Marking positions in streams

Skipping ahead in a stream

Finding the number of bytes in a stream

Methods

Description

read()

if reads a byte from input stream

read (byte b[])

reads an array of bytes into b

read(byte b[], int n, int m)

reads m bytes into b starting from nth byte

available()

gives total number of bytes available in input

skip()

skips over n bytes from input stream

103 | O O P S T h r o u g h J a v a - G R K

reset()

get backs to beginning of stream

close()

closes the input stream

OUTPUT STREAM CLASSES:They are derived from the base class output stream. If includes methods to perform the
following tasks such as
1. Writing bytes
2. Closing streams
FILE CLASS:The java.io.package includes a class known as the file class that provides support for creating
files. This class includes several methods for supporting the operations such as
1. Creating a file
2. Opening a file
3. Closing a file
4. Deletion a file
5. Getting the name of a file
6. Renaming a file
CREATION OF FILES :If we want to create and use a disk file, we need to decide the following about the file and its
intended purpose.

Suitable name for the file

Data type to be stored

Purpose (reading, writing or updating)

Method of creating a file


A filename is a unique string of characters that helps identify a file on the disk. The length of the

filename and the characters allowed are dependent upon the operating system on which java program
is executed.
Data type is important to decide the type of file stream classes to be used for handling the data
i.e. whether data to be handled in characters or bytes.
The purpose of using a file must also be decided before using if. We should know whether the
file is created for reading only or writing only or both the operations.
For using a file it must be opened first. This is done by creating a file stream and then linking it
to the filename.
A file stream can be defined using the classes of reader/input stream for reading data and
writer/output stream for writing data.

104 | O O P S T h r o u g h J a v a - G R K

TEST.DAT

FIS
STREAM OBJECT

FILE NAME

FIS

STREAM OBJECT

INFILE

FILE OBJECT

FileInputStream fis= new FileInputStream(test.dat)


File infile;
Infile=new File(test.dat);
Fis=new FileInputstream(infile);

READING/WRITING FILES:import java.io.*;


class FileWriterDemo
{
public static void main(String s[])
{
try
{
File riter Fw=new FileWriter(s[0]);
for (int i =0;i<10;i++)
{
Fw.write(Line +i+ \n)
}
Fw.close();
}
catch(Exception e)
{

105 | O O P S T h r o u g h J a v a - G R K

TEST.DAT

FILE NAME

}
It accepts one command line argument that is the name of the file to be created 10 strings are
written to the file by using write() method of file writer.
import java.io.*;
class FileReaderDemo {
public static void main(String s[]) {
try {
FileReader Fw=new FileReader (s[0]);
int i;
while ( (i=Fr.read())!=-1) {
System.out.print((char)i);
}
Fr.close();
} catch(Exception e) {

}}
It reads one command-line argument that is the name of the file to read.
> java FileWriterDemo out.txt

line 0

> java FileReaderDemo out.txt

line 1.line 9

READING/WRITING BYTES:We have used File Reader and File Writer classes to read and write 16-bit characters. Two
commonly used classes for handling bytes are File Input Stream and File Output Stream classes.

Writing bytes to a file


import java.io.*;
class Write Byte S {
public static void main(String s[]) {
byte cities[]={J, A, V,A, \n, O,R,A,C,L,E,\n,H,T,M,L,\n};
FileOutputStream outfile;
try {
outfile=new File Output Stream(city.txt);
outfile.write(cities);
outfile.close();
} catch(IOException ioe) { }

106 | O O P S T h r o u g h J a v a - G R K

}} }

> type city.txt


JAVA
ORACLE
HTML

READING BYTES FROM A FILE


import java.io.*;
class ReadBytes {
public static void main(String s[]) {
FileInputStream infile;
int b;
try {
infile = new File Input Stream(s[0]);
while((b=infile.read())!=-1)
System.out.print((char)b);
infile.close();
} catch(IOException ioe) { }
} }

> java ReadBytes city.txt


JAVA
ORACLE
HTML

RANDOM ACCES FILES:So for we have seen files that can be used either for read only or for write only operations
and not for both purposes simultaneously. These files are read or written only sequentially and
therefore are known as sequential files.

107 | O O P S T h r o u g h J a v a - G R K

Random Access file class supported by the java.io.package allows us to create files that can be
used for reading and writing data with random access.
A file can be created and opened for random access by giving a mode string as a parameter to
the constructor when we open the file. The mode strings are
r For Reading only.
rw For both reading and writing.
Random Access files support a pointer known as the file pointer that can be moved to the
arbitrary position in the file prior to reading or writing. The file pointer is moved using the method see().

The syntax is
File=new RandomAccessFile(filename.dat, rw);
The file pointer is automatically positioned at the beginning of the file.
READING/WRITING USING A RANDOM ACCESSFILE:import java.io.*;
class RandomDemo {
public static void main(String s[]) {
RandomAccessFile file=null;
try {
file=new RandomAccessFile(rand.dat,rw);
file.writeChar(J );
file.writeInt(5555);
file.writeDouble(1.414);
file.seek(0);
System.out.println(file.readChar( ));
System.out.println(file.writeInt());
System.out.println(file.writeDouble());
file.seek(0);
System.out.println(file.readInt();
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close()

108 | O O P S T h r o u g h J a v a - G R K

} catch(IOException e) { }
} }

OUTPUT
J
5555
1.414
5555
False

HANDLING PRIMITIVE DATA TYPES


The basic input and output streams provide read/write methods that can only be used for
reading/writing bytes or characters. If we want to read/write the primitive data types such as Integers
and doubles we can use Filter classes in existing input and output streams to filter data in the original
stream. The two Filter classes used for creating data streams for handling primitive types are
DataInputStream and DataOutputStream.

The commonly used methods are


writeShort()

readShort()

writeInt()

readInt()

writeLong()

readLong()

writeFloat()

readFloat()

writeDouble()

readDouble()

writeChar()

readChar()

writeBoolean()

readBoolean()

readLine()

fis

dis

Prim.dat

program

fos
109 | O O P S T h r o u g h J a v a - G R K

dos

screen

READING AND WRITING PRIMITIVE DATA


import java.io.*;
class HandPrimData
{
public static void main(String s[])throws IOException
{
File p=new File(prim.dat);
FileOutputStream Fos = new FileOutputStream(p);
DataOutputStream Dos=new DataOutputStream(Fos);
dos.writeInt(2000);
dos.writeDouble(159.628);
dos.writeBoolean(true);
dos.writeChar(A);
dos.close();
Fos.close();
FileOutputStream fis=new FileOutputStream(p);
DataOutputStream dis=new DataOutputStream(Fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar();
dis.close();
fis.clsoe();
} }
write a java program that copies first 34th of a.txt file to b.txt and last 1/4th to c.txt file
import java.io.*;
class Filecopy {
public static void main(String s[])throws IOException {
FileInputStream fis= new FileInputStream(a.txt);
FileOutputStream fos1=new FileOutputStream(b.txt);

110 | O O P S T h r o u g h J a v a - G R K

FileOutputStream fos2=new FileOutputStream(c.txt);


int Fs=fis.available();
int size = int (Fs*0.75);
int k,i=0;
while((d=fis.read())!=-1) {
if( i < size)
fos1.write(k);
else
fos2.write(k);
i++;
}
fos2.close();
fos1.close();
fis.close();
} }
Write a program that will count the number of characters, Number of words and lines in the file.
import java.io.*;
public class FileRead
{
public static void main(String s[])throws IOException
{
FileInputStream fis=new FileInputStream(a.java);
DataInputStream dis=new DataInputStream(fis);
String str=null;
int words=0;
int chars=0;
int lines=0;
while((str=dis.readline())!=null) {
lines++;
chars+=str.length();
for(int i=0;i<str.length();i++) {

111 | O O P S T h r o u g h J a v a - G R K

if(str.charAt(i)== )
words++;
} }
System.out.println(No of Characters : +chars);
System.out.println(No of Words : +words);
System.out.println(No of Lines : +lines);
} }

112 | O O P S T h r o u g h J a v a - G R K

NETWORKING
The java.net package contains classes that allow us to build distributed applications.
INTERNET ADDRESS:
An Internet address ia a 32-bit quantity that identifies a machine connected to the Internet. It is
commonly expressed as a sequence of four numbers separated from each other by periods.
An Internet address may also be expressed as a sequence of tokens separated from each
other by periods.
This format is significantly easier for users to remember and communicate. The Domain Name
System(DNS) translates an Internet address in dotted string format to a dotted decimal format.
The class INetAddress in the java.net package encapsulates an Internet address.
Ex:

127.0.01
www.yahoo.com

SERVER SOCKETS AND SOCKETS:

A Socket is one end of a bidirectional communication path

between two machines. It provides a mechanism for two applications to obtain reliable, sequenced
data exchange.
Sockets use the Transmission control protocol(TCP) in addition to the Internet Protocol(IP). The
ServerSocket class is used to build a server application. It listens for incoming requests form clients.
The following is one of the constructor
ServerSocket(int port)

throws IOException

Here, port is the software port on which it listens for incoming client requests.
The accept( ) method listens for an incoming requests from a client. It waits until a request
arrives. The syntax of this method is
Socket accept( ) throws IOException
The accept( ) method returns a Socket object. This object is used to communicate with the client.
We can close a ServerSocket with close( ) method.
void close( ) throws IOException
SOCKET:The Socket Class is used to exchange data between a client and a server. The Constructor is
Socket( String HostName, int port ) throws UnKnownHostException, IOException
Here, HostName is the name of the server. This may be either a dotted string or a dotted decimal
address. The parameter port indicates the software port on the server to which this socket should
connect.

113 | O O P S T h r o u g h J a v a - G R K

After a Socket is created, a program must then obtain input and output streams to
communicate. The getInputStream( ) and getOutputStream( ) methods are used to communicate. The
Signatures are
InputStream getInputStream( ) throws IOException
outputStream getOutputStream( ) throws IOException
The InputStream and OutputStream objects are then typically used to create DataInputStream
and DataOutputStream objects respectively.
We may close a Socket via the close( ) method
void close( ) throws IOException
SERVER / CLIENT APPLICATION

Server Program
import java.io.*;
import java.net.*;
import java.util.*;

class ServerSocketDemo
{
public static void main(String args9[])
{
try {
int port =Integer.parseInt(args[0]);
Random r=new Random( );
ServerSocket ss= new ServerSocket(port);
While(true){
Socket s=ss.accept();
OutputStream os=s.getOutputStream( );
DataInputStream dos=new DataInputStream(os);
Dos.writeInt(r.nextInt( ));
s.close( );
}
}catch(Exception e){ }
}

114 | O O P S T h r o u g h J a v a - G R K

Client Program
import java.io.*;
import java.net.*;

class SocketDemo
{
public static void main(String args[ ]) throws Exception
{
String server=s[0] ;
int port =Integer.parseInt(args[1 ]);
Socket s=new Socket(server, port);
InputStream is=s.getInputStream( );
DataInputStream dis=new DataInputStream(is);
int i=dis.readInt( );
System.out.println(i);
s.close( );
}
}

java SocketDemo 127.0.0.1 2000

DATABASE CONNECTIVITY
Open DataBase Connectivity(ODBC):-

115 | O O P S T h r o u g h J a v a - G R K

It is a windows technology that lets a database client application connect to a external


database. To use ODBC, the database vendor must provide an ODBC driver for data access. Once
that Driver is available, the client machine should be configured with this driver. The destination of the
database, login id and password is also to be configured on every client machine. This is called as
Data Source Name
ODBC is composed of 3 parts. They are

A Driver Manager

One or More Drivers

One or More Data Sources

CREATING AN ODBC DATA SOURCE:

The DSN is used whenever a reference is made to an ODBC Database. To setup ODBC

Start

Control Panel

Select ODBC DataSource(32bit) and Double Click it


o

A list of ODBC Data Sources is displayed

Select Add button to add a new ODBC Data Source Name.

A list of ODBC Drivers available in the system are displayed.

Select the Microsoft ODBC driver for oracle

Oracle DSN Config Dialog box is displayed. Enter Data Source Name and press OK

DATA BASE SYSTEMS:


A Database is an integrated collection of data. A database system involves the data itself, the
hardware on which the data resides, the software that controls the storage and retrieval of data and the
users themselves.
ADVANTAGES OF DATABASE SYSTEMS:

Redundancy can be reduced

Inconsistency can be avoided

The Data can be shared

Standards can be enforced

Security restrictions can be applied

116 | O O P S T h r o u g h J a v a - G R K

Integrity can be maintained

Conflicting requirements can be balanced

STRUCTURE OF DATA BASE:

117 | O O P S T h r o u g h J a v a - G R K

JAVA DATABASE CONNECTIVITY (JDBC)


It is mainly consists of
1. Connection
2. Statement
3. Resultset
CONNECTION
Connection c = DriverManager.getConnection(URL, UserName, Password)
url = (jdbc:odbc:dsn_name)
username= soctt
password= tiger
STATEMENT
Statement s = c.createStatement( );
RESULTSET
Resultset r = s.executeQuery(query);
Query = select * from emp;
We should import java.sql.* for jdbc programs
import java.sql.*;
import java.io.*;
import java.util.*;
class AbcDemo

public static void main(String args[])


{
try {
Class.ForName ( sun.jdbc.odbc.JdbcOdbcDriver );
Connection c = DriverManager.getConnection ( jdbc : odbc : abc , scott , tiger );
Statement s = c.createStatement( );
Resultset r = s.executeQuery( select * from emp);
While ( r.next( )== true)
System.out.println(r.getInt(1)+ +r.getString(2));
DataInputStream dis = new DataInputStream(System.in);
System.out.println(Enter Roll No);

118 | O O P S T h r o u g h J a v a - G R K

int i= Integer.parseInt(dis.readLine( ));


System.out.println(Enter Name :);
String n = dis.readLine( );
String q= insert into emp values(+ i + , + n + ) ;
s.execute(q);
}
catch(Exception e) { }
} }

119 | O O P S T h r o u g h J a v a - G R K

SERVLETS
A server could dynamically construct a page by creating a separate process to handle each
client request. The process would open connections to one or more databases in order to obtain the
necessary information. The client communicates with the web server via an interface known as the
Common Gateway Interface(CGI). CGI allowed the separate process to read data from the HTTP
request and write data to the HTTP response.
A variety of different languages were used to build CGI programs. They are C,C++ and Perl

Disadvantages of CGI :

They are not platform independent.

It was expensive to open and close database connections for each client request.

It was expensive in terms of processor and memory resources to create a separate process for
each client request.

So they developed a technique called servlets.

Advantages of Servlets:

They are platform independent because they are written in java.

Performance is better. It is not necessary to create a separate process to handle each client
request.

It enforces a set of restrictions to protect the resources on a server machine.

It communicates with applets, databases or other softwares via sockets and RMI mechanisms.

Life Cycle of a Servlet:


There are 3 methods in a Life Cycle of a Servlet
1. init ()
2. service ()
3. destroy ()
They are implemented by every servlet and are invoked at specific times by the server.
First, a user enters a URL to a web browser. The web browser generates an HTTP request for
this URL and sends to appropriate server.
Second, HTTP request is received by web server. It maps the request to a particular servlet.
The servlet is dynamically retrieved and loaded into the address space of the server.
Third, the server invokes the init () method of the servlet. If is invoked only when the servlet is
first loaded into the memory.

120 | O O P S T h r o u g h J a v a - G R K

Fourth, the server invokes the service () method of the servlet. It is called to process the HTTP
request. If formulates an HTTP response for the client.
The servlet remains in severs address space and is available to process any other HTTP
requests received form clients.
The service () method is called for each HTTP request. Finally, the server may decide to unload
the servlet from its memory. Then the server calls the destroy () method.
The servlet package define two abstract classes that implement the interface servlet.
GenericServlet (javax.servlet)
HttpServlet (javax.servlet.http)
The key method in every servlet is method service (), which receives both a Servlet Request
Object and a Servlet Response Object. These objects provide access to input and output streams that
allow the servlet to read data from the client and send data to the client.
SERVLETS ARCHITECTURE:Servlets are framed to implement the request/response pattern. When a browser sends a
request to the server, the server may forward the request to a servlet. A servlet is a software working
inside the server itself. The servlet process the request access the database and constructs an
appropriate response that is returned to the client in HTML format sevlet container is the context area in
which all servlet of the server works.

.
A simple java program becomes a sevlet when it extends either Generic Servlet of its subclass
HTTP servlet.
A servlet contains a service () method, which is called by the server automatically when a
request is made by the client.
All the classes and interfaces required to create and execute servlets are contained within two
packages.
javax.servlet and javaz.servlet.http
The most commonly used classes are:

HttpServlet class

GenericServlet class

Servlet Request interface

HttpServletRequest interface

ServletResponse interface

HttpServletResponse interface

121 | O O P S T h r o u g h J a v a - G R K

A SMALL PROGRAM WHICH DISPLAYS A MESSAGE


import javax.servlet.*;
import javax.sevlet.http.*;
import java.io.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest Req, ServletResponse res)throws ServletException, IOException
{
res.setContentType(text/html);
Str
Print Stream ps=new Print Stream(res.getOutputStream());
ps.println(Hello!Java);
ps.close();
}
}
The HTTP header in the response indicated the type of the content. The multipurpose Internet
Mail Extension (MIME) are use for this purpose.
Ordinary ASCII text has a MIME type of text/plain HTML source code of a webpage has a
MIME type of text/html.

122 | O O P S T h r o u g h J a v a - G R K

REMOTE METHOD INVOCATION (RMI)


RMI enables the programmer to create distributed java-to-java application, in which the
methods of remote java objects can be invoked from other java virtual machines, possible in different
systems.
A java program can make a call in a remote object once it obtains a reference to the remote
object either by looking provided by RMI or by receiving the reference as an argument.

TYPES OF APPLICATIONS:MONOLITHIC APPLICATIONS:These applications are single binary modules. General applications in C or C++ are monolithic.
If there is ac change source code must be changed, changed module should be compiled, the whole
program should be linked again.

.exe files
COMPONENT BASED APPLICATIONS:It will have a set of components which are integrated together to form the application. It is
possible to change a specific component without changing the other components. It is implemented
through Dynamic binding. It allows us to change the functions without effecting other components.
DISTRIBUTED APPLICATIONS:The components will reside on different machines in the network and have a well established
form of communication between them. This can be easily achieved with RMI interface provided by java.

Advantages of RMI:OBJECT ORIENTED:-

It pass full objects as arguments and return values

MOBILE BEHAVIOUR:-

RMI can move behaviour (class implementations) from client


to server and server to client.

SAFE AND SECURE:-

RMI uses built-in java security mechanism that allows the


system to be safe when user downloads a implementation.

EASY TO WRITE/EASY TO USE-

RMI makes it simple to write remote java, servers and java


clients that access those servers.

WRITE ONCE, RUN ANY WHERE


PARALLEL COMPUTING:-

RMI is multi-threaded allowing servers for better concurrent


processing of client requests.

RMI ARCHITECTURE:The RMI system consists of three layers

123 | O O P S T h r o u g h J a v a - G R K

1. The stub/skeleton Layer


2. The Remote Reference Layer
3. The Transport Layer
THE STUB/SKELETON LAYER:A STUB for a remote object is the client-side entity for the remote object. It is responsible for

Initiating a call to remote object

Informing remote Reference Layer that the call should be invoked

Informing remote reference Layer that the call is complete


A SKELETON for a remote object is a server-side entity that contains a method which

dispatches calls to

Setting up connection to remote address

Managing connections

Listening for incoming requests

Maintaining a table of remote objects that reside in the address space

Setting up response

PROCEDURE TO WRITE RMI PROGRAM:1. Write the interface class, Implementation class, object Binding class and Client classes
and compile all the classes.
2. Place the interface class extending remote on the server and the client
3. Place the implementation class extending remote object on the server
4. Generate stubs and skeletons on the server by running rmic (RMI complier)
5. Copy stubs to the client
6. Start bootstrap registry service on the server
7. Start a program that creates and register objects of the implementation class on the
server
8. Run the program that looks up server objects and invoke remote methods on the client.
A SIMPLE RMI EXAMPLE

Interface program:import java.rmi.*;


public interface Hello extends Remote
{
public string Disp() throws RemoteException;

124 | O O P S T h r o u g h J a v a - G R K

Implementation Program:import java.rmi.*;


import java.rmi.server.*;
public class HelloImpl extends UnicastRemoteObject implements Hello
{
public HelloImpi()throws RemoteException
{
super();
}
public string Disp()throws RemoteException
{
returnHell!Java;
}
}

Server Program:import java.rmi.*;


import java.net.*;
public class ServerDemo
{
public static void main(String s[])throws RemoteException
{
HelloImp1 h1=new HelloImp1();
Try
{
Naming.rebind(My server, h1);
}
catch(Exception e) { }
System.out.println(Waiting for Client Request);
}

125 | O O P S T h r o u g h J a v a - G R K

Client Program:import java.rmi.*;


import java.net.*;
public class ClientDemo
{
public static void main(String s[])
{
System.setSecurityManager(new RMI SecurityManager());
Try
Hello h2=new (Hello)Naming.lookup(Myserver);
System.out.println(h2.Disp());
}
catch(Exception e) { }
}
}

Procedure for executing the above example:1. Compile all

classes files
i. A interface file
ii. Implementation file
iii. Server file
iv. Client file

2. Create the stub and skeleton classes using rmic compiler rmic implementation file
3. rmic HelloImp1

4. Copy the below classes to the


CLIENT SIDE

SERVER SIDE

5. Interface class

126 | O O P S T h r o u g h J a v a - G R K

interface class

6. Stub class

implementation class

7. Client class

skeleton class

8.

Server class

9. Start the rmi registry


10. Execute the server that is binding remote object
11. Execute the client and observe the output
RMI REGISTRY:RMI registry keeps a track of the addresses of remote objects that are being exported by their
applications. All objects are assigned unique names that are used to identify them server registers one
of its objects with a registry by calling a bind () or rebind () method on a registry instance, passing it a
sting parameter that uniquely identifies.
Registry is checked whenever client passes a reference object. If an object by a same name is
already registered with the registry, an exception Already Bound Exception is thrown. To avoid this use
rebind () method which will not throw an exception by replacing the earlier one with the present one.

TCP/IP PROTOCOLS:A client can establish connection with the server through a socket. There are two kinds of TCP sockets
in java. one is for sever, and the other is for clients.
Server Socket
Socket
A socket class uses TCP/IP protocol the service it provides is connection-oriented service i.e. the data
delivery to the destination is guaranteed.
Uniform Resource Locator (URL):URL is an address of a system on the internet.
A URL has two main components
1. Protocol Identifier
2. Resource Name
Ex:- http://yahoo.com\

http stands for Hypertext Transfer Protocol that is to be used to search for the resource
yahoo.com on Internet.

Protocol and resource names are separated by a can and two forward slashes.

Writing a port number in the URL is optional

127 | O O P S T h r o u g h J a v a - G R K

CREATING AN URL:URL object embeds an internet site and an URL object can be created as
URL u1=new URL(http:\\Rediff.com\);

URL constructor is overloaded and each constructor throws a checked exception, Malformed
URL Exception.

URL class provides several methods to get data from an URL object. They are
o

getProtocol ()

getHost ()

URL class is defined in java.net package. It has several constructors.

URL (String Url specifier)

URL (String Protocol Name, String Host Name, int Port, String path)

URL(String Protocol Name, String Host Name, String path)

128 | O O P S T h r o u g h J a v a - G R K

JAVA DOCUMENTATION
Java supports three types of comments. The first two are // and /* */.

The Third type is

called a documentation comment. It will begin with the character sequence /**. It ends with a */.
Documentation comments allow us to embed information about our program into the program
itself.
We can then use the javadoc utility program to extract the information and put it into an HTML
file.

The javadoc tags

Tag

Meaning

129 | O O P S T h r o u g h J a v a - G R K

Você também pode gostar