Вы находитесь на странице: 1из 88

Compiled By:

Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Object Oriented Paradigm:


The Major objective of object oriented approach is to eliminate some of the flaws
encountered in the procedure oriented programming. OOP treat data as critical component
and it combines data and its related function into a single unit called Object Only Methods of
object can access data. Some of the features of object oriented paradigm are
1. Programs are divided into Objects.
2. Data is hidden and cannot be accessed by external functions.
3. Follows bottom up approach in program design.
4. Data and its related functions are tied together.
5. Primary focus is on data.
6. Object may communicate with each other through methods.
Basic Concepts of Object Oriented Programming :
Object & Classes:
Objects are the basic runtime entities in an object oriented system. They may represent a
student, course, fee, attendance etc. An object takes up space in the memory and has an
associated memory address. When a program is executed, the objects interact by sending
messages to one another. For example student and course are two objects in student
information system, then the student object may send a message to the fee object requesting
for the balance fee.
Objects contain data and methods to manipulate that data. A class may be considered user
defined data type and an object as a variable of that data type. So class is collection of
objects of similar type. For example Mango, apple and orange are objects of fruit class.

Student Object

Rno , Name, Fname, Course_id Data


Address, city, mobile, email

newAdmission( )
updateCourse( ) Methods
updateAddress()

Page 1 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Data Abstarction and Encapsulation:
The combination of data and methods into a single unit (called class) is known as
encapsulation. By this process data is not accessible to outside world only methods
combined with data can access it. So methods provide an interface between the data and the
program. This insulation of the data from direct access by the program is called data hiding.
Abstraction means representing essential features without including the background details
or explanations. For example when we driver change the gear of a car internal function of
gear change is irrelevant from driver point of view.
Inheritance:
Inheritance is the process by which we create new classes called
subclasses from existing class called super class. By this process
subclass inherits all properties of its super class. In OOP inheritance
provides the idea of reusability. This means that we can additional
features to an existing class without modifying it.
Person

PId, Name, Fname,


Qual, DOB, Address

add( ), update( )

Employee

Designation, basic
pay, hra, da

Polymorphism:
Polymorphism means the ability to take more than one forms. For example consider the
operation of addition for two numbers operation will generate sum( 1+1=2 ) and for two
strings generate third string( “1” + ”1” = ”11” ). Figure given below describes that a single
function name can be used to handle different number and different types of arguments.

Shape

draw(Page
) 2 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Circle
Square
draw( radius )
draw(side)
Benefits of OOP:
OOP offers several benefits to both the programmer and the user. The main benefits are as
under:
1) Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2) The principal of data hiding helps the programmer to build secure programs.
3) It is possible to have multiple objects to coexist without any interference.
4) It is easy to partition the work in a project based on objects.
5) Object oriented system can be easily upgraded from small to large systems.
6) Software complexity can be easily managed.
Applications of OOP:
The most popular application of object oriented programming, up to now, has been in the
area of user interface design such as windows. The promising areas for application of OOP
includes
1) Real Time Systems
2) Simulation and modeling.
3) Object oriented databases.
4) AI and expert systems.
5) Decision support and office automation systems.
6) CIM/ CAD system.
Java History:
Java is a general purpose, object oriented programming language developed by Sun
Microsystems of USA in 1991. Originally called Oak , java was designed for the
development of software for consumer electronic devices like TVs, toasters. The java team

Page 3 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


discovered that the existing languages like C and C++ had limitations in terms of reliability
and portability. So they modelled their new language java on C and C++ but removed a
number of features of C and C++ and thus made java a really simple, reliable, portable and
powerful language.
Java Features:
Java language provide following features
1. Platform Independent and Portable:
Platform independent means Java programs can be easily moved from one computer
system to another, anywhere and anytime. Changes and upgrades in operating systems,
processors and system resources will not force any change in java program.
Java ensures portability in two ways. First java compiler generates bytecode
instructions that can be implemented on any machine. Secondly the size of the
primitive data types is machine independent.
2. Object Oriented:
Java is a true object-oriented language. Almost everything in Java is an object.All
program code and data reside within objects.
3. Roubst and Secure:
Java is a robust language which provides following safeguard to ensure reliable code
a) Strict compile time and run time checking for data types.
b) Automatic garbage collector.
c) Java includes exception handling.
Java is a secure language due to following
a) The absence of pointers in java ensures that program s cannot access to memory
locations without proper authorization.
b) Java ensures that no viruses are communicated with applet.

4. Distributed:
Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and program. Java applications can access remote objects
on internet.

Page 4 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


5. Simple, Small and Familiar:
Many features of C and C++ that are source of unreliable code like pointers,
preprocessor header files, goto statement ,operator overloading and multiple
inheritance are eliminated from java.
6. Multithreaded:
Java supports multithreaded programming. Multithreaded means a program is divided
into two or more subprograms or threads that are executed at the same time in parallel.
7. Compiled and Interpreted:
Usually a computer language is either compiled or interpreted. Java combines both
approaches. First java compiler translates source code into bytecode, in the second
stage java interpreter converts bytecode into machine language.
8. High Performance:
According to Sun Microsystems, java speed is comparable to C/C++. Further the
incorporation of multithreading enhances the overall execution speed of java program.
How Java Differs From C and C++:
Java and C:
1. Java does not contain the data types struct and union.
2. Java does not define the type modifier keywords auto, extern, register, signed and
unsigned.
3. Java does not support pointer.
4. Java does not have a preprocessor.
5. Java adds labeled break and continue statements.
6. Java adds many features required for object oriented programming.
Java and C++:
1. Java does not support operator overloading.
2. Java does not have template classes as in C++.
3. Java does not support multiple inheritances of classes.
4. Java does not support global variables.
5. Java does not use pointers.
6. There are no header files in java.
Java and Internet:

Page 5 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Java is strongly associated with the internet because first application program written in java
was HotJava. HotJava, a Web browser to run applets on internet. Internet user can use java
to create applet programs and run them locally using a “Java enabled browser” such as
HotJava.
Internet users can also setup their web sites containing java applets that could be used by
other remote users of internet.
Java and World Wide Web:
World Wide Web contains web pages that provide both information and controls. Web
system is open ended and we can navigate in any direction. Web pages contain HTML tags
that enable us to find, manipulate and display documents worldwide. Before java the World
Wide Web was limited to display still images and texts. However with the help of java we
can include animation, graphics, games and wide range of effects in web pages. Java
communicates with a web page through a special tag called <APPLET>.
Web Browsers:
Web browsers allow us to retrieve the information spread across the internet and display it
using the hypertext markup language (HTML). Example of Web browser among others
includes:
1) Hot Java :
Hot java is a web browser from Sun Microsystems that enable display of interactive
content on the web, using the Java language. HotJava is written entirely in java.
2) Netscape Navigator:
Netscape Navigator from Netscape Communications Corporation is a general purpose
browser that can run java applets.
3) Internet Explorer:
Internet explorer is another popular browser developed by Microsoft for Windows 95,
NT, XP and Windows 7 workstations.

Page 6 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Comments in Java:
Java permits both single line comments and multi line comments available in C++. The
single line comment begins with // and end at the end of line. Multiline comment starting
with a /* and ending with a /*. For Example a program with two classes and different type of
comment is shown below.
/* Program with two classes
Author: Aryabhatta Group*/
class A
{ void show( )
{ System.out.println(“Class A”);}
}
class B
{ public static void main(String args[ ])
{ System.out.println(“Hello”);} // display Hello
}
Java Program Structure:
A java program may contain one or more sections as shown in figure
below
Documentation Section Suggested

Package Statement Optional

Import statements Optional

Optional
Interface statements

Class Definitions Optional

Main Method Class


{ Main Method Definition} Essential

Page 7 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

1. Document Section:
Document section includes comment lines giving the name of the program, the author and
other details.
2. Package Section:
First statement allowed in a java file is a package statement which informs the compiler
that the class defined here belongs to this package. Package statement is optional.
3. Import Statements:
This is similar to the #include statement in C. Using import statements we can use classes
that are part of other packages. This is also an optional section.
4. Interface Statement:
An interface is like a class but include a group of method declarations. This is also an
optional section.
5. Class Definitions:
A java program may contain multiple class definitions. Classes are primary and essential
elements of a java program.
6. Main Method Class:
Since every program execution starts from main method so this class is the essential part
of a java program.
Java Virtual Machine:
Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is called the Java Virtual Machine and it exists only inside the computer
memory.
Java interpreter converts this bytecode into machine code. So java interpreter act as an
intermediary between the virtual machine and the real machine.

Java Program Java Compiler Virtual Machine


(Bytecode)

Bytecode Java Interpreter Machine Code

Page 8 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Java Tokens:
Smallest individual units in a program are known as tokens. The compiler recognizes them
for building up expressions and statements.
Java language includes five types of tokens. They are:
a) Reserve Keywords
b) Identifiers
c) Literals
d) Operators
e) Separators
Keywords:
The keywords are also called reserved words. Keywords has specific meaning in java, we
cannot use them as names for variables, methods, classes, interfaces and so on. Java
language has 50 keywords. For example

byte if private throws catch


short switch public case default
int for protected finally char
long while abstract new implements
float do class static void
double break extends this
boolean continue import try

Identifiers:
Identifiers are used for naming variables, methods, classes, objects, labels, packages and
interfaces in a program. Java identifiers must enforce following rules
a) They can have alphabets (a to z), digits (0 to 9), and underscore.
sal1 Valid
sal# Invalid (# is not a valid character)
b) They must not begin with a digit.
sal1 Valid
_sal1 Valid
Page 9 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


1sal Invalid (Start from digit)
c) Uppercase and lowercase letters are distinct
class ABC
{ public static void main( String args[ ] )
{ int a=2;
System.out.println(A) ;
}
}
O/P- This program generates compile error: Undefined Variable A because in our program
we have declared variable with name a not A.
d) Keywords cannot be used as identifiers.
int float invalid (float is a keyword)
Constants/Literals:
Constant is one that has a fixed value throughout the program. Constants are assigned to
variables in a program. Java language specifies five major types of literals.
1) Integer literals:
Integer numeric constant have integer data combination of 0-9 without any decimal
point.
2) Floating Point literals:
Floating point constant have data combination of 0-9 with decimal point. It may have
positive or negative values. It is also called Real number constant.
3) Character Literals:
Character constant contains only single character from alphanumeric character sets.
This single character is written in single quotation marks.
For example: ‘a’, ‘A’, ‘2’
4) String literals:
This type of constant contains more than one character in it. It contains multiple
characters according to our requirements. These characters are written in double
quotation marks. For example:
“Welcome to Aryabhatta”
5) Boolean literals:

Page 10 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


This type of constant contains only true or false.
Escape Sequence / Backslash Character Constant:
This type of constant contains some characters for some special purposes. Following are
some of the backslash character constants. These are also known as Escape sequences.

Escape Purpose
Sequence

\b Backspace

\f Form feed

\n New line

\t Tab

\\ Backslash

\’ Single quotation mark

\” Double quote

Separators or Punctuators:
These are symbols used for grouping and separating code. They are also known as separators
or Delimiters. Separators are given below
 Parentheses ()
 Braces { }
 Brackets [ ]
 Semicolon (;)
 Comma (,)
 Period (.) etc.

Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may take different values during the execution of program. Variable must be
declared befor use.

Data Types:
Page 11 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Data types are used to declare variables. Variable declaration tells us
1) Type of value a variable can hold
2) Name of variable
3) Range
Primary or Scalar Data type: it is used for representing a single value only. Scalar data
type is further divided into four types
1. Integer types
2. Floating types
3. Character types
4. Boolean types
Integer types:
Integer type can store integer constant i.e. numerical value without decimal points.
Numerical value can be positive as well as negative. It supports 4 types of integers as
shown in table
Type Size Range

byte 1 byts -128 to 127

short 2 bytes -32768 to 32767

int 4 bytes -2 31 to 2 31-1

long 8 bytes -263 to 2 63 -1

Floating Point Types:


Floating data type can store real constants i.e. numerical value with decimal points. Values
can be positive as well as negative.
The float type values are single precision numbers while the double types represent double
precision numbers. Double precision types are used when we need greater precision in
storage of floating point numbers.

Type Size

Page 12 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Float 4 bytes

Double 8 bytes

Character Type:
Character data type can hold only a single alphabet (A-Z) or digit (0-9) or special symbol.
The character data type assumes a size of two bytes. It has been designed to hold 16 bit
Unicode.
Boolean Type:
There are only two values that a Boolean type can take: true or false. All comparison
operators return Boolean type values. The words true or false cannot be used as identifiers.
Mathematical Functions:
Java supports mathematical functions through Math class defined in the java.lang package.
The function should be used as follows:
Math.function_name()
For Example
Class MF1
{ public static void main( String args[ ] )
{ double x;
x=Math.max(22 , 33);
System.out.println(“ Maximum value= “ + x);
x=Math.pow(2,4);
System.out.println(“Power=”+x);
}
}
o/p is
Maximum value= 33
Power= 16

Page 13 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Java operators:
An operator is a symbol that tells the compiler to perform a certain mathematical or logical
manipulators. Java supports a rich set of operators. Java operators can be classified into following
categories:
1. Arithmetic operators :
Arithmetic operators are used for arithmetic operations like Addition, Subtraction,
Multiplication, and Division & Modulus. These can operate on any built in numeric type.
Arithmetic operators are binary operators because they required two operands. Following are
the list of Arithmetic Operators.

Operator Meaning

+ Addition

- Subtraction or unary minus

* Multiplication

/ Division

% Modulus division

class AO1
{
public static void main( String args[ ] )
{
int a=14, b=4;
System.out.println( a - b); //10
System.out.println( a * b); //56
System.out.println( a / b); //3(decimal truncated)
System.out.println( a % b); //2
}
}

Page 14 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Type Conversions:
When two operands of different types are encountered in the same expression java
automatically converts lower type variable into higher type variable but opposite not
possible.

double Highest order

float

long

int

short

byte (Lowest order)

E.g. 1. a = 1/2= 0 2. a = 1/2.0=0.5


Casting:
The term applies to the data conversions by the programmer as opposed to the automatic data
conversion. It is also known as explicit conversion.
E.g. a = 11/( int ) (5.0 ) =2
2. Increment/Decrement operator:
The ++ (increment) operator adds 1 to the operand and – (decrement) subtracts 1 from the
operand. Both are unary operators because they required single operand. These operators can
be used in two ways:
1. Prefix Increment/Decrement Operator: In this first of all value will be
incremented or decremented (according to operators ++ & --) and then that
new value will be assigned to a variable.
2. Postfix Increment/Decrement Operator: In this first of all value will be
assigned to a variable then it is incremented or decremented according to the
operator used.
//Program to explain Postfix and Prefix Increment Operator
class IDO1
{ public static void main ( String args [ ] )
{ int a=2, b=2, c, d;
Page 15 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


c= ++a;
d= b++;
System.out.println(“a = ”+a+”\tc = ”+c);
System.out.println(“b = ”+b+”\td = ”+d);
}
}
Output: a=3 c=3
b=3 d=2
3. Relational Operators:
The relational operators are symbols that are used to test the relation between two
expressions. These operators return true or false. Relational operators are binary operators
because they required two operands. There are mainly six types of relational operators.

Operator Meaning

== Equal to

> Greater than

< Less than

!= Not equal to

>= Greater than or equal to

<= Less than or equal to

class RO1
{ public static void main ( String args [ ] )
{ int a=5;
boolean result;
result=a > 2; //result=true

System.out.println( result);
if (a> 2)

Page 16 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


System.out.println(“ True”);
else
System.out.println (“False”);
}
}
4. Logical operators:
Logical operators are used to combine two or more relations. These are used in decision
making statement because they return true or false values only. There are mainly three types
of Logical Operators.

Operator Meaning

&& AND

|| OR

! NOT

class LO1
{ public static void main ( String args [ ] )
{ int a=5;
boolean result;
result=a > 2 && a<5; //result=false
System.out.println( result);
if (a> 2 && a<5)
System.out.println(“ True”);
else
System.out.println (“False”);
}
}
Truth Table of Logical AND and Logical OR Operators

A B A&&B A||B

false false false false


Page 17 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

false true false true

true false false true

true true true true

Truth Table of Logical NOT Operator

A !A

True False

False True

5. Bitwise Operators:
These operators are mainly used for the operation of Binary bits i.e. 0 and 1. So these are
mainly used for low level programming. Bitwise operations are the testing, setting or shifting
of the actual bit in a byte. These operators should not be of float or double type due to binary
version. There are mainly six Bitwise Operators.

Bitwise Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

<< Bitwise Left

>> Bitwise Right

~ One’s Complement

class BO1
{ public static void main ( String args [ ] )

Page 18 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{ int a=11, b=5,c;
c=a&b; // c =1
System.out.println ( “ a & b = “ + c);
c= a|b; // c =15
System.out.println ( “ a | b = “ + c);
c=a^b; // c =14
System.out.println ( “ a ^ b = “ + c);
c=a>>2; //c = 2
System.out.println ( “ a >> 2 = “ + c);
c=a<<2; // c = 44
System.out.println ( “ a << 2 = “ + c);
c=~a // cc= -12
System.out.println ( “ ~a = “ + c);
}
}
6. Assignment operator:
Assignment operators are used for assigning an expression or value to a variable. It is
the short hand symbol for arithmetic & bitwise operators. Assignment operators are
binary operators because they required two operands. Some of the commonly used
assignment operators are given below

Statement using Assignment Equivalent statement using


Operator arithmetic / bitwise operator

a+=1 a=a+1

a- =1 a=a-1

a*=5 a= a* 5

a\=5 a=a/5

a%=b a=a%b

a>>=2 a=a>>2

Page 19 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

a<<=2 a=a<<2

a&=2 a=a&2

a|=2 a=a|2

a^=2 a=a^2

class AO2
{ public static void main ( String args [ ] )
{ int a=11;
a &= 5 \
System.out.println ( a);
}
}
O/P= 1
7. Conditional operator or Ternary operator:
This operator is compressed version of if-else statement. This is called ternary operator
because it requires three operands. The syntax of the statement is
c= ( a > b) ? a: b;
This above statement returns the greatest number as a value of c variable i.e. if a is greater than b
then the value of a is assigned to c otherwise the value of b is assigned to c.
class TO1
{ public static void main(String args[ ])
{ int a=11,b=8,c;
c=( a > b) ? a : b;
System.out.println( c);
}
}
Precedence of operators:
In an expression operators with higher precedence are evaluated before lower precedence
operator. Operators having equal precedence are evaluated on the basis of associatively.

Page 20 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Desc. Operator Associatively

Higher ( ), [ ], . Left to right

-, ++, --, ~, ! Right to left


( Type ) casting

*,/,% Left to right

+- Left to right

<< ( left shift) Left to right


>> ( Right shift )

< ,<=, > , >= Left to right

==, != Left to right

& (Bitwise AND) Left to right

^ Bitwise XOR Left to right

| Bitwise OR Left to right

&& Left to right

|| Left to right

? : ( conditional operator) Right to left

= Right to left
Lower Shorthand assignment operator Right to left

Page 21 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Control Statements or Flow Controls:
A program consists of some statements which will execute in some sequiential manner but if
we want to override that flow of execution of statements then we need some type of flow
control Statements. So there are mainly three different categories to control the flow of
execution.
1. Branching
2. Looping
3. Jumping

1. Branching:
To override the sequential flow of execution branching is must. Branching must be done on
the basis of some condition. Java supports following control or decision making statements
1. If statement
2. switch statement
3. conditional operator statement
If statement:
“If statement” is used to control the flow of execution of statements. It is a two way decision
statement and used in conjunction with an expression. If statement is of further four types.
a) Simple If Statement:
Simple if statement is used for one way branching. The syntax of if statement is like
If (condition)
{true statement block;}
other statements;
In this type of statement condition will be checked. If condition is true then true statement
block will be executed and after that other statements block will be executed. If the condition
is false only other statements bock will be executed.
b) If-else Statement:
This statement is used for two way branching. The syntax of if statement is like:

if (condition)
{True Statement- block;}
Expressi else
on False {False Statement- block;}
? Statement – n;
True

Page 22 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


In this type of statement condition will be checked. If condition is true then true statement
block will be executed and after that statement - n block will be executed. If the condition is
false then the block of false statement will be executed and after that statement – n block will
be executed.
c) Nested If Statement: When one if statement occurs within another if statement then that
type of if statements are known as nested if statements. These statements are used to solve
some complex type of problems. The syntax of this statement is given below:
if(condition1)
{ if (condition2)
{Statement1;}
else
{Statement2;}
}
else
{Statement3;}
Statement – n;
}
In this type of statement condition1 will be checked. If condition1 is true then next
condition2 will be checked. If condition2 is true then Statement1 will be executed and
Statement – n will be executed and if condition2 will be false then Statement2 will be
executed and then Statement – n will be executed. If condition1 becomes false then
Statement3 will be executed and after that Statement – n will executed.
d) Ladder if-else statement:
This type of statement is used only when there are many numbers of conditions to be there to
check. The program showing the structure of this statement is given below:

Page 23 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

//Program to print the division of a student on the basis of following criteria:


Marks>=60 First
Marks>=50 AND Marks<60 Second
Marks>=40 AND Marks<50 Third
Marks<40 Fail
class Marks1
{ public static void main( String args [ ] )
{ int marks=45;
if(marks >=60)
System.out.println(”First”);
else
if(marks >=50)
System.out.println(”Second”);
else
if(marks >=40)
System.out.println (”Third”);
else
System.out.println(”Fail”);
}
}
2. Switch statement:
Switch statement is a multi way decision statement. 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 switch statement is as shown
below
Switch (expression)
{ case value1: block-1; break;
case value 2: block-2;break ;
default: default block;
}

Page 24 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

//Program to check if the given character is vowel


class Switch1
{ public static void main( String args [ ] )
{ char ch=’j’;
switch(ch)
{ case ‘A’ :
case ‘a’ : System.out.println(”Vowel”); break;
case ‘E’ :
case ‘e’ : System.out.println(”Vowel”); break;
case ‘I’ :
case ‘i’ : System.out.println(”Vowel”); break;
case ‘O’ :
case ‘o’ : System.out.println(”Vowel”); break;
case ‘U’ :
case ‘u’ : System.out.println(”Vowel”); break;
default : System.out.println(” Not Vowel”);
}
}
}
Conditional Operator (? :) :
Already Explained Above Page No-20

2. Looping:
Loops are used to repeat the some portion of a program either a specified number of times or
until a particular condition is being satisfied. Mainly loops are of two types. One is Entry
Controlled Loop and another is Exit Controlled Loop.
a) Entry Control Loop: In this type of loop firstly condition is checked if it is true then
body of the loop is executed otherwise body of the loop is not executed.

Page 25 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


b) Exit Control Loop: In this type of loop firstly body of the loop is executed then condition
is checked, now if condition is true then body executed again until the condition becomes
true otherwise the program goes out of the loop.
After the above types, there are three ways by which we can repeat a part of the program.
1. for statement
2. while statement
3. do-while statement
1. For loop:
For loop is an entry control loop. The general form of for statement is as under
for( initialization; test condition; modifier expression)
{
body of the loop;
}
The execution of for statement is as follows
Initialization: Initialization part executes only once at start of loop and it is used to initialize
control variable.
Test condition: If the condition is true, the body of the loop is executed; otherwise the loop
is terminated.
Modifier Expression: After executing the body of the loop the control transferred back to
for loop. Now modifier expression modify control variable.
class For1
{ public static void main( String args [ ] )
{ int i;
for( i=1;i<=5; i++)
System.out.println(” Welcome to Aryabhatta Group of Institutes”);
}
}
output: ‘Welcome to Aryabhatta Group of Institutes’ prints 5 times.

Page 26 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

class For2
{ public static void main( String args[] )
{ for( ; ; )
System.out.println(“Hello”);
}
}
Output: Hello infinite times.
2. While loop:
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 otherwise loop terminated. The
general form of while loop is as under:
initialization;
while( test condition)
{ Body of the loop; }
class While1
{ public static void main( String args[ ] )
{ int sum =0;
int n=1;
while (n<=5)
{ sum= sum+n ;
n++;
}
System.out.println (sum);
}
}
Output: 15

Page 27 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


3. Do-while statement:
Do While is an exit controlled loop statement. In this loop, first body of the loop is executed
and then the condition is checked. If condition is true, then the body of the loop is executed
otherwise loop terminated. In this statement body of loop executes at least once. The syntax
of this loop is:

initializations;
do
{ body of the loop; }
while ( test condition);}
class Do1
{ public static void main( String args[] )
{ int i=11;
do
{ System.out.println(”Hello”);
i++;
} while( i<=10);
}
}
Output: Hello
3. Jumping:
1. Break statement:
Break statement is used for an early exit from nearest loop .It is usually used with for loop,
do-while, while loops and in the switch statement.
class Break1
{ public static void main( String args [ ] )
{ int i=1;
for( i=1 ; i<=5 ; i++)

{ if(i==2)

Page 28 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


break;
System.out.println(i);
}
}
}
Output: 1

class Break2
{ public static void main( String args [ ] )
{ int i,j;
loop1: for( i=1 ; i<=5 ; i++)
{ for (j=1 ;j<=5;j++)
{ if( j==3)
break;
System.out.print(“*”);
}
System.out.println();
}
}
}
Output:
**
**
**
**
**

class Break3
{ public static void main( String args [ ] )
Page 29 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{ int i,j;
loop1: for( i=1 ; i<=5 ; i++)
{ for (j=1 ;j<=5;j++)
{ if( j==3)
break loop1;
System.out.print(“*”);
}
System.out.println();
}
}
}
Output:**
2. Continue statement
Continue statement causes the loop to continue with the next iteration without executing
remaining statements. It is usually used with for loop, do-while, while loops
class Continue1
{ public static void main( String args[] )
{ int i;
for(i=1;i<=10;i++)
{ if( i%2==0)
continue;
System.out.print( i+” ”);
}
}
}
Output: 1 3 5 7 9

Page 30 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Difference Between While & Do While:

SNo While Do While


1 While loop is entry controlled loop i.e Do while loop is exit controlled loop
the test condition is evaluated first and i.e. first body of the loop is executed
if the condition is true then the body of and then condition is checked
the loop is executed.
2 While loop will not execute any Do While loop executes at least once
statement if the condition is false
e.g. e.g.
class While11 class Do11
{ public static void main( String args[]) { public static void main( String args[])
{ int i=11; { int i=11;
while (i<=10) do
{ {
System.out.println( i); i++; System.out.println(i); i++;
} }
} while (i<=10);
} }
Output: Blank Screen }
Output: 11
3 Semi colon not required after while Semi colon required after while

Page 31 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Difference between Break & Continue:

Sno Break Continue


1 Break statement is used for an early exit Continue statement causes the loop to
from a loop. continue with the next iteration without
. executing remaining statements.
2 It is usually used with for loop, do- It is usually used with for loop, do-
while, while loops and in the switch while, while loops
statement.
e.g. e.g.
class Break11 class Break11
{ public static void main(String args[] ) { public static void main(String args[] )
{ int i; { int i;
for( i=1 ;i<=5;i++) for( i=1 ;i<=5;i++)
{ if(i==3) { if(i<3)
break; continue;
System.out.print(i); System.out.print(i);
} }
} }
} }
Output: 1 2 Output: 3 4 5

Page 32 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Defining a Class:
A class is a user defined data type with a template that serves to define its properties. Once
the class type has been defined, we can create variables of that type. These variables are
termed as instances of classes which are the actual objects. The basic form of class definition
is:
Class classname [extends superclassname]
{ [ fields declaration;]
[methods declaration;]
}
Everything inside the square brackets is optional.
For example
class Student
{ int rno;
String name,course;
int fee;
void setData( )
{ rno=0;
name=” ”;
course=””;
fee=0;
}
void setData( int r, String n, String c, int f)
{ rno=r;
name=n;
course=c;
fee=f;
}
void dispData()
{
System.out.println(rno + ”\t” + name + “\t” + course + “\t” + fee);

Page 33 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


}
}
class StudentDemo
{ public static void main( String args[])
{
Student s1=new Student( );
Student s2=new Student();
s1.setData( 1, “Kuldeep Singh”,”BCA”,14000);
s2.setData(2,”Aman Bansal”,”BBA”,14000);
s1.dispData();
s2.dispData();
}
}
Creating Objects : An object is a block of memory that contains space to store all the
instance variables. Creating an object is also referred to as instantiating an object. Objects in
java are created using the new operator. In the above example s1,s2 are the objects created
using new operator.
Constructors:
Constructor runs automatically when we create object of that class. Constructors initialized
object when it is created. Constructors are syntactically similar to method except that:
1. Constructor name must equal to class name in which it resides.
2. Constructors do not specify return type, not even void.
For Example
class Student
{ int rno;
String name,course;
int fee;
Student( )
{rno=0; name=” ”; course=””; fee=0; }
Student( int r, String n, String c, int f)

Page 34 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{rno=r; name=n; course=c; fee=f; }
void dispData()
{System.out.println(rno + ”\t” + name + “\t” + course + “\t” + fee); }
}
class StudentDemo
{ public static void main( String args[])
{
Student s1=new Student(1, “Kuldeep Singh”,”BCA”,14000 );
Student s2=new Student(2,”Aman Bansal”,”BBA”,14000);
s1.dispData();
s2.dispData();
}
}
Method overloading:
When a class has more than one method with same name but different parameters then it is
called method overloading. For example in above example Student constructor is
overloaded.
Types of Variables:
In java we have three types of variables
1. Local Variables
Variables declared inside the method are called local variables. Local variables can be
accessed only inside the method in which they declared.
2. Instance Variables
Instance variables are declared outside the method and each instance of the class
maintains their own copy of data.
3. Class/ Static Variables
Class variables are declared outside the method and each instance of the class share
same copy of data. One of the most common examples is count variable that could
keep a count of how many objects of a class have been created. For example
class Student
{ int rno;

Page 35 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


String name,course;
int fee;
static int count;
Student( )
{rno=0; name=” ”; course=””; fee=0;count++;}
Student( int rno, String n, String c, int f)
{this.rno=rno; name=n; course=c; fee=f; count++;}
void dispData()
{System.out.println(rno + ”\t” + name + “\t” + course + “\t” + fee); }
static void showCount( )
{ System.out.println(“Total Students=”+count);}
}
class StudentDemo
{ public static void main( String args[])
{ Student.showCount( );
Student s1=new Student(1, “Kuldeep Singh”,”BCA”,14000 );
Student s2=new Student(2,”Aman Bansal”,”BBA”,14000);
s1.dispData();
s2.dispData();
Student.showCount( );
}
}
Static/class Methods:
Like static variables static methods can be called without creating the object of the class.
Best example of static method is main () method. Static methods are called using class
names. Static methods have several restrictions
1. They can call only other static methods.
2. They can access only static data.
3. They cannot refer to this or super keyword.
This Keyword:
Page 36 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


This keyword is actually a pointer which points the object through which it is called.
Nesting of Methods:
A method can be called by another method of the same class. This is known as nesting of
methods. For example
class Nesting
{ int m,n;
Nesting( int x, int y)
{ m=x; n=y;}
boolean largest()
{ if (m > n)
return true;
else
return false;
}
void display()
{ System.out.println( “m=”+m);
System.out.println(“n=”+n);
System.out.println(“ m is greater than n:” + largest());
}
}

class NestingDemo
{ public static void main( String args[])
{ Nesting nest=new Nesting(50, 40);
nest.dispaly( );
}
}

Page 37 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Inheritance:
Inheritance is the process of creating new classes called derived class or sub class from an
old class called base class or super class. Inheritance allows subclass to inherit all the
variables and method of their super class. Inheritance may take different forms
 Single inheritance( only one super class, one subclass )
 Multiple inheritance( several super classes)
 Hierarchical inheritance( one super class, many subclasses )
 Multilevel inheritance (subclass from a subclass)

A A

B B C D

(Single inheritance) (Hierarchical inheritance)


A A B

B C

C
(Multilevel inheritance) ( Multiple inheritance)
In java multiple inheritances is not possible through classes but it is possible through
interfaces.
For example

class Student
{ int rno;
String name, course;
int fee;
Student ( ) { rno=fee=0; name=course=” ”;}
Student( int r, String n, String c, int f) {rno=r; name=n; course=c; fee=f;}
void dispData()
Page 38 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{System.out.println(rno+”\t”+name+”\t”+course+”\t”+fee);}
}
class Student1 extends Student
{ int mobile;
Student1( ) { super( ); mobile=0;}
Student1(int r, String n, String c, int f, int m) {super(r, n, c, f); mobile=m; }
void dispData( ) // Method Overriding
{ super.dispData( );
System.out.print( “\t” + mobile);
}
}
class Demo1
{ public static void main(String args[])
{ Student1 s1=new Student1 (1, “Kuldeep Singh”, “BCA”, 18000, 9781342925);
S1.display();
}
}
Method Overriding:
When a subclass has method with same name, same arguments and return type as a method
in the superclass. This is known as method overriding. Above example shows the concept of
method overriding. The method display () is overridden.
Super Keyword:
Subclass uses super keyword to invoke superclass constructor or method. The keyword super
is used with following restrictions
1. super may only be used within a subclass constructor or method.
2. The parameters in the super call must match the order and type of the instance
variables declared in the superclass.

Page 39 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Final Variables and Methods:


Final Variables:
The value of final variables can never be changed. Final variables behave like class variables
and they do not take any space for each object of the class.
class FinalDemo
{ public static void main( String args[])
{ final int a=5;
a=a+3; // Error : final variable can never be changed
System.out.println(a);
}
}
Final Methods:
All methods can be overridden by default in subclass. If we wish to prevent subclasses form
overriding the members of superclass we can declare them as final.
class A
{ final void show()
{ System.out.println( “Hello A”);}
}
class B extends A
{ void show ( ) // Error: Final methods cannot overridden
{ System.out.println( “Hello A”);}
}
Final Classes:
A class that cannot be subclassed is called final class. Declaring a class final prevents any
unwanted extension to the class for example
final class A
{}
class B extends A // Error: Final class cannot be subclassed
{}

Page 40 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Abstract Method and Classes:
Abstract methods are just opposite to final methods. Final method cannot be overridden in a
subclass while abstract method must be overridden in a subclass otherwise class contains
abstract method must be declared abstract.
When a class contains one or more abstract method, it should also be declared abstract.
While using abstract classes we must satisfy the following conditions
 We cannot use abstract classes to instantiate objects directly.
 The abstract method of abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.
class Shape
{ double dim1, dim2;
Shape( ) { dim1=dim2=0;}
Shape( double d1, double d2) { dim1=d1;dim2=d2; }
abstract double area( );
}
class Rectangle extends Shape
{ Rectangle() { super(); }
Rectangle(double d1,double d2) { super(d1,d2); }
double area( ) { return dim1*dim2; }
}
class Triangle extends Shape
{ Triangle() { super(); }
Triangle (double d1, double d2) { super(d1,d2); }
double area ( ) { return (dim1*dim2 / 2); }
}
class AbstractDemo
{ public static void main(String args[])
{ Rectangle r1=new Rectangle (10, 20);
Triangle t1=new Triangle (10, 20);
System.out.println (“Rectangle r1 area =” + r1.area ( ));

Page 41 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


System.out.println (“Triangle t1 area =” + t1.area ( ));
Shape s1=t1;
System.out.println (“Triangle t1 area =” + s1.area ( ));
s1=r1;
System.out.println (“Rectangle r1 area =” + s1.area ( ));
}
}
Dynamic Method Dispatch:
It is used to implement runtime polymorphism. In this mechanism method overriding is
resolved at runtime instead of compile time. In the above example, s1.area () call invokes the
subclass version of the method.
Array:
An array is a collection of related data items that share a common name. A particular value is
indicated by a number called index number or subscript in brackets after array name e.g.
salary [10]
Memory allocation to array is always contiguous. Like any other variables, array must be
declared and created in the computer memory before they are used.
In java, all array store the allocated size in a variable length.
class CountOdd
{ public static void main( String args[ ])
{ int a [ ]={ 55,40, 80, 65, 71};
int n= a.length, c=0;
for( int i=0; i<n; i++)
{ if (a[i] %2 ==1)
c++
}
System.out.println(“Total odd numbers:”+c);
}
}

Page 42 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Multidimensional Array:
Java treats multidimensional array as “arrays of arrays”. It is possible to declare a two-
dimensional array as follows
int x[][]=new int [3][4];
in java it is possible that each row has different length i.e. variable size array as shown below
int x[][]=new int [3][];
x[0]= new int [2];
x[1]= new int[4];
x[2]= new int[3];
class MulTable
{ public static void main( String args[])
{ int p[][]=new int[10][10];
System.out.println(“Multiplication Table”);
int i,j;
for( i=0; i<10; i++)
{ for(j=0; j<10; j++)
{ p[i][j]=(i+2)*(j+1);
System.out.print(“ “+ p[i][j]);
}
System.out.println(“ “);
}

}
}
Strings:
Strings represent a sequence of characters. In java string is an object of String class. Java
strings as compared to C strings are more reliable and predictable because C lacks bound
checking. A java array is not a character array and is not NULL terminated. Strings may be
decared and created as follows:
String firstName;

Page 43 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


firstName=new String(“Anil”);
String Methods:

Method Example Task performed

toLowerCase ( ) s2=s1.toLowerCase() Converts the string s1 to lowercase

toUpperCase ( ) s2= s1.toUpperCase() Converts the string s1 to uppercase

replace(char,char) s2=s1.replace(‘X’,’Y’) Replace all appearances of x with y

trim( ) s2=s1.trim() Remove white spaces at the beginning and end


of the string s1

equals( ) s1.equals(s2) Returns true if s1 is equal to s2

length( ) s1.length() Gives the length of s1

Interfaces:
An interface is basically a kind of class but with some major differences as under
1. In an interface by default all methods are abstract and public.
2. In an interface by default all fields are public and final.
Like classes, interfaces can also be extended. This can be obtained using the keyword
extends as shown below:
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
void display()
}

Page 44 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Difference between class and interface is given below

Sr No. Class Interface

1 Data members of a class can be Data members of interface are always declared
constant or variables. as constant.

2. Methods can be abstract or non- Methods in an interface are abstract by default.


abstract

3. Classes can be instantiated by Interfaces cannot be used to declare objects.


declaring objects.

4. It can use various access specifiers Interfaces can only use public access specifier.
like public, private or protected.

5. Multiple inheritance is not Multiple inheritance is possible through


possible through classes. interfaces.

interface Shape
{ double pie=3.14;
double area( );
}
class Rectangle implements Shape
{ double dim1,dim2;
Rectangle() { dim1=dim2=0;}
Rectangle(double d1, double d2) { dim1=d1;dim2=d2;}
public double area( ) { return dim1*dim2);}
}
class Circle implements Shape
{ double radius;
Circle ( ) {radius=0 ;}
Circle (double r) {radius=r ;}
double area( ) { return pie*radius*radius;}

Page 45 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


}
class InterfaceDemo
{ public static void main(String args[ ])
{ Rectangle r1=new Rectangle(10, 20);
Circle c1=new Circle(10);
System.out.println(r1.area());
System.out.println(c1.area());
Shape s1;
s1= r1; System.out.println(s1.area());
s1=c1; System.out.println(s1.area());
}
}
Packages:
Package is a collection of classes and interfaces of similar nature. By organizing classes and
interfaces into packages we get following benefits
1. The Classes contained in the packages can be easily reused.
2. In packages, classes can be unique compared with classes in other packages.
3. Packages provide a way to hide classes.
4. Packages also provide a way for separating design from coding.
There are two ways to accessing the classes stored in packages
1. Use fully qualified class name:
For example to access Color class in the java.awt package fully qualified name is
java.awt.Color
2. Using import statement:
Import statement must appear at the top of file, before any declaration. Import
statement is useful when we want use a class in number of places in the program. e.g.
import java.awt.Color;

Page 46 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Example:
C:\java\ptu>
package ptu;
class Hello
{ public static void main ( String args[])
{ System.out.println(“ Hello”);}
}

C:\java\ptu> javac Hello.java


C:\java> java ptu.Hello
Visibility Modifiers/ access modifiers:
The visibility modifiers are also called access modifiers. Java provides following types of
visibility modifiers which provides different level of protection as described below

private default protected Public

Within same Yes Yes Yes Yes


class

Subclass in same No Yes Yes Yes


package

Other classes in No Yes Yes Yes


same package

Subclass in No No Yes Yes


another package

Non subclass in No No No Yes


another package

Page 47 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Applet:
Applets are small java programs that are used in internet computing. They can be transported
over the internet from one computer to another and run using the Applet Viewer or any web
browser that supports java. An applet can perform arithmetic operation, display graphics,
play sounds, create animation and play interactive games. Applets are two types
1. Local Applets:
An applet developed locally and stored in a local system is known as local applet. To
access local applet web page does not require internet connection.
2. Remote Applet:
A remote applet is developed by someone else and stored on a remote computer
connected to internet. To access remote applet web page requires internet connection.
The difference between Applets and application programs is as under:
1. Applets do not use the main () method for initiating the execution of the code.
2. Applets cannot be run independently. They must be embedded in web page using
<applet> tag.
3. Applets cannot read or write to the files in the local computer.
4. Applets cannot communicate with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++.
Steps involved in developing and testing an applet are:
1. Building an applet code (.java file)
2. Creating an executable applet( .class file)
3. Embed applet in HTML file using applet tag
4. Testing the applet code
Building applet code:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{ public void paint(Graphics g)
{ g.drawString(“Hello Java”,10,100);}
}
Page 48 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Adding applet in HTML File:
<html>
<head>
<title>Welcome to Java Applets</title>
</head>
<body>
<center><h1>Welcome to the World of Applets</h1>
<BR>
<applet code=”HelloJava.class” width=400 height=200></applet>
</center></body></html>

Page 49 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Applet Life Cycle:


Applet during its life cycle enters many states. The applet state includes
 Born or initialization state
 Running State
 Idle State
 Dead or destroyed state
Initialization State:
Applet enters the initialization state when it is first loaded. This is achieved by calling init()
method of applet class. At this stage we can perform following tasks
 Create objects
 Setup initial Values
 Load images or fonts
 Set up colors
The initialization occurs only once in the applet life cycle. We may override the init method
public void init ()
{ ………….
………….
}
Running State:
Applet enters the running state when the system calls the start () method of Applet class. This
occurs automatically after the applet is initialized. Starting can also occurs if the applet is
already in idle state and we return back to the page. We may override the start method
public void start ()
{ ………….
………….
}

Page 50 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Idle or Stopped State:


An applet enters the idle state when we leave the page containing the currently running
applet. We can also do so by calling the stop() method. We can achieve this by overriding the
stop () method.
public void stop ()
{ ………….
………….
}
Dead State:
An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking destroy () method when we quit the browser. We may override the destroy() method
to clean up these resources.
public void destroy ()
{ ………….
………….
}
Passing Parameters to Applets:
We can supply user defined parameters to an applet using <PARAM> tag. Each <PARAM>
tag has a name attribute such as color, and a value attribute such as red. For example
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{ String str1,str2;
public void init()
{ str1=getParameter(“sname”);
str2=getParameter(“course”);
}
public void paint(Graphics g)
{ g.drawString(str1,10,100);

Page 51 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


g.drawString(str2,10,120);
}
}
<HTML>
<HEAD>
<TITLE> Welcome to Java Applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE=”HelloJavaParam.class” width=400 height=200>
<PARAM NAME=”sname” VALUE=”Rahul”>
<PARAM NAME=”course” VALUE=”BCA”>
</APPLET></BODY></HTML>
Displaying Numeric Values:
We can convert numeric values into strings by calling the valueOf () method of String class.
import java.awt.*;
import java.applet.*;
public class NumValues extends Applet
{ public void paint( Graphics g)
{ int value1=10;
int value2=20;
int sum=value1+value2;
String s=”Sum:”+String.valueOf(sum);
g.drawString(s,10,100);
}
}
<HTML>
<APPLET CODE=”NumValues.class” width=300 height=300>
</APPLET></HTML>
Graphics Class:

Page 52 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Graphics class includes methods for drawing many different types of shapes like lines, Rectangles, circles,
Arcs, polygon and text. Most commonly used methods are

drawLine(int x1,int y1,int x2, int y2) Draws a straight line.


x1,y1 represent coordinates of starting point
x2,y2 represent coordinates of end point.

drawRect(int x, int y,int w, int h) This method draws rectangle.


x,y represent the coordinates of top left corner
w represent the width of rectangle
h represent the height of rectangle.

fillRect(int x, int y, int w, int h) Draws a filled rectangle.


x,y represent the coordinates of top left corner
w represent the width of rectangle
h represent the height of rectangle.

drawRoundRect(int x, int y, int w, Draws a hollow rectangle with rounded corner.


int h, int cw, int ch) x,y represent the coordinates of top left corner
w represent the width of rectangle
h represent the height of rectangle.
cw represents the width of the corner
ch represents the height of the corner

fillRoundRect(int x, int y, int w, int Draws a filled rectangle with rounded corner.
h, int cw,int ch) x,y represent the coordinates of top left corner
w represent the width of rectangle
h represent the height of rectangle.
cw represents the width of the corner
ch represents the height of the corner

drawOval(int x, int y, int w, int h) Draws a hollow circle or ellipse.


x,y represent the coordinates of top left corner of

Page 53 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

imaginary rectangle.
w represent the width of imaginary rectangle
h represent the height of imaginary rectangle.

fillOval(int x, int y, int w, int h) Draws a filled circle or ellipse.


x,y represent the coordinates of top left corner of
imaginary rectangle.
w represent the width of imaginary rectangle
h represent the height of imaginary rectangle.

drawArc(int x, int y, int w, int h,int Draws a hollow arc.


sa, int d) x,y represent the coordinates of top left corner of
imaginary rectangle.
w represent the width of imaginary rectangle
h represent the height of imaginary rectangle.
sa represents the starting angle of the arc.
d represents number of degree around the arc.

fillArc(int x, int y, int w, int h,int sa, Draws a filled arc.


int d) x,y represent the coordinates of top left corner of
imaginary rectangle.
w represent the width of imaginary rectangle
h represent the height of imaginary rectangle.
sa represents the starting angle of the arc.
d represents number of degree around the arc.

drawPolygon(int x[], int y[], int n ) Draws a hollow polygon with n lines. It takes three
arguments.
x[] an array of integers containing x coordinates.
y[] an array of integers containing y coordinates.
n represents the total number of points.

fillPolygon(int x[], int y[], int n ) Draws a filled polygon with n lines. It takes three
arguments.
Page 54 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

x[] an array of integers containing x coordinates.


y[] an array of integers containing y coordinates.
n represents the total number of points.

import java.awt.*;
import java.applet.*;
public class GraphicShapes extends Applet
{ public void paint( Graphics g)
{ g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRoundRect(10,100,80,50,10,10);
g.drwOval(60,10,200,120);
g.setColor(Color.green);
g.fillOval(110,20,100,100);
g.fillArc(160,100,80,40,180,180);
}
}
<HTML>
<APPLET CODE=”GraphicShapes.class” width=300 height=300>
</APPLET></HTML>

Page 55 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

AWT Package:
AWT (Abstract Window Toolkit) contains classes and methods that allow you to create and
manage windows. The main purpose of the AWT is to support applet windows; it can also be
used to create stand alone windows that run in a GUI (Graphical User Environment). AWT
classes are contained java.awt package. It is one of Java’s largest packages.Some of the
important AWT classes are as under

Button Creates a push button control

Checkbox Creates a check box control

CheckboxGroup Creates a group of checkbox controls

Choice Creates a pop-up list

Label Creates a label that displays a string

List Creates a list box

MenuBar Creates a menu bar

Menu Creates a pull-down menu.

MenuItem Creates a menu item

PopupMenu Encapsulates a pop-up menu

Scrollbar Creates a scrollbar control

TextField Creates a single line edit control

TextArea Creates a multi line edit control

Dialog Creates a dialog window

FileDialog Creates a window from which file can be


selected.

Windows Creates a window with no frame, no menu


bar and no title

Frame Creates a standard window that has a title


Page 56 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

bar, menu bar and resize corners

Panel The simplest subclass of container

Font Encapsulates a type font

Color Manage colors in a portable, platform


independent manner.

BorderLayout The border layout manager. Border layout


use five components: North, South, East,
West, Center

FlowLayout The flow layout manager. Flow layout


positions components left to right, top to
bottom.

GridLayout The grid layout manager. Grid layout


displays components in two dimensional
grids.

GridBagLayout The grid bag layout manager. Grid bag layout


displays components subject to constraint
specified by GridBagConstraints.

CardLayout The card layout manager. Card layout


follows index cards. Only the one on top is
showing.

Component An abstract superclass for various AWT


components.

Window Fundamentals:
The two most common windows are
1. Derived from Panel which is used by applets
2. Derived fro Frame which creates a standard window.

Page 57 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Most of the functionality of these windows is derived from their parent classes. Explanation
of the class hierarchies related to these two classes is as under:
Component

Container

Window Panel

Frame

Component Class:
At the top of the AWT hierarchy is the component class. Component is an abstract class. All
user interface elements that are displayed on the screen and that interact with the user are
subclass of component. It defines over a hundred public methods that are responsible for
managing events such as mouse and keyboard input, positioning and resizing the window
and repainting.
Container:
The container class is subclass of Component. It has additional methods that allow other
Component objects to be nested within it. A container is responsible for laying out
components that it contains.
Panel:
The Panel class is a concrete subclass of container. It does not add any new methods; it
simply implements Container. Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object. Panel is a window that does
not contain a title bar.
Window:
The Window class creates a top level window. A top level window is not contained within
any other object. Generally you would not create window objects directly. Instead you will
use subclass of window called Frame.
Frame:

Page 58 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


It is subclass of Window and has a title bar, menu bar, borders and resizing corners. When a
frame window is created by a program rather than a applet a normal window is created.
Canvas:
This is special type of window. Canvas encapsulates a blank window upon which you can
draw.
AWT Controls:
Labels:
A label is an object of type Label. It contains a string which it displays. Labels are passive
controls that do not support any interaction with the user. Label supports following three
constructor
Label( )
Label(String str)
Label(String str, int how)
Str specifies the string to be displayed
how Specifies alignment. The value of how must be one of these three constants:
Label.LEFT, Label.RIGHT, Label.CENTER

Methods Description

void setText(String str) Set or change the text of Label

String getText( ) Return current label

void setAlignment( int how) Set the alignment of the string within the label.

int getAlignment( ) Return current alignment.

/*
<applet code="LabelDemo.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class LabelDemo extends Applet
{ public void init()
Page 59 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{ Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add(one);
add(two);
add(three);
}
}
Buttons:
A push button is a component that contains a label and that generates an event when it is
pressed. Push buttons are object of type Button. Button supports following two constructors
Button( )
Button(String str)
str specifies the string to be displayed.

Methods Description

void setLabel( String str) Set label of button

String getLabel( ) Returns current label of button

/*
<applet code="ButtonDemo.class" width=250 height=150>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ButtonDemo extends Applet
{ String msg = "You pressed yes";
Button yes, no, maybe;
public void init()
{ yes = new Button("Yes");

Page 60 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
}
public void paint(Graphics g)
{g.drawString(msg, 6, 100);}
}
Checkbox:
Check box is a control that is used to turn an option on or off. There is a label associated with
each check box that describes what option the box represents. You can change the state of a
check box by clicking on it. Check boxes are objects of the Checkbox class. Checkbox
supports following constructors
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
str specifies the label of checkbox.
on Set the initial state of the check box. If on is true, check box is initially checked.
cbGroup specifies the group of check box.

Methods Description

void setLabel(String str) Set the label of check box.

String getLabel( ) Returns current label of check box.

void setState(boolean on) Set the state of check box.

boolean getState( ) Return the current state of check box.

/*

Page 61 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


<applet code="CheckboxDemo.class" width=250 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class CheckboxDemo extends Applet
{ String msg = "";
Checkbox winXP, winVista;
public void init()
{ winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista",true);
add(winXP);
add(winVista);
}
public void paint(Graphics g)
{ msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
}
}

Choice Control:
Choice class is used to create a popup list of items from which the user may choose. When
the user clicks on it , the whole list of choices pop up and a new selection can be made.
Choice only defines the default constructor which creates an empty list. To add an item call
add () method.

Methods Description
Page 62 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

void add(String name) To add an item to the list.

String getSelectedItem( ) Returns name of currently selected item.

int getSelectedIndex( ) Returns the index of the currently selected item.

int getItemCount( ) Return total number of items in list.

void select(int index) Set currently selected item using zero based integer index.

void select(String name) Set currently selected item using string that will match a name
in list.

String getItem(int idx) Return the name of the item whose index is given by idx

/*
<applet code="ChoiceDemo.class" width=300 height=180>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ChoiceDemo extends Applet
{ Choice os, browser;
String msg = "";
public void init()
{ os = new Choice();
browser = new Choice();
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
browser.add("Internet Explorer");
browser.add("Firefox");

Page 63 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


browser.add("Opera");
add(os);
add(browser);
}
public void paint(Graphics g)
{ msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Lists:
The List class provides a compact, multiple choices, scrolling selection list. List shows any
number of choices in comparison to Choice object which shows only the single selected item
in the menu. List provides following three constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
numRows specifies the number of entries in the list that will always be visible.
multipleSelect if it is true user may select more than one items at a time

Methods Description

void add(String name) To add an item to the list.

String getSelectedItem( ) Returns name of currently selected item.

int getSelectedIndex( ) Returns the index of the currently selected item.

int getItemCount( ) Return total number of items in list.

Page 64 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

void select(int index) Set currently selected item using zero based integer index.

void select(String name) Set currently selected item using string that will match a name
in list.

String getItem(int idx) Return the name of the item whose index is given by idx

String[] getSelectedItems[] Returns an array containing the name of currently selected


items.

int[] getSelectedIndexes() Returns an array containing the indexes of currently selected


items.

/*
<applet code="ListDemo.class" width=300 height=180>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ListDemo extends Applet
{ List os, browser;
String msg = "";
public void init()
{ os = new List(4, true);
browser = new List(4, false);
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);

Page 65 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


add(os);
add(browser);
}
public void paint(Graphics g)
{ int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Scrollbars:
Scroll bars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. Scrollbar defines the
following constructors.
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
Style Specify the orientation of the scrollbar
initialValue Specify the initial value of scrollbar
thumbSize Specify the number of units represented by the height of the thumb
min Specify the min value of scrollbar
max Specify the max value of scrollbar

Method Description

int getValue() Return current value of scrollbar

Page 66 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

void setValue(int newValue) To set the current value of scrollbar

int getMinimum() Returns minimum value of scrollbar

int getMaximum() Returns maximum value of scrollbar

/*
<applet code="SBDemo.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class SBDemo extends Applet
{ String msg = "";
Scrollbar vertSB, horzSB;
public void init()
{ int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB);
add(horzSB);
}
public void paint(Graphics g)
{ msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
g.drawString("*", horzSB.getValue(),vertSB.getValue());
}
}
TextField:

Page 67 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


The TextField class implements a single line text entry area called an edit control. Text fields
allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys
and mouse selections. TextField defines the following constructors
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
numChars Creates a text field that is numChars characters wide.
str Create a text field with the string contained in str

Method Description

String getText() Return the string currently contained in the text field

void setText(String str) To set text in text field

String getSelectedText() Return currently selected text

boolean isEditable() Returns true if the text may be changed and false if not.

void setEditable(boolean canEdit) Set whether text field is editable or not.

void setEchoChar(char ch) This method specifies a single character that the text
field will display when characters are entered.

/*
<applet code="TextFieldDemo.class" width=380 height=150>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextFieldDemo extends Applet
{ TextField name, pass;
public void init()
{ Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
Page 68 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
}
public void paint(Graphics g)
{ g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}
TextArea:
TextArea class implements a simple multiline editor. TextArea defines the following
constructors
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
numLines Specify the height in lines
numChars Specify the width of text area
str Specify initial text
sBars Specify the scroll bars that you want the control to have.

Method Description

String getText() Return the string currently contained in the text field

void setText(String str) To set text in text field

Page 69 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

String getSelectedText() Return currently selected text

boolean isEditable() Returns true if the text may be changed and false if not.

void setEditable(boolean canEdit) Set whether text field is editable or not.

void setEchoChar(char ch) This method specifies a single character that the text
field will display when characters are entered.

void append(String str) Appends the string specified by str to the end of the
current text.

void insert(String str, int idx) Inserts the string specified by str at the specified index

/*
<applet code="TextAreaDemo.class" width=300 height=250>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{ public void init()
{ String val ="Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Layout Managers:
Each container object has a layout manager associated with it. A layout manager is an
instance of any class that implements the LayoutManager interface. The Layout manager is
set by the setLayout() method. Java has following predefined LayoutManager classes
 FlowLayout
 BorderLayout

Page 70 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


 GridLayout
 CardLayout
 GridBagLayout
FlowLayout:
FlowLayout is default layout manager . FlowLayout implements a simple layout style, which
is similar to how words flow in a text editor. The direction of the layout by default is left to
right, top to bottom. FlowLaout defines following constructors.
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
how specify how each line is aligned.
horz Specify horizontal space left between components
vert Specify vertical space left between components.
/*
<applet code="FlowLayoutDemo.class" width=250 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class FlowLayoutDemo extends Applet
{ String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init()
{ setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
Page 71 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


add(solaris);
add(mac);
}
public void paint(Graphics g)
{ msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
BorderLayout:
The BorderLayout has four narrow fixed-width components at the edges and one large area
in the center. The four sides are referred to as north, south, east and west. The middle area is
called the center. BorderLayout defines following constructors.
BorderLayout( )
BorderLayout(int horz, int vert)
horz Specify horizontal space left between components
vert Specify vertical space left between components.
/*<applet code="BorderLayoutDemo.class" width=400 height=200>
</applet>*/
import java.awt.*;
import java.applet.*;
import java.util.*;
public class BorderLayoutDemo extends Applet
Page 72 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{ public void init()
{ setLayout(new BorderLayout());
add(new Button("This is across the top."),BorderLayout.NORTH);
add(new Label("The footer message might go here."),BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
GridLayout:
GridLayout lays out component in a two dimensional grid. GridLayout defines following
constructors
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
numRows Specify number of rows
numColumns Specify number of columns
horz Specify horizontal space left between components
vert Specify vertical space left between components.
/*
<applet code="GridLayoutDemo.class" width=300 height=200>
</applet>*/
import java.awt.*;
import java.applet.*;
Page 73 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


public class GridLayoutDemo extends Applet
{ static final int n = 4;
public void init()
{ setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
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));
}
}
}
}
CardLayout:
The CardLayout class is unique among the other layout managers in that it stores several
different layouts. Each layout can be considered as separate index card in a deck that can be
shuffled so that any card is on top at a given time.
GridBagLayout:
In GridBagLayout each component can be a different size, and each row in the grid can have
a different number of columns. This is why the layout is called a grid bag. It is a collection of
small grids joined together.

Page 74 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

/*<applet code="GUI.class" width=200 height=200>


</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GUI extends Applet
{ Label lblName,lblCourse,lblHobbies,lblCity,lblRemarks;
TextField txtName;
Button btnExit;
Checkbox cbMusic,cbDance,cbReading;
Choice chkCourse;
List lstCity;
TextArea txtRemarks;
public void init()
{ setLayout(new GridLayout(6,3,5,10));
lblName=new Label("Enter Name");
txtName=new TextField(30);
lblCourse=new Label("Enter Course");
chkCourse=new Choice();
chkCourse.add("BCA");
chkCourse.add("BBA");
chkCourse.add("MScIT");
lblHobbies=new Label("Hobbies");
cbMusic = new Checkbox("Music");
cbDance = new Checkbox("Dance");
lblCity=new Label("City");
lstCity=new List(3,true);
lstCity.add("Barnala");

Page 75 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


lstCity.add("Moga");
lstCity.add("Ludhiana");
lstCity.add("Chandigarh");
lblRemarks=new Label("Remarks");
btnExit=new Button("Exit");
txtRemarks = new TextArea("Please Enter Remarks",10, 30);
add(lblName);add(txtName);add(new Label(" "));
add(lblCourse);add(chkCourse);add(new Label(" "));
add(lblHobbies);add(cbMusic);add(cbDance);
add(lblCity);add(lstCity);add(new Label(" "));
add(lblRemarks);add(txtRemarks);add(new Label(" "));
add(btnExit);
}
}
Event Delegation Approach:
Delegation Event Model a source generates an event and sends it to one or more listeners. In
this scheme, the listener simply waits until it receives an event. The advantage of this design
is that the application logic that processes events is cleanly separated from the user interface
logic that generates those events.
In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to listeners
that want to receive them.
Events:
An event is an object that describes a state change in a source. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard,
selecting an item in a list, clicking the mouse and timer expires.
Event Sources:
A source is an object that generates an event. Sources may generate more than one type of
event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the
general form:
public void addTypeListener(TypeListener el)
Page 76 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Here type is the name of the event and el is a reference to the event listener.
Event Listeners:
A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, it must implement methods to receive and process these
notifications.
ActionListener Interface:
This interface defines the actionPerformed () method that is invoked when an action event
occurs. Its general form is shown here
void actionPerformed(ActionEvent ae)

/*
<applet code="ButtonDemo.class" width=250 height=150>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonDemo extends Applet implements ActionListener
{ String msg = "";
Button yes, no, maybe;
public void init()
{ yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{ String str = ae.getActionCommand();
if(str.equals("Yes"))
{msg = "You pressed Yes.";}
else
if(str.equals("No"))
{msg = "You pressed No.";}
else

Page 77 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


{msg = "You pressed Undecided.";}
repaint();
}
public void paint(Graphics g)
{g.drawString(msg, 6, 100);}
}

AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an
adjustment event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
The MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( )
method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and
mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)


void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multiple times as
the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is
moved. Their general forms are shown here:

void mouseDragged(MouseEvent me)


void mouseMoved(MouseEvent me)
/*
<applet code="SBDemo.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.awt.event.*;

Page 78 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


import java.applet.*;
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener
{ String msg = "";Scrollbar vertSB, horzSB;
public void init()
{ int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB);
add(horzSB);
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
public void mouseDragged(MouseEvent me)
{ int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
public void mouseMoved(MouseEvent me)
{ }
public void paint(Graphics g)
{ msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
g.drawString("*", horzSB.getValue(),
vertSB.getValue());
}
}
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an
item changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie)

Page 79 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


/*
<applet code="CheckboxDemo.class" width=250 height=200>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CheckboxDemo extends Applet implements ItemListener
{ String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init()
{ winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{repaint();}
public void paint(Graphics g)
{ msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

Page 80 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods
are invoked when a key is pressed and released, respectively. The keyTyped( ) method is
invoked when a character has been entered.
For example, if a user presses and releases the A key, three events are generated in
sequence: key pressed, typed, and released. If a user presses and releases the HOME key,
two key events are generated in sequence: key pressed and released. The general forms of
these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
The WindowListener Interface:
This interface defines seven methods. The windowActivated ( ) and windowDeactivated( )
methods are invoked when a window is activated or deactivated, respectively. If a window is
iconified, the windowIconified ( ) method is called. When a window is deiconified, the
windowDeiconified ( ) method is called. When a window is opened or closed, the
windowOpened ( ) or windowClosed( ) methods are called, respectively. The
windowClosing ( ) method is called when a window is being closed. The general forms of
these methods are

void windowActivated(WindowEvent we)


void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

Page 81 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Errors:
An error is an unwanted condition which may produce an incorrect output or terminate the execution of
program. Errors are two types
1. Compile Time Errors:
All errors which occurs during compilation of program are called compile time errors. Whenever
compiler displays an error , it will not create the .class file. Most common compile time errors are
a. Missing semicolon
b. Missing double quotes in strings
c. Missing or mismatch of brackets in classes and methods.
d. Use of undeclared variables
e. Bad refrerence to objects.
For example
class Error1
{ public static void main( String args[ ] )
{
System.out.println(“Hello”) // compile time error (; expected)
}
}
Run Time Errors:
Sometimes a program may compile successfully creating the .class file but may generate errors
during run time. These errors are called run time errors. Most common run time errors are
a. Dividing an integer by zero.
b. Accessing an element that is out of bounds of an array.
c. Trying to store value into an array of incomaptible class or type.
d. Attempting to use a negative size for an array.
e. Converting invlaid string to a number.
For Example
class Error2
{ public static void main( String args[] )
{
int a=10,b=5,c=5;
int x = a / (b-c); // run time error (Division by zero)
System.out.println(“ x= “ + x);
}
}

Page 82 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Exceptions:
An exception is a condition that is caused by a run-time error in the program. When the java interpreter
encounters an error it creates an exception object and throws it.( i.e. informs us that an error has occurred). If
we want the program to continue , then we must catch the exception object thrown by the error condition .
This task is known as exception handling. Some common exceptions are

Exception Type Cause of Exception

ArithmeticException Cuased by math errors such as division by zero

ArrayIndexOutOfBoundsException Caused by bad array indexes.

FileNotFoundException Caused to access a nonexistant file

IOException Cuased by I/O Failure

NullPointerException Caused by refrencing a null object

StackOverFlowException Caused when the sysytem runs out of stack space

Syntyax of Exception Handling Code:


1. Try Block
Try block contains a block of code that can
cause an error condition and throws an
exception. Try block can have one or more
than one statements that could generate an
exception. If any one statement generates an
exception the remaining statements in block
are skipped and execution jumps to the catch
block.
2. Catch Block
Catch block catches the exception thrown by
try block and handles it appropriately. The
catch block is added immidiately after the try
block. It is possible to have more than one
catch block with try block.
3. Finally
It is added immidately after the last catch block. Finally block contains code which executes whteher
exception occurs or not. We use it to perform house keeping operations such as closing files and
releasing system resources.
For Example
class Error3
{ public static void main( String args[ ] )
{

Page 83 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


int a[ ] = { 5, 10 };
int b = 5;
try
{
int x = a [2] / b- a [1];
}
catch (ArithmeticException e)
{ System.out.println(“ Division by Zero”);}
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println(“Array Index Error”);}
finally
{ int y = a[1] / a[0];
System.out.println( “ y= “ + y );
}
}
}
Throw Keyword:
We can throw our own exceptions using the keyword throw as follows
throw new Throwable subclass;
class Error4
{ public static void main( String args[ ] )
{
int a=5, b=10;
try
{ int x = a/ b ;
if ( x <= 0 )
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
System.out.println(“ Value Less than or Equal to Zero”);
}
}
}

Page 84 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


Throws Keyword:
There are situations when a method may generate exception but there is no exception handling mechanism
within the method . in such a case method intimates it using keyword throws immidiately after the method
declaration. For Example
class Error5
{ static void divide_m( ) throws ArithmeticException
{
int x=22,y=0;
int z = x/y;
}
public static void main( String args[ ] )
{
try
{
divide_m();
}
catch (ArithmeticException e)
{
System.out.println(“ Caught The Exception:” + e );
}
}
}

Page 85 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Multitasking Multithreading

It is an operating System concept in which multiple It is a programming concept in which a program is


programs are executed in parallel. divided into subprograms called threads which are
executed in parallel.

Processor switch between different programs Processor switch between different parts or threads
of a program.

Program is the smallest unit Thread is the smallest unit

It is less efficient It is highly efficent

Developing less efficent programs Developing efficent programs

Creating Threads:
A new thread can be created in two ways
1. Define a class that extends Thread class and override its run( ) method with the required code.
2. Define a class that implements Runnable interface and overide its run( ) method with the required
code. Runnable interface has only one method run( )
Stopping a thread:
stop ( ) method is used to stop a thread from running . By calling this method thread moves to the dead
state. A thread will also move to the dead state automatically when it reaches to end of its method. For
example
aThread.stop ( );
Blocking a Thread:
A thread can be suspended or blocked using following methods
sleep ( ) // Blocked for a specified time
suspend( ) // Blocked until further orders i.e. by calling resume ( ) method
wait ( ) // Blocked until certain condition occurs i.e. by calling notify () method

Page 86 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com

Life Cycle of a Thread:


During the life time of a thread it enters following states
1. New born State:
Thread enters into new born state when we
create a thread object. At this stage we do only
one of the following things
a) Schedule it for running using start() method
b) Kill it using stop method
2. Runnable State:
The Runnable state means thread is ready for
execution and is waiting for the availability of the
processor. If all waiting threads have equal
priority then they executed in round robin fashion
i.e. first come first serve manner
3. Running State:
Running means that the processor has given its time to thread for its execution. A running thread
may give up control in one of the following conditions
1. It has been suspended using suspend () method.
2. We put thread to sleep for a specified time period using the method sleep (time) where time is in
milliseconds.
3. Thread has been told to wait until some event occurs. This is done using the wait () method. The
thread can be rescheduled to run again using the notify () method.
4. Blocked State:
A thread is said to be blocked when it is prevented from entering into Runnable or running state.
This happen when thread is suspended, sleeping or waiting in order to satisfy certain requirements.
5. Dead State:
A running thread enters dead state i.e. ends its life when run() method completed. We can also kill it
by using stop () method. A thread can be killed as soon as it is born or running or even when it is
suspended.
class A extends Thread
{ public void run ( )
{ for ( int i=1; i<=5; i++)
{ if ( i == 1 ) yield();
System.out.println (“ \t From Thread A: i= “ + i );
}
System.out.println (“ Exit from A”);
}
}

Page 87 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:rkgupta39@gmail.com

NH71, BAZAKHANA ROAD, BARNALA fb.com/aryabhattagroup,www.aryabhattagroup.com


class B extends Thread
{ public void run ( )
{ for ( int j=1; j<=5; j++)
{ System.out.println (“ \t From Thread B: j= “ + j );
if ( j == 3 ) stop();
}
System.out.println (“ Exit from B”);
}
}

class C extends Thread


{ public void run ( )
{ for ( int k=1; k<=5; k++)
{ System.out.println (“ \t From Thread C: k= “ + k );
if ( k == 1 )
try
{ sleep(1000);}
catch( Exception e)
{ }
}
System.out.println (“ Exit from C”);
}
}

class ThreadMethods

{ public static void main ( String args[ ])

{ A threadA =new A( );
B threadB =new B( );
C threadC =new C( );
threadA.start( );
threadB.start( );
threadC.start( );
}
}

Page 88 of 88

Вам также может понравиться