Java Complete Material New
Java Complete Material New
objects and then build Data and Methods around these entities.
The Combination of Data and Methods make up an object.
OBJECT = DATA + METHODS
Data Structures are designed such that they characterize the objects.
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
Applications of OOPs
Hyper text.
CAD System.
OOP is a new way of organizing code and data that gives increased control over the
complexity of software development process.
INHERITENCE
POLYMORPHISM
DATA ABSTRACTION
Abstraction refers to the act of representing essential features without including the
background details or explanation.
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
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
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.
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:
+
+
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
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:
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 :
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:
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:
A java application can play a sound file, while prompting the user for input. It
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 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 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 requires that the functions with no arguments must be declares with empty
parenthesis and not with the void keyword as done 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.
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()
Documentation Section
Suggestible
Package Statement
Optional
Import Statements
Optional
Interface Statements
Optional
Class Definitions
Optional
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
//
/* ..*/
/** ..*/
Documentation Comment
Package Statement :
The
first
statement
statement.
This
Ex : package student ;
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.
.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
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
if
Boolean
interface
catch
throws
final
transient
instanceof
while
IDENTIFIERS :
Identifiers are programmer designed tokens.
They can have alphabets, digits, underscore( _ ) and Dollar sign ($) characters.
Uppercase and lowercase letters are distinct as java is case sensitive language.
A variable for a data type name cannot be used for another data type.
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.
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
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.
0 to 9
JAVA CONSTANTS
CHARACTER CONSTANTS
0 to 7
INTEGER
CONSTANTS
REAL
CONSTANTS
CHARACTER
CONSTANTS
STRING
CONSTANTS
These numbers are shown in decimal notation, having a whole number followed
215 X 10 23
215E23 or 215e23
215 X 10 -23
215-E23 or 215e-23
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
\r
blank space
\t
tab
\n
new line
single quote
Double quote
\f
form feed
carriage return
\\
back slash
The
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
+=
-=
--
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 :
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 :
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
x=(a>b) ? a : b ;
class or not.
Dot Operator:
a=15; b=56;
Ex:
s1 instanceof student;
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
* / %
Low Priority
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
[]
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
>>>
<
Less than
Left to right
<=
>
Greater than
>=
13 | O O P S T h r o u g h J a v a - G R K
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( )-
Braces { }
Brackets [ ]
Semicolon ;
Period .
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
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
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.
int x, y, z=10;
char c1,c2=A,c3;
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 ;
Ex: count=10 ;
Ch=A ;
int count=0 ;
char = % ;
READ STATEMENT:
We may also give values to variables interactively through the keyboard.
1. As command line arguments.
2. Using readLine( ) method
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( ));
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
otherwise
Next Statement
if (radium >=
0)
20 | O O P S T h r o u g h J a v a - G R K
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)
else
System.out.println( Negative number not allowed);
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
else
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
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:
value 1:
block 1;
break;
case
value 2:
block 2;
break;
case
value 3:
block 3;
break;
case
value 4:
default :
block 4;
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
23 | O O P S T h r o u g h J a v a - G R K
case C
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..
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
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.
Do
{
Body of the loop
}
while (test condition)
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)
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); }
Ex:
for (i = 0 ; i < 10 ; i ++ )
{
for (j = 0 ; j < 10 ; j ++ )
Inner
loop
Outer
loop
}
}
This keyword only ends the current iteration. Program control goes to
the next cycle of the loop
class TestBreak
{
26 | O O P S T h r o u g h J a v a - G R K
Output:
The sum is 15
c++;
sum=sum+c;
if (sum==5) break;
}
while ( c < 5)
class TestContinue
{
c++;
if (c==2) continue
sum=sum+c;
}
while ( c < 5)
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
{
28 | O O P S T h r o u g h J a v a - G R K
Output:
*
**
***
****
*****
..........
********
*
METHODS
METHOD :
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:
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:
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:
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
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
{
while ( n>0)
{
System.out.prinln(msg);
n--;
}}}
Java passes the value of x to n
31 | O O P S T h r o u g h J a v a - G R K
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
{
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
{
}}
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;
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:
succession.
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 ;
where n > 2
{
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)
{
}}
OUTPUT:
If n is 5 the series number is 5
Fib ( 5 ) = fib ( 4 ) + fib ( 3 )
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 :
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
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
These
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;
36 | O O P S T h r o u g h J a v a - G R K
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.
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( );
}
}
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( );
}
}
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.
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).
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 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
This keyword allows one constructors to explicitly invoke another constructor in the
same class
this(args)
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);
}
}
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.
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
Main Thread
Start
-----------------
-------------------
-------------------
Thread A
Thread B
Thread B
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
run( ) method.
By converting a class to a Thread Define a class that implements runnable interface.
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 ThreadTest
{
public static void main(String args[])
{
new A( ).start( );
B b=new B( );
b.start( );
}
}
suspend ( )
wait ( )
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
Born
start ( )
Runnable
sleep
interval
expires
resume ( )
Assign to processor
notify( )
yield ( )
Wait
Running
Sleep
Dead
Suspend
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.
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
51 | O O P S T h r o u g h J a v a - G R K
Example:
A:
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
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()
{--------------}
}
}
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.
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
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
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.
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
58 | O O P S T h r o u g h J a v a - G R K
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.
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);
}
}
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.
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
output
java NestTry
divide by zero : java.lang.ArithmeticException
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;
} }
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);
}}
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:
66 | O O P S T h r o u g h J a v a - G R K
class FinalBlockDemo {
procB( );
procC( );
}
}
output
inside procA
Proc As finally
Exception caught
inside procB
Proc Bs finally
inside procC
Proc Cs finally
Public Exception( )
takes no arguments
Ex:
System.out.println(e.getmessage());
e.kprintStacktrace();
} }
output
68 | O O P S T h r o u g h J a v a - G R K
Ex:
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
lang
util
io
awt
net
applet
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 :
Java.io:
Java.awt:
It contains set of classes for implementing GUI. They include classes for
windows, buttons, menus and so on.
Java.net :
Java.applet:
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
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;
}
the package p1 contains one public class by name A. suppose we want to add another class
B to this package.
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
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;
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.
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.
75 | O O P S T h r o u g h J a v a - G R K
}}
The applet class name is the main class for the applet.
Running state
Idle 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
------
------
}
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.
79 | O O P S T h r o u g h J a v a - G R K
addKeyListener( )
addMouseMotionListener( )
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
component.
public void mouseClicked (MouseEvent e) //MouseListener
------
by a MousePressed event.
public void MouseEntered (MouseEvent e)
------
It is called when the mouse button is pressed and the mouse is moved.
It is called when the mouse is moved with the Mouse cursor on 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
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
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
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:-
Ascent:-
Descent:-
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
Label.RIGHT,
Lable.CENTER
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
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
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
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
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.add(wn NT);
os.add(Solaris);
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()
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
Textfield(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
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.
specifies
the
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.
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)-
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.
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
OUTPUT:-
Applet
Left
__
Right
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.
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
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
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:
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.
2.
INPUT STREAM CLASSES :The input stream class defines methods for performing input functions such as
Reading bytes
Classing streams
Methods
Description
read()
available()
skip()
103 | O O P S T h r o u g h J a v a - G R K
reset()
close()
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.
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
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
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.
106 | O O P S T h r o u g h J a v a - G R K
}} }
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
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
110 | O O P S T h r o u g h J a v a - G R K
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
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( );
}
}
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
A Driver Manager
The DSN is used whenever a reference is made to an ODBC Database. To setup ODBC
Start
Control Panel
Oracle DSN Config Dialog box is displayed. Enter Data Source Name and press OK
116 | O O P S T h r o u g h J a v a - G R K
117 | O O P S T h r o u g h J a v a - G R K
118 | O O P S T h r o u g h J a v a - G R K
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 :
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.
Advantages of Servlets:
Performance is better. It is not necessary to create a separate process to handle each client
request.
It communicates with applets, databases or other softwares via sockets and RMI mechanisms.
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
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
122 | O O P S T h r o u g h J a v a - G R K
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.
MOBILE BEHAVIOUR:-
123 | O O P S T h r o u g h J a v a - G R K
dispatches calls to
Managing connections
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
124 | O O P S T h r o u g h J a v a - G R K
125 | O O P S T h r o u g h J a v a - G R K
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
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
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.
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 (String Protocol Name, String Host Name, int Port, 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 /* */.
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.
Tag
Meaning
129 | O O P S T h r o u g h J a v a - G R K