If you can't read please download the document
Upload
sumanthreddy
View
11
Download
1
Embed Size (px)
DESCRIPTION
Java complete Reference
Citation preview
1 | O O P S T h r o u g h J a v a- G R K
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.
2 | O O P S T h r o u g h J a v a- G R K
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 CLASSES DATA
OBJECTS : 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
3 | O O P S T h r o u g h J a v a- G R K
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.
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. It is associated with Polymorphism and
Inheritance.
Ex 2:
Addition of two Integers
Concatenation of two strings
Ex 1: Shape Draw()
Circle Object Box Object Triangle Object Hexagon Object
Draw(Circle) Draw(Box) Draw(Triangle) Draw(Hexagon)
4 | O O P S T h r o u g h J a v a- G R K
2. INTRODUCTION TO JAVA
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.
Simple Object Oriented Distributed Interpreted
Secured Portable High Performance Multithreaded
5 | O O P S T h r o u g h J a v a- G R K
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
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.
6 | O O P S T h r o u g h J a v a- G R K
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
{
main method definition
}
Essential
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
7 | O O P S T h r o u g h J a v a- G R K
A first simple program: /* This is a simple java program */
class example { public static void main(String args[ ]) { } }
/* 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 ;
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 .class extension.
Java is case sensitive language.
8 | O O P S T h r o u g h J a v a- G R K
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.
-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
All keywords are to be written in lower case letters.
abstract case else float if int protected static try Boolean continue extends for implements interface public super throw break catch default import long switch throws void byte char do final native package return synchronized transient volatile class double finally instanceof new private short this while The following are the VALUES defined by java null false true
9 | O O P S T h r o u g h J a v a- G R K
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.
10 | O O P S T h r o u g h J a v a- G R K
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
Ex : 123, 345, -89, 0
Octal Integer 0 to 7
Ex : 0123, 0345, -089
Hexadecimal Integer
0 to 9,A,B,C,D,E,F
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
Mantissa E Exponent
Or
JAVA CONSTANTS
NUMERIC CONSTANTS CHARACTER CONSTANTS
INTEGER
CONSTANTS
REAL
CONSTANTS
CHARACTER
CONSTANTS
STRING
CONSTANTS
11 | O O P S T h r o u g h J a v a- G R K
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:
Java supports some special backslash character constants that are used in output methods.
Some of them are ---
\ blank space \ tab \ new line \
single quote \ Double quote \ 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.
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 & ! ^ ~ > >>>
12 | 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 a/b (decimal truncated)
Real Arithmetic : It involves only real operations
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 1
Conditional Operators: The character pair ? : is a ternary operator available in java.
Expression1? Statement1 : Statement2
Ex : a=15; b=56; x=(a>b) ? a : b ;
Special Operators: Java supports special operators such as instanceof and ( . )
instanceof: This operator allows us to determine whether the object belongs to a particular
class or not. Ex: s1 instanceof student;
Dot Operator: 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; Ex: x=a*b+c;
Precedence of Arithmetic Operators: 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
13 | 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 1
( ) Function call
[ ] Array element reference
Operator Description Associativity Rank
- Unary minus Right to left 2
++ Increment
-- Decrement
! Logical negation
~ Ones Complement
(type) Casting
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Substraction
> Right shift
>>> Right shift with zero fill
< Less than Left to right 6
Greater than
>= Greater than or equal to
14 | 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 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| 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.
15 | 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, Post-
Increment, Pre-Decrement, Post-Decrement, Method call and Allocation
Expressions.
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.
JAVA STATEMENTS
EXPRESSION
STATEMENTS
LABELLED
STATEMENTS
CONTRONL
STATEMENTS
SYNCHRONIZATION
STATEMENTS GUARDING
STATEMENTS
SELECTION
STATEMENTS
ITERATION
STATEMENTS
JUMP
STATEMENTS
IF
IF ELSE
SWITCH CASE
WHILE
DO
FOR
BREAK
CONTINUE
RETURN
16 | 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 16 ) which is known as UNICODE character
set.
char 2 bytes
17 | O O P S T h r o u g h J a v a- G R K
BOOLEAN TYPE:
It is used to test a particular condition during the execution of the program. It takes
only two values : true or false
boolean 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
Ex: int x, y, z=10;
GIVING VALUES TO VARIABLES:
DATA TYPES
PRIMITIVE (INTRINSIC) NONPRIMITIVE (DERIVED)
NUMERIC CLASSES INTERFACES ARRAYS
BOOLEAN CHARACTER
TYPES
FLOATING POINT INTEGER
TYPES
NON NUMERIC
TYPES
18 | 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: The general form of assignment is
VariableName = value ; Ex: count=10 ;
It is possible to assign a value to a variable at the time of its declaration.
type name = value ;
Ex: int count=0 ;
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 {
n=Integer.parseInt(dis.readLine( ));
19 | 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) { }
}
}
20 | 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 if statement may be implemented in different forms depending on the complexity
of conditions.
Simple if statement
statement
Nested
statement
Else if ladder
SIMPLE IF STATEMENT
The general form of a
simple if statement is
If ( test condition)
{statement block; }
statement x;
If the test
expression is true, the
statement-block will be
executed, otherwise
the statement block
will be skipped and the
execution will jump to
the statement x.
Ex : if (radium >=
0)
Test Condition
Statement block
Next Statement
FALSE
TRUE
Next Statement
FLOW CHART OF SIMPLE IF STATEMENT
Test Condition
True block stmts
Next Statement
FALSE TRUE
FLOW CHART OF SIMPLE STATEMENT
False block stmts
21 | O O P S T h r o u g h J a v a- G R K
{ area = radius * radius *(22/7); }
:
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
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)
22 | O O P S T h r o u g h J a v a- G R K
} else
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)
Test condition I
Statement 1
Statement 3
FALSE TRUE
Statement 2
FLOW CHART OF SIMPLE STATEMENT
Test condition 2
FALSE TRUE
Statement 1
23 | O O P S T h r o u g h J a v a- G R K
statement N;
Ex: if (marks > 79)
else if (marks > 59)
else if (marks > 49)
else if (marks > 39)
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: block 4; break;
default : 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)
{
:
:
24 | O O P S T h r o u g h J a v a- G R K
:
Default :
}
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
TEST CONDITIONS
BODY
OF
THE LOOP
FALSE
TRUE
ENTRY
ENTRY CONTROL
LOOP
BODY
OF
THE LOOP
FALSE
TRUE
ENTRY
TEST CONDITIONS
EXIT CONTROL
LOOP
25 | O O P S T h r o u g h J a v a- G R K
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.
When the condition becomes false, the loop will be terminated. Since the test
rolled 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:
Do
{
Body of the loop
} while (test condition)
For ( initialization ; condition ; increment / decrement )
{ Body of loop }
26 | O O P S T h r o u g h J 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
27 | 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 {
c++;
sum=sum+c;
if (sum==5) break;
}
while ( c < 5)
}}
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)
}
}
LABELLED LOOPS:
Output:
The sum is 15
Output:
The sum is 13
28 | O O P S T h r o u g h J a v a- G R K
Output:
*
* *
* * *
* * * *
* * * * *
. . . . . . . . . .
* * * * * * * *
*
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
29 | O O P S T h r o u g h J a v a- G R K
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 :
30 | 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:
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.
}
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
31 | 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 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 ;
}
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.
32 | 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[ ])
{
}
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[ ])
{
S
33 | 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) diff = - diff;
} while ( diff >= 0.001);
return nextGuess ;
} }
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. The Fibonacci series begins with two is in
succession. 1 1 2 3 5 8 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]);
OUTPUT:
N.G DIFF L.G
5 4 5
3.4 -1.6 3.4
3.0235 -0.3765 3.0235
3.0 -0.0235 3.0
3.0 0 3.0
34 | 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);
}}
One or more base classes (Simplest cases) are used to stop recursion.
Every recursive call reduces the original problem into a base case.
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 )
35 | 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
Location
access
Modifier
Public Protected Default Private protected private
Same class Yes Yes Yes Yes Yes
Subclass in same package Yes Yes Yes Yes
Other classes in same
package
Yes Yes Yes
Subclass in other package Yes Yes Yes
Non-subclasses in
other package
Yes
36 | O O P S T h r o u g h J a v a- G R K
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.
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( );
Object
Data Field 1
Data Field 2
37 | 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:
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:
Class TestClass {
Public static void main( String args[]) {
Circle mycircle=new Circle( );
System.out.println(The radius is
+mycircle.r);
System.out.println(The area is
+mycircle.area( ));
} }
class Circle
{
double r=20.0;
double area( ) {
return( r*r*3.1415);
}
}
38 | O O P S T h r o u g h J a v a- G R K
OVERLOADING CONSTRUCTORS
The name of the constructor will be same but have different parameters. Ex:
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);
}
}
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 1 is
+vol);
vol = b2.volume( );
System.out.println(Volume of Box 2 is
+vol);
vol = b3.volume( );
System.out.println(Volume of Box 3 is
+vol);
} }
39 | O O P S T h r o u g h J a v a- G R K
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)
Defining a subclass:
The class derived form the super class is called the subclass. The syntax of sub class
class subclass name extends superclassname
{
variables declaration;
methods declaration;
}
A
B
A B
C
A
B C D
B
C
A
Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance
40 | 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);
}
}
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);
}
}
41 | O O P S T h r o u g h J a v a- G R K
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);
} }
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
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:
43 | O O P S T h r o u g h J a v a- G R K
INTERFACES MULTIPLE INHERITANCE
Classes in Java can not have more than one
superclass. Java provides an alternate approach
know as Inheritance
to support the
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;
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;
}
Ex: interface Area {
Final static float pie=3.1415;
float compute (float x, float y);
void show( );
}
44 | 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
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.
IMPLEMENTING 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( );
}}
Interface_name1 extends name1 {
body of name 2
}
Ex:
Interface ItemConstants {
int n=100;
String name=Java;
}
interface Item extends ItemConstants {
void display( );
}
45 | 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
{
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
46 | 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;
}
47 | 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.
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
be implemented.
Public void run( )
{
Class A
{
.
}
Begin
Body
End
Single Threaded Program
--------------------
-
------------------
Main Thread
Start Start
Thread A Thread B Thread B
----------
----------
-
----------
----------
-
Multi Threaded Program
48 | 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( );
49 | 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:
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( ).
Class A extends Thread {
public void run( ) {
for (int i=0;i
50 | 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.
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
Born
Runnable
Running
Suspend Sleep Dead Wait
start ( )
notify( )
yield ( )
Assign to processor
resume ( ) sleep
interval
expires
51 | 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. M
priority
52 | O O P S T h r o u g h J a v a- G R K
Example:
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
Class A extends Thread
{
public void run( ) {
for ( int i=1; i
53 | 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.
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( )
{ ------
54 | 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
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
55 | O O P S T h r o u g h J a v a- G R K
}
} }
class RunnableTest {
public static void main(Sting as[]) {
A a=new A()
Thread t=new Thread(a);
t.start();
} }
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);
56 | 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.
57 | 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
}
58 | 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
59 | 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.
60 | O O P S T h r o u g h J a v a- G R K
Throwable
Exception
Error
ClassNotFoundE
CloneNotFound
NoSuchMethod
Instantiation
IO
Interrupted
NoSuchField
RunTimeException
Assertion
ThreadDeath
VirtualMachine
Linkage
ClassCirularity
ClassFormat
ExceptionIniInitialize
ThreadDeath
tANoSuchMethod
ngNoSuchField e
NInCompatibleClassChange
oCExceptionIniInitializeVirtual
Machine
UNoClassDefFound
Verify
UnSatisfiedLink
Internal
OutOfMemory
StackOverFlow
UStackOverFlow
nOutOfMemory
knInternal
own
Arithmetic
ArrayStore
ClassCast
IllegalArgument
IllegalMonitorState
IllegalState
IndexOutOfBound
NegativeArraySIze
NullPointer
Security
UnSupportedOperation
IllegalThreadState
NumberFormat
ArrayIndexOutOfBound
StringIndexOutOfBound
Illegalccess
61 | O O P S T h r o u g h J a v a- G R K
Ex:
Class Multicatch{
Public static void main(String args[]){
Try{
Int a=args.length();
Int b=42/a;
Int c[]={2,3};
C[3]=99;
}
catch(ArithmeticException ae){
}
catch(ArrayIndexOutOfBoundsException e){
}
}
}
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:
62 | 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,
63 | 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;
Try
{
if (a==1)
a=a/(a-a);
if (a==20
{
int c[]={1,2,3};
c[5]=100;
}
} catch(ArrayIndexOutBoundsException e)
{
}
}
catch(ArithmeticException e)
{
64 | O O P S T h r o u g h J a v a- G R K
System.out.println(
}
}
}
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
65 | O O P S T h r o u g h J a v a- G R K
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.
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.
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
66 | O O P S T h r o u g h J a v a- G R K
FINALLY BLOCK:
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 f
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:
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);
} final ly {
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
67 | O O P S T h r o u g h J a v a- G R K
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) {
class FinalBlockDemo {
static void porcA( ) {
try {
System.out.println(Inside Proc A);
throw new RuntimeException(demo);
} finally
{
System.out.println(Proc As finally);
} }
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;
} }
public static void main(Sting args[]) {
try {
procA( );
} catch(Exception e)
{
System.out.println(Exception
caught);
}
procB( );
procC( );
}
}
output
inside procA
Proc As finally
Exception caught
inside procB
Proc Bs finally
inside procC
Proc Cs finally
68 | 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 {
} }
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.
69 | 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
70 | 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
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.
java
lang util io awt net applet
71 | 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
public class
{
-
--
}
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
72 | 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 packa