Oops Java
Oops Java
UNIT – I
Object-Oriented Programming (OOPS)
Definition:-“Object Oriented Programming is an approach that provides a way of modular
programming by creating patrician memory “ area for both data and functions that can be used
for creating copies of such modules on demand.
Object Oriented Paradigm
The major objective of Object Oriented Programming (OOP) is to dominate some of the
defect encountered in the Procedure Oriented Programming (POP). OOP treats data as critical
elements which doesn’t move freely around the system. It ties data more closely to the functions
that operate it and protects it from accidental modifications by other functions.
In OOP, the problem is decomposed into number of entities called Objects. And then
built data and functions (Known as methods in java) around there entities. The diagrammatic
representation of object creation is as follows.
Method Method
Data
Method Method
Data Data
Methods Methods
Data
Methods
Object - 3
1
Gudur, Tirupati Dist, AP. (India)
Features of JAVA
The inventor of java is James Gosling and it is become the familiar language for general
purpose and stand alone applications. The features of java are as follows.
Compiled and interpreted:- Java combines both compiled and interpreted, thus making java a
two stage system. First the java compiler translates source code into byte code instructions. Then
the java interpreter generates byte code into machine code that’s why java is a both compiled and
interpreted language.
Platform-independent and portable:- The most significant feature of java over other
languages is portability. Java programs can be easily moved from one computer system to
another, anywhere and anytime.
Object Oriented:- Java is pure object oriented language. Almost everything in java is an object.
All programs are resides within objects and classes.
Robust and secure:- Java is a robust language. It performs many safe guards to reliable code.
Security becomes an important issue for a language that is used for programming on internet.
Familiar, simple and Small:- Java is a small and simple language. Many features of C and C++
that are either redundant or sources of unreliable code are not part of java.
High Performance:- Java performance is impressive for an interpreted language mainly due to
the use of intermediate byte code.
2
Gudur, Tirupati Dist, AP. (India)
Dynamic and extendible:- Java is a dynamic language. It is capable dynamically linking in new
class libraries, methods and objects. Java supports functions written in other languages such as C
and C++.
OOPS CONCEPTS
Object Oriented Programming offers several benefits to both programmer designer and
user. It contributes to the solution of many problems, associated with the development of better
software products and also provides user maintenance cost. The basic concepts of OOP are as
follows.
- Classes
- Objects
- Data Abstraction
- Data Encapsulation
- Inheritance
- Polymorphism
- Dynamic Binding
- Message Passing
Classes:- A class is a mechanism which binds data and actions together. It allows the data to be
hidden if necessary from the external users. For Ex. In case of student class all objects have
similar attributes like student name, student number and marks. Actions like Total () and
Average () etc..
Objects: An objectis a runtime entity in object oriented system. It can be anything that exits in
the world. It is a composition of properties and actions. Ex. Student, Chair, Pen etc.
Data Abstraction:- Abstraction means data hiding. The technique of creating new data type
using encapsulating items that is applied to an application. The data types that are used in data
abstraction those are called as Abstract Data Types (ADT).
Data Encapsulation:- The grouping of data and functions into a single component is known as
encapsulation. Here the data is not accessible by outside functions.
Inheritance:- Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concepts of hierarchical classification. In OOP, the
concept of inheritance provides the idea of reusability. The following example shows the
inheritance hierarchy.
3
Gudur, Tirupati Dist, AP. (India)
Bird
Polymorphism:-It is another important OOP concept. Poly means many or several, morphism
means forms. It is an ability to take more than one form. Polymorphism plays an important role
in allowing the objects having different internal structures to share the external interface. The
following example shows the polymorphism hierarchy.
Shape
Dynamic Binding:- Binding refers to the linking of procedure-call to the code to be executed in
response to that call. Binding means that the code associated with a given procedure –call is not
known until the time of the call at run time.
Message Passing:- In object Oriented program concepts of set of objects that communicate with
each other. The following this to done thru Message passing.
4
Gudur, Tirupati Dist, AP. (India)
OOP offers several benefits to both program designer and users. It contributes to the
solution of many problems, associated with the development of better software product and also
provides user maintenance cost.
a) Through inheritance, we can eliminate the redundant code and extend the use of existing
classes.
b) We can build standard working modules that communicate with one another. This leads less
development time and higher productivity.
c) It is possible to have multiple objects to co-exist without any interference.
d) The data centered design approach enables to capture more details of a model in an
implementable form.
e) Object oriented systems can be easily upgraded from small to large systems.
f) Message passing technique for communication between objects.
g) Software complexity can be easily manages.
Applications are:- The application of OOP are beginning to gain importance in many areas. The
most popular applications are:
5
Gudur, Tirupati Dist, AP. (India)
Java program may contain many classes of which only one class defines a main method.
It contains data members and methods that operate on the data members of the class. A java
program can contain one or more section. They are:
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Section
Documentation Section:- The documentation section consists of comments given name of the
programmer, the author and date details. They are:
Java also use third style of comments i.e. /** ……. */ known as documentation
comment.
Package Section:- the first statement in java file is package statement. This statement declares a
package name and informs the compilers that the class defined here belong to the package.
Ex : package Student;
Import statement:- The next statement after java package is import statement, it is similar to #
include statement in C.
This statement instructs the interpreter to load the test class contained in package student.
6
Gudur, Tirupati Dist, AP. (India)
Interface statement:- An interface is like a class but it includes a group of method declarations.
That is an optional section and is used only when we wish to implement multiple inheritance
feature in java program.
Class Definition:- A java program may contain multiple class definitions. Class are the primary
and essential elements of a program.
Main method class:- Every java program requires a main method as its starting point. The main
method creates objects of various classes and establishes communication between them.
Java Tokens
- Keywords
- Identifiers
- Literals
- Operators
- Separators
Keywords:- Keywords are an essential part of a language definition. Java supports 50 keywords
to implement the program. All keywords are written in lowercase only.
Ex: int, float, do, for etc.
Identifiers:- Identifiers are programmer designed tokens. They are variables, class-names,
method-names, package-names etc.
Ex: student, employee, slno etc.
Literals:- Literals are also called as constants. In java there are five types of literals. They are:
- Integer literals
- Floating literals
- String literals
- Character literals
- Boolean literals
7
Gudur, Tirupati Dist, AP. (India)
Separators:- Separators are symbols used to indicate where group of code are divided and
arranged. Java supports 6 types of separators. They are:
- Parenthesis ( )
- Brace { }
- Brackets [ ]
- Semicolon ;
- Comma ,
- Period .
DATA TYPES
The data type specifies what type of data is stored and manipulated in the computer
system. Data type specifies a collection of values and a set of operations to be applied on those
values.It also specifies the memory usage by a memory variable.
Data Types
Integer types:- Integer data type are used to store whole numbers only. In java the integer data
type support four types of data types. They are shown in the following diagram.
8
Gudur, Tirupati Dist, AP. (India)
. Integer
Byte Long
Short int
Floating Point types:- floating point data types are used to store floating point data like real
numbers or fractional values. In java two types of floating point types which are shown in the
following diagram.
Floating-point
float double
The keywords ‘float’ and ‘double’ are used to declare float type variables. We can also use
qualifiers to declare float type variables. The following table shows float data types and their range
of values:
9
Gudur, Tirupati Dist, AP. (India)
Character Family:
The keyword ‘char’ is used to declare character data type variables. It contains any
alphabet, digit (or) special character. It occupies 2 bytes of memory space.
Boolean type:
Boolean type is used to store only true and false values. It occupies 1 byte of memory space.
The default value of Boolean variable is false.
VARIABLES
A variable is a name given to a memory location where the data is stored temporarily. It
is an identifier whose value is changed during the execution of a program.
The user is allowed to access the data from the memory location through the variable name.
A variable can hold only one value in its location.
Declaration of Variables:
A variable must be declared before it is used in the program. The declaration of variables
tells the compiler to reserve memory space with specified variable names depending on the
specified data type.
The general format of variable declaration is as follows:
10
Gudur, Tirupati Dist, AP. (India)
Syntax:-
In the above syntax, the ‘datatype’ refers to any valid data type. Var1, var2, …. are the
variable names associated to the data type.
Ex:
int a, b, sum ;
float avg, f ;
char ch ;
double xyz ;
Giving values to variables:- For a variable, we may given a value at the time of using the variables
in an expressing. This can be achieved in two ways. They are:
- By using an assignment statements
- By using read statements.
Examples:
int a=40, b=50, c=90;
In this example, variables a, b and c are declared as integer data type and they are initialised
with values 40, 50 and 90 respectively.
-Using read statements, we may give the values to the variables. The following statements
are used to read the values to the variables.
11
Gudur, Tirupati Dist, AP. (India)
SCOPE OF VARIABLES
The scope of variable represents, how long a variable is stored into a computer’s memory.
The scope of variable is determined by the way of it has been declared. In java, the variables scope
is classified into the following types. They are:
Instance variables
Class variables
Local variables
Instance variables:- instance variables are declared inside the class. These variables are created
when the objects are created and they are associated with the object.
Class variables:- class variables are also declared inside the class but they are global to the class
and belongs to the entire set of objects that class creates. A separate memory location is created
for each class variables for storing and accessing the value to the entire class.
Local variables:- the local variables are declared inside the method only. They are accessed only
inside the method and cannot be accessed outside the method. In java, local variables can also be
declared inside of program blocks that are defined between ‘{‘ and ‘}’. These variables are visible
to the program only from the beginning of its program block and to the end of the program.
The following program is shown the scope of variables.
12
Gudur, Tirupati Dist, AP. (India)
TYPE CASTING
Sometimes, we need to store a value of one type into a variable of another type. In such
situations we must cast the value into a specific type. Simply the process of converting one data
type into another data type is called type casting. The general form of type casting is as follows.
In the above syntax, the type which is placed in between parenthesis is the primary data type which
is converted variable two to variable one.
int y=(int)x;
y=20;
Automatic Converting:- In java, the small type data is automatically converted into larger type.
long b = a;
Here, no need to use type casting because the small type is automatically casting. While
converting larger type to smaller type, we should use type casting. The example shown the type
casting.
int a = (int) b;
Finally the process of assigning a smaller type to large is known as Widening or Promotion. The
process of assigning larger type to smaller is known as Narrowing.
Ex:
class TypeCasting
{
public static void main(String args[])
{
float a = 123.456f;
byte b = (byte) a;
long c = 6789;
13
Gudur, Tirupati Dist, AP. (India)
int d = (int) c;
System.out.println( a + “------“ + b);
System.out.println( c + “-------“ + d);
}
}
OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. It is used to
manipulate data stored in the variables.
‘C’ language supports the following types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment and decrement operators
5. Assignment Operators
6. Conditional operator
7. Bitwise operators
8. Special operators
1. Arithmetic operators:
Arithmetic operators are used to perform arithmetic calculations. The following are the
various arithmetic operators.
Operator Meaning
+ Addition
– Subtraction
* Multiplication
/ Division
2. Relational Operators:
The relational operators are used to compare two values and to give either true (1) or false
(0) result. The following are the relational operators.
14
Gudur, Tirupati Dist, AP. (India)
Operator Meaning
== Equal to
!= Not equal to
3. Logical Operators:
These are used to combine two or more conditions and give the result either true or false.
They are used to form compound conditions.
Operator Meaning
¦¦ Logical OR
! Logical NOT
Logical AND (&&) Operator: This operator gives true if all the conditions are true otherwise it
gives false. The truth table for && operator is as follows:
Ex: A && B
Logical OR ( ¦¦ ) Operator: This operator gives true if any or all the conditions are true otherwise
it gives false. The truth table for ¦¦ operator is as follows:
Ex. X || Y
Logical NOT (!) Operator: This operator negates the result of a condition. It means if the
condition is true then it gives false. If the condition is false then it returns true. The truth table for
! operator is as follows:
Ex: !N
15
Gudur, Tirupati Dist, AP. (India)
Increment and decrement operators are used to increment and decrements the value
of an operand. It is incremented and decremented only 1 value at a time.
Ex: a++; ++a;
n--; --m;
5. Assignment Operators: The assignment operator is used to assign the value to the variable.
The operator ‘=’ is used to assign the value of the variable. The general form of assignment
operator is as follows.
Value
variable
Variable = constant
expression
In the above syntax, any one of the left side value is assigned to the variable.
6. The Conditional Operators
The conditional operators (? :) are used to execute the statements which are depending on the given
condition. The general form of conditional operator is as follows.
Syntax:
In the above syntax, the conditional expression is executed first. If the result is true,
expression-1 is executed and it is returned as the value of the conditional expression. Otherwise,
expression-2 is executed and its value is returned.
Ex:
In the above example, the value of age is > 50 the string “Old Age” is returned as a results.
Otherwise, the string “Young Age” is returned as results to the variable s.
7. Bitwise Operators: The bitwise operators are used to perform the operation on bits insteadof
decimal values. The bitwise operators which are supported by java are as follows.
16
Gudur, Tirupati Dist, AP. (India)
Operator Meaning
& AND
| OR
^ XOR
~ One’s complement
<< Left shift
>> Right shift
>>> Right shift with zero fill
8.Special Operators: The operator ‘.’ (dot) and instanceof are used as special operators.
Expressions
The expression is a combination of variables, constants and operators. In java, there are
several types of expression; some of them are as follows.
- Arithmetic expressions
- Relational expressions
- Logical expressions
- Boolean expression etc
Arithmetic expressions: The expression which is constructed with the help of arithmetic
operators is called arithmetic expression.
Ex: a+b
a -b etc
Relational Expressions: The expression which is constructed with the help of relational
operators is called relational expression.
Ex: a>b
A<b etc
Logical Expression: The expression which is constructed with the help of logical operators are
called as logical expression
17
Gudur, Tirupati Dist, AP. (India)
Boolean Expression: The expression which is constructed without help of any operators is
called Boolean expression.
Ex: true
false
if statement:-
The ‘if’ statement is a conditional execution statement that executes the specified set of
instructions based on the condition.
Syntax:
if (condition) statement-block ;
’if…else’ statement:
It is also conditional execution statement that executes the statements based on the
condition. If the condition is true then it executes one group of instructions otherwise it executes
another group of statements.
Syntax:
if (condition)
statement-block1 ;
else
statement-block2 ;
18
Gudur, Tirupati Dist, AP. (India)
Example-1:
if (a % 2 = = 0)
System.out.println(“Even number”);
else
System.out.println(“Odd Number”);
Syntax:
if (condition1)
{
if (condition2)
statement-block1 ;
else
statement-block2 ;
}
else
{
if (condition3)
statement-block3 ;
else
statement-block4 ;
}
19
Gudur, Tirupati Dist, AP. (India)
Example:
if (x= =y)
{
if (a= =b)
System.out.println(“x is equal to y and a is equal to b”);
else
System.out.println(“x is equal to y, but a is not equal to b”);
}
else
{
if (a= =b)
System.out.println(“x is not equal to y, but a is equal to b”);
else
System.out.println(“x is not equal to y and a is not equal to b”);
}
Switch Statement:
The ‘switch’ statement is a multiple branching statement. It can be used to make a decision
from the number of choices. It is an extension of ‘if…else’ statement.
Syntax:
switch (op)
{
case V1 : statement-block1;
[break;]
case V2 : statement-block2;
[break;]
: :
: :
case Vn : statement-block-n;
[break;]
[default : statement-block-d;]
}
In the above syntax, ‘op’ is a constant, variable (or) expression that results an integer value.
The switch statement uses the value of ‘op’ to execute the statement-blocks.
20
Gudur, Tirupati Dist, AP. (India)
V1, V2, …, Vn are the values that represent the value of ‘op’. These are the constants either
integer or character type. These values must be unique.
When statement-block contains many statements then they must be enclosed within a pair
of braces ({}).
Working: The switch statement searches for a match of switch variable (op) and case constants
(V1, V2, …, Vn). If a value matches to the ‘op’, the switch statement executes all the statements in
that case-block. If there is ‘break’ statement in that block then it terminates the execution of switch
statement. If ‘break’ is not present then all the statements of remaining blocks are executed.
If any value doesn’t match to the ‘op’ then the ‘default’ block is executed, if it is specified
in the switch statement.
Example:
import java.io.*;
class MySwitch
{
public static void main(String args[] ) throws IOException
{ DataInputStream D= new DataInputStream(System.in);
int a;
System.out.println(“Enter a single digit number”);
a=Integer.parseInt(D.readLine());
switch (a)
{ case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”);
break;
case 3: System.out.println(“Tuesday”);
break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”);
break;
case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default: System.out.println(“Wrong Value”);
21
Gudur, Tirupati Dist, AP. (India)
}
}
}
The Conditional Operators
The conditional operators (? :) are used to execute the statements which are depending on the given
condition. The general form of conditional operator is as follows.
Syntax:
In the above syntax, the conditional expression is executed first. If the result is true,
expression-1 is executed and it is returned as the value of the conditional expression. Otherwise,
expression-2 is executed and its value is returned.
Ex:
In the above example, the value of age is > 50 the string “Old Age” is returned as a results.
Otherwise, the string “Young Age” is returned as results to the variable s.
In 'Java' language, there are 3 types of repetitive control structures. They are
1. While structure
2. Do…while structure
3. For structure
22
Gudur, Tirupati Dist, AP. (India)
Syntax:
import java.io.*;
class MyWhile
{
public static void main(String args[] ) throws IOException
{ DataInputStream D= new DataInputStream(System.in);
int i,n;
System.out.println(“Enter a number”);
n=Integer.parseInt(D.readLine());
i=1;
while (i<=n)
{
System.out.println(i);
i++;
}
}
23
Gudur, Tirupati Dist, AP. (India)
do…while Statement:
Do..While is one of the looping statement. This statement is used to execute a statement or
group of statements repeatedly as long as the specified condition is satisfied. It is an exitcontrol
loop structure. The do…while structure executes at least one time even initially the condition is
false.
Syntax:
do
{
statement-block;
import java.io.*;
class MyDo
{
public static void main(String args[] ) throws IOException
{ DataInputStream D = new DataInputStream(System.in);
int i,n;
System.out.println(“Enter a number”);
n=Integer.parseInt(D.readLine());
do
{
System.out.println(i);
i++;
24
Gudur, Tirupati Dist, AP. (India)
} while (i<=n);
}
‘for’ Statement:
For is one of the looping statements. This statement is used to execute a statement or group
of statements repeatedly as long as the specified condition is satisfied.
Syntax:
Example: A program to find and print the sum of first ‘n’ natural numbers.
import java.io.*;
class MySwitch
{
public static void main(String args[] ) throws IOException
{ DataInputStream D= new DataInputStream(System.in);
int i,n,sum=0;
System.out.println(“Enter a number”);
n=Integer.parseInt(D.readLine());
for (i=1; i<=n; i++)
{
System.out.println(i);
25
Gudur, Tirupati Dist, AP. (India)
sum+=i;
}
System.out.println(sum);
}
Break Statement:
Break is one of the statements, which is used in Switch and Loops only. If we execute the
break statement, the control point is come out form the switch or loop. The general form of break
statement is as follows.
Syntax: break ;
Example:
import java.io.*;
class MySwitch
{
public static void main(String args[] ) throws IOException
{ DataInputStream D= new DataInputStream(System.in);
int a;
System.out.println(“Enter a number”);
a=Integer.parseInt(D.readLine());
for(i=1;i<=n;i++)
{
num = Integer.parseInt(D.readLine());
if (num<0)
break;
sum=sum+num;
}
System.out.println(sum);
}
Continue Statement:
The continue statement must be used in loops only. When the continue statement is reached
within a loop, it continues the execution from the first statement of the loop.
Syntax:
continue ;
26
Gudur, Tirupati Dist, AP. (India)
Example:
import java.io.*;
class MySwitch
{
public static void main(String args[] ) throws IOException
{ DataInputStream D= new DataInputStream(System.in);
int n,num,i;
System.out.println(“Enter a number”);
n=Integer.parseInt(D.readLine());
i=0;
while (i<=n)
{
i++;
num=Integer.parseInt(D.readLine());
if (num<0)
continue;
}
}
ARRAYS
An array is a group of related data items that share a common name and same datatype. Using
arrays, we can store group of elements of a particular type. In arrays a particular item is
identified by their index numbers.
One-Dimensional Arrays:- A list items can be given one variable name using only one
subscript is known as single subscripted variable or one-dimensional variable. While creating
one-dimensional arrays, we follow the following steps.
Declare the array:- the following syntax is used to declare the array.
27
Gudur, Tirupati Dist, AP. (India)
or
Type []arrayName;
Or
int [] a;
Creating memory locations:- the following syntax is used to create memory location to the array.
Putting values into memory: the following syntax is used to put values to the arrays.
class ArrayOne
{
Public static void main(String args[])
{
int a[]={5,1,4,2,3};
int \i,j,n,t;
n=a.length;
System.out.println(“List of values”);
for(i=0; i<n; i++)
System.out.print(“ “ + a[i]);
for(i=0; i<n; i++)
{
for(j=i+1; j<n;j++)
{
if(a[i]>a[j])
` {
t=a[i];
28
Gudur, Tirupati Dist, AP. (India)
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println(“Order of values”);
For(i=0; i<n; i++)
System.out.print(“ “ + a[i]);
}
}
Two-dimensional Array or double Dimensional array: For creating two dimensional arrays,
we must follow some steps as one dimensional arrays. Two dimensional array must be used two
subscripts: one for row and another for column representation. The following are used to create
two dimensional arrays.
class MatMultiplication
{
public static void main(String args[])
{
int i, j, k;
int a[][]={{1,2},{3,4}};
int b[][]={{5,6},{7,8}};
int c[][]={{0,0},{0,0}};
for(i=0; i<2; i++)
{ for(j=0; j<2;j++)
{ for(k=0; k<2;k++)
` {
29
Gudur, Tirupati Dist, AP. (India)
A class is a basic concept of OOP which is used to create Objects. A class is also a basic
structure of all programs of java programs. It provides a convenient environment for packing
together a group of logically related data items. It is also the basic description of how to make an
object that contains fields and methods.
30
Gudur, Tirupati Dist, AP. (India)
}
Fields declaration:- the variables which are declared with in the class are called variables (fields).
These variables also called as instance variables because they are created whenever an object of
class is instantiated.
Method declaration:- methods are declared inside the body of the class usually, after declaration
of instance variables. The general form of method declaration is as follows.
(or)
31
Gudur, Tirupati Dist, AP. (India)
Accessing members:- The members of a class must be invoked by the object with the help of
dot (.) operator. The general form of member accessing is as follows:
Syntax:- objectname.variable=value;
Objectname.method();
In the above syntax the dot operator is used to access fields and methods.
p.getData();
class Person
{
String name=”Nani”;
int age = 10;
void getData()
{
System.out.println (name + “ –“ + age);
}
}
class MySister
{
Public static void main(String args[])
{
Person p = new Person();
p.getData();
}
}
32
Gudur, Tirupati Dist, AP. (India)
Class
1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint or prototype from which
objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of methods.
Object: It is a basic unit of Object-Oriented Programming and represents real life entities. A
typical Java program creates many objects, which as we know, interact by invoking methods.
Generally,an object consists of :
State: It is represented by attributes (values) of an object. It also reflects the properties of
an object.
Behavior: It is represented by methods (actins) of an object. It also reflects the response
of an object with other objects.
Identity: It gives a unique name (ID) to an object and enables one object to interact with
other objects.
Example: Pen
CONSTRUCTORS
33
Gudur, Tirupati Dist, AP. (India)
Default Constructor
Parameterized Constructors
Default Constructors:- Default constructor is a constructor which is not having any parameter
list. The following example shows the default constructors.
Ex: Rectangle()
{
…………….
……………
}
Parameterized Constructors:- Parameterized constructor is a constructor which is having one
or more parameter list. The following example shows the default constructors.
class Rectangle
{
int length;
int width;
Rectangle(int x, int y)
{
34
Gudur, Tirupati Dist, AP. (India)
length = x;
width = y;
}
Void getData()
{
System.out.println(“Area of Rectangle is = “ + length * width);
}
}
class MyRectangle
{
Public static void main(String args[])
{
Rectangle R = new Rectangle(2, 58);
R.getData();
}
}
ACCESS CONTROL
An access control feature in Java specifies how to access the members of a class or a class
itself. We can use access specifiers before a class and its members.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If we do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If we do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
35
Gudur, Tirupati Dist, AP. (India)
THIS KEYWORD
The this keyword refers to the current object in a method or constructor of the present
class.
The most common use of this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a method
or constructor parameter).
classTest
{
inta;
intb;
Test(inta, intb)
{
this.a = a;
this.b = b;
}
voiddisplay()
{
System.out.println("a = "+ a + " b = "+ b);
}
}
class TestThis
{
publicstaticvoidmain(String[] args)
{
Test object = newTest(10, 20);
object.display();
}
}
36
Gudur, Tirupati Dist, AP. (India)
GARBAGE COLLECTION
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program. Eventually, some objects will no longer
be needed. The garbage collector finds these unused objects and deletes them to free up memory.
Generally, In C/C++, a programmer is responsible for both the creation and destruction of
objects. Usually, programmer neglects the destruction of useless objects. Due to this negligence,
at a certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free heap
memory by destroying unreachable objects. The garbage collector is the best example of
the Daemon thread as it is always running in the background.
In java, is possible to create methods that have the same name, but different parameter
list and with different definitions are called method Overloading.
or
Method overloading has ability to define more than one method with the same name in
class. In method overloading, the Objects are requested to perform similar tasks using different
input parameters when we call a method. Java matches the method name first and then the
number and type of parameters to decide which one of the definitions have to execute. This
process is known as Polymorphism.
Ex: class Rectangle
{
int length;
int width;
Rectangle(int x )
{
length = width = x;
}
Rectangle(int x, int y)
{
length = x;
width = y;
37
Gudur, Tirupati Dist, AP. (India)
}
int getData()
{
return ( length * width);
}
}
class MyRectangle
{
Public static void main(String args[])
{
int area1, area2;
Rectangle R1 = new Rectangle(39);
Rectangle R2 = new Rectangle(2, 59);
area1 = R1.getData();
area2 = R2.getData();
System.out.println(“Area of First Rectangle = “ + area1);
System.out.println(“Area of Second Rectangle = “ + area2);
}
}
After execution of the above program, the first method Rectangle is executed because we
are passing one parameter. And then second method also executed while passing two parameters.
Simply this process is known as method overloading.
PARAMETER PASSING
Information is passed to a method from the calling point by using parameters. In Java
language there are two types of methods used to send parameters to a method. They are (i) Call-
by-value Method and (ii) Call-by-reference Method
i. Call-by-value Method:
In this method, we can send only values to a called method. Whenever a method is called
with parameters, the value of an argument is sent to the formal parameter.
Inside the method, the values of formal parameters can be used and changed according to
the need. But, when the control is returned back to its calling point, the changed values of formal
parameters are not transferred. This type of passing technique is called call-by-value mechanism.
Example:
publicclassExample
{
inta = 10;
38
Gudur, Tirupati Dist, AP. (India)
voidcall(inta)
{
a = a+10;
}
publicstaticvoidmain(String[] args)
{
Example eg = newExample();
System.out.println("Before call-by-value: "+ eg.a);
eg.call(500);
System.out.println("After call-by-value: "+ eg.a);
}
}
ii. Call-By-Reference Method:
This method is also known as Call-by-location method. In this method, we have passed the
object reference as a value instead of a valueto the called method. Whenever a method is called
with parameters, the reference of an argument is sent to the formal parameter.
Inside the method, when the formal parameter is changed then value of actual argument is
also changed. This is method of passing technique is called call-by-reference method.
class Example
{
int a = 10;
void call(Example eg) {
eg.a = eg.a+10;
}
public static void main(String[] args)
{
Example eg = new Example();
System.out.println("Before call-by-reference: " + eg.a);
eg.call(eg);
System.out.println("After call-by-reference: " + eg.a);
}
}
RECURSION
Recursion is a process by which a method calls itself repeatedly. In the recursion process,
a method is repeated endlessly or until some specified condition has been satisfied. Recursion is
used for repetitive computations in which each action is started in terms of a previous result.
For Example, to find factorial of 5, it can be recursively computed as follows:
39
Gudur, Tirupati Dist, AP. (India)
5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1
In the same way, the factorial of n is recursively defined as,
N! = N * (N-1)! if N > 1
= 1 if N <=1
long int fact( int n)
{
if ( n <= 1 )
return (1) ;
else
return ( n * fact ( n-1) );
}
STATIC MEMBERS
A class basically contains two sections: one for data, another for methods. These data and
methods are called instance variables and instance methods. These are accessed using objects with
the help of (.) dot operator. Sometimes, we declare the members in a class using static keyword
as follows.
40
Gudur, Tirupati Dist, AP. (India)
STRINGS HANDLING
41
Gudur, Tirupati Dist, AP. (India)
class StringOrder
{
Public static void main(String args[])
{
String name[]={“Nellore”,”Kavali”, “Gudur”,”Tirupati”,”Amaravathi”};
int \i,j,n;
String t = null;
n=name.length;
for(i=0; i<n; i++)
{
for(j=i+1; j<n;j++)
{ if(name[i].compateTo(name[j]) > 0)
` {
t=name[i];
name[i]=name[j];
name[j]=t;
}
}
}
System.out.println(“Order of Names”);
For(i=0; i<n; i++)
System.out.print(“ “ + name[i]);
}
}
42
Gudur, Tirupati Dist, AP. (India)
STREAMS
ByteStream
ByteStream classes are used to read bytes from the input stream and write bytes to the
output stream. In other words, we can say that ByteStream classes read/write the data of 8-bits.
We can store video, audio, characters, etc., by using ByteStream classes. These classes are part of
the java.io package.
The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the Input/Output stream
classes.
InputStream Class
The InputStream class provides methods to read bytes from a file, console or memory. It
is an abstract class and can't be instantiated; however, various classes inherit the InputStream class
and override its methods. The subclasses of InputStream class are given in the following table.
Class Description
BufferedInputStream This class provides methods to read bytes from the buffer.
ByteArrayInputStream This class provides methods to read bytes from the byte array.
DataInputStream This class provides methods to read Java primitive data types.
FilterInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.
PipedInputStream This class provides methods to read from a piped output stream to
which the piped input stream must be connected.
SequenceInputStream This class provides methods to connect multiple Input Stream and
read data from them.
43
Gudur, Tirupati Dist, AP. (India)
Character Streams
However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are divided into
two types of classes, i.e., Reader class and Writer class.
Reader Class
Reader class is used to read the 16-bit characters from the input stream. However, it is an
abstract class and can't be instantiated, but there are various subclasses that inherit the Reader class
and override the methods of the Reader class. All methods of the Reader class throw an
IOException. The subclasses of the Reader class are given in the following table.
Class Description
BufferedReader This class provides methods to read characters from the buffer.
CharArrayReader This class provides methods to read characters from the char array.
FileReader This class provides methods to read characters from the file.
FilterReader This class provides methods to read characters from the underlying
character input stream.
PipedReader This class provides methods to read characters from the connected piped
output stream.
44
Gudur, Tirupati Dist, AP. (India)
DATA STREAM
Data streams support binary I/O of primitive data type values (Boolean char byte, short,
int, long, float, and double) as well as String values. All data streams are implement either the
DataInput interface or the DataOutput interface. Instead of interfaces, there are DataInputStream
or DataOutputStream class to handle the input output data to the java program.
The DataStreams example demonstrates data streams by writing out a set of data records,
and then reading them in again. Each record consists of three values related to an item on an
invoice, as shown in the following table:
Order
Data
in Output Methods Input Methods Sample Value
type
record
1 double DataOutputStream.writeDouble DataInputStream.readDouble 19.99
2 int DataOutputStream.writeInt DataInputStream.readInt 12
3 String DataOutputStream.writeUTF DataInputStream.readUTF "Java Program"
import java.io.*;
class DataStrm
{
Public static void main(String args[])
{
DataInputStream dt=new DataInputStream(System.in);
String s;
System.out.println(“Enter a String”);
s=dt.readLine();
System.out.println(“Your String is = “ + s);
}
}
45
Gudur, Tirupati Dist, AP. (India)
UNIT – II
HIERARCHICAL ABSTRACTIONS
Ex: class A
{
…………………
}
class B extends A
{
………………....
}
In java, there are four kinds of inheritance. They are:
- Single inheritance
- Multiple inheritance
- Hierarchical inheritance
- Multi-level inheritance
46
Gudur, Tirupati Dist, AP. (India)
legth = x;
breadth = y;
}
int area()
{
return (length * breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom (int x, int y, int z)
{
super (x, y);
height = z;
}
int volume()
{
return (length * breadth * height);
}
}
class MyFlat
{
public static void main(String args[])
{ BedRoom B = new BedRoom(10, 20, 30);
int area1 = B.area();
int area2 = B.volume();
System.out.println(“First Room Area =” + area1);
System.out.println(“Second Room Area =” + area2);
}
}
INHERITANCE
Inheritance is the process of inherit (import) the properties of one class to another. In
OOP the concept of inheritance provides the idea of re-usability. This means that we can add
additional features to an existing class without modifying it. The mechanism of deriving a new
class from an old class is called inheritance. Here the old class is referring to base-class and new
47
Gudur, Tirupati Dist, AP. (India)
class can be referred as derived-class. The derived inherits the features from the base class.
Inheritance can be classified into following types.
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical
4. Multilevel inheritance
1. Single Inheritance:- The derived class with only one class is called as single inheritance.
The diagrammatic representation of single inheritance is as follows.
A -Base Classes
B -Derived Class
2. Multiple Inheritance:- A derived class can be derived from multiple base classes is
multiple inheritance. The diagrammatic representation of multiple inheritances is as
follows.
A B -Base Classes
C -Derived Class
3. Hierarchical Inheritance: - Two or more derived classes can be derived from one base
called is called hierarchical inheritance. The diagrammatic representation of hierarchical
inheritance is as follows.
-Base Classes
A
A C D -Derived Classes
48
Gudur, Tirupati Dist, AP. (India)
4. Multilevel Inheritance:- The mechanism of deriving a class from another derived class
is known as multilevel Inheritance. The diagrammatic representation of multilevel
inheritance is as follows.
A - Base class
C -Derived Classes
BENEFITS OF INHERITANCE
Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class.
An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered
by the derived class.
COSTS OF INHERITANCE
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
49
Gudur, Tirupati Dist, AP. (India)
The member access rules determines whether a sub class can use a property of it’s super
class or it can only access or it can neither access nor access. There are two level of access
control.
1. At the top level: public or package-private.
2. At the member level: public, private, and protected.
A class may be declared with the public modifier, th the case that class is visible to all classes
everywhere.
At the member level, there are three different access modifiers are there: 'private', 'protected' and
'public'.
private : If private access modifier is applied to an instance variable, method or with a
constructor in side a class then they will be accessed inside that class only not out side of the
class.
For example: class A
{
private int x=10;
}
class B extends A
{
int y=20;
System.out.println(x); //Illegal access to x ;
}
If you make any class constructor private, you can't create the instance/object of that class
from outside the class. for example:
class A
{
int x;
private A(int k) // private constructor
{
x=k;
}
}
class Test
{
public static void main(String args[])
{
A ob=new A(10); //Compile time error
}
}
50
Gudur, Tirupati Dist, AP. (India)
public: The class, variable, method or a constructor with public access modifier can be accessed
from anywhere.
FINAL VARIABLES, METHODS AND CLASSES
Final is a keyword, which is used to define the variables, methods and classes as final.
Once we define these as final they are not modifiable or not accessible for the others. The final
keyword is used like the following.
Final variables:- The variables which defined as final variables, are not modified in the
program. The general form of final variable is as follows.
Final methods:- The methods which are defined as final are not altered anywhere or the final
method is not accessible by the Subclass Objects. The general form of final method is as follows.
51
Gudur, Tirupati Dist, AP. (India)
}
Example program for final fields, methods and classes
protected Object clone() - Used to create and return a copy of this object.
boolean equals(Object obj) - Used to indicate whether some other object is "equal to" this
one.
protected void finalize() - garbage collector calls this method on an object when it
determines that there are no more references to the object.
Class<?> getClass() - Used to get the runtime class of this Object.
int hashCode() - Used to get a hash code value for the object.
void notify() - Used to wake up a single thread that is waiting on this object's monitor.
void notifyAll() - Used to wake up all threads that are waiting on this object's monitor.
String toString() - Used to get a string representation of the object.
52
Gudur, Tirupati Dist, AP. (India)
void wait() - marks the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
void wait(long timeout) - marks the current thread to wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount
of time has elapsed.
void wait(long timeout, int nanos) - marks the current thread to wait until another thread
invokes the notify() method or the notifyAll() method for this object, or some other thread
interrupts the current thread, or a certain amount of real time has elapsed.
METHOD OVERRIDING
In java, Method Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one of its super-classes or parent
classes. When a method in a subclass has the same name, same parameters or signature, and
same return type(or sub-type) as a method in its super-class, then the method in the subclass is
said to override the method in the super-class. The following example shown the process of
method overriding
class Animal
{
void display()
{
System.out.println(“I am an Animal”);
}
class Tiger extends Animal
{
void display()
{
System.out.println(“I am a Tiger”);
}
}
class Main
{
public static void main(String[] args)
{
Tiger tg = new Tiger();
tg.display();
53
Gudur, Tirupati Dist, AP. (India)
}
}
Output: I am a Tiger();
In the above example program, the display() method is resent in both the Animal super-
class and Tiger sub-class. When we call display() using tg object (object of the subclass), the
method inside the subclass Tiger is called. The display() method of the subclass overrides the
same method of the superclass.
ABSTRACT CLASSES
An abstract method is method, which does not contain any body. It contains only the
method header. So that, we can say it is an incomplete method.
An abstract class is a class, which is generally contains some abstract methods. Both the
abstract class and abstract methods should be declared by the keyword abstract. Usually, an
abstract method has the method header(without body). So that we should create sub-classes to
implements the actual body of the method. The simple example of abstract classes and abstract
method is as follows.
Ex:
54
Gudur, Tirupati Dist, AP. (India)
{
void draw()
{
System.out.println(“We can Draw a line “);
}
}
class Circle extends Shape
{
void draw()
{
System.out.println(“We can Draw a Circle “);
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(“We can Draw a Rectangle “);
}
}
class ExAbstract
{
public static void main(String args[])
{
Line L = new Line();
Circle C = new Circle();
Rectangle R= new Rectangle();
L.draw();
C. draw();
R.draw();
}
}
55
Gudur, Tirupati Dist, AP. (India)
An interface is basically a kind of class like class. Interface also contains variables and
methods. The main difference between class and interface is that interface contains abstract
methods and final variables.
*Note:- Interface supports multi-inheritance because we can derive a class from more than one
interface.
56
Gudur, Tirupati Dist, AP. (India)
class ExInterface
{
Public static void main(String args[ ])
{
Float a,b;
Rectangle R = new Rectangle( );
Circle C = new Circle( );
a = R.compute(10.0f, 20.3f);
b = C.compute(30.3f,50.9f);
System.out.println(“Rectangle – “ + a);
System.out.println(“Area Of Circle – “+b);
}
}
Extending Interfaces:- Like class , interfaces can also be extended. That is an interface can be
sub-interfaced from other interfaces. This is achieved using the keyword extends like the
following.
57
Gudur, Tirupati Dist, AP. (India)
Syntax :-
Example: interface A
{
int x = 40;
int y = 50;
}
class B implements A
{
int m = x;
int n = y;
}
Example Program :-
class Student
{
int rlno;
void getNo(int x)
{
rlno = x;
}
void putNo( )
{
System.out.println(“Roll Number : “ + rlno);
}
}
58
Gudur, Tirupati Dist, AP. (India)
59
Gudur, Tirupati Dist, AP. (India)
}
}
Difference between Class and Interfaces
CLASS
INTERFACE:-
PACKAGES
A package represents a directory that contains related group of classes and interfaces.
Java supports two types of Packages.
Pre – defined packages: Java(API) provides a large number of classes and interfaces grouped
into different package. According to functionally they are shown in the diagram.
60
Gudur, Tirupati Dist, AP. (India)
java
import java.lang.*;
class Sample
{
Public static void main(String args[ ])
{
int x = 81;
double y;
y =Math.sqrt(x);
System.out.println(“Square Root is : “ +y);
}
}
Here import java.lang.*; Matt.sqrt(x);
In java, we can create our own packages. The keyword package is used to create our own
packages. Once we create a package, then we may import the package to the other programs.
61
Gudur, Tirupati Dist, AP. (India)
}
In the above syntax packageName is the name directory and class name is filename.
Accessing the package:-To access the package, we use the keyword “import”.
package pack;
public class Fact
{
long i, f = 1;
public void getFact(int n)
{
for(i=n;i>0;i++)
{
f=f*i;
}
System.out.println(f);
}
62
Gudur, Tirupati Dist, AP. (India)
}
The above program is saved with filename Fact.java
Then compile the program like the following c:\java>javac -d . Fact .java.
import pack.Fact;
class Fnumber
{
public static void main(String args[ ])
{
Fact f = new Fact( );
f.getFact(5);
}
}
UNDERSTANDING CLASSPATH
o We need to load a class that is not present in the current directory or any sub-directories.
o We need to load a class that is not in a location specified by the extensions mechanism.
The CLASSPATH depends on what we are setting the CLASSPATH. The CLASSPATH
has a directory name or file name at the end. The following points describe what should be the end
of the CLASSPATH.
o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the zip
or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the directory that
contains the class files.
o If class files placed in a named package, the CLASSPATH ends with the directory that
contains the root package in the full package name that is the first package in the full
package name.
63
Gudur, Tirupati Dist, AP. (India)
The default value of CLASSPATH is a dot (.). It means the only current directory searched.
The default value of CLASSPATH overrides when we set the CLASSPATH variable or using the
-classpath command (for short -cp). Put a dot (.) in the new setting if we want to include the current
directory in the search path.
64
Gudur, Tirupati Dist, AP. (India)
UNIT – III
EXCEPTION HANDLING
Errors are the wrongs that can make a program go wrong. An error may produce an
incorrect output or may terminate the execution of the program or system crash.
Types of errors:-The errors may be classified into two categories. They are
1. Compile – Time errors :- All syntax errors will be detected and displayed by the java
compiler are known as Compile - Time errors. Most compile time errors are detected due to
typing mistakes.
Missing – Semicolon.
Missing – double – quotes.
Misspelling keywords.
Use of undeclared variables.
Missing brackets in classes and methods etc.
Improper placement of braces.
65
Gudur, Tirupati Dist, AP. (India)
Exceptions
An Exception is a condition that is caused by run-time errors in the program. When Java
interpreter encounters an error such as dividing an integer by Zero. It creates an exception object
and throws it. While throwing the exception object, we should be catch that, otherwise the
program is terminated abruptly. The process of handling the exception is known as exception
handling.
The error handling code basically consists of two segments, one is detect and throw errors(try
block) and other is to catch the exception(catch block).
The following diagram shows the process of try and catch block.
66
Gudur, Tirupati Dist, AP. (India)
skipped and exception jumps to the catch-block. The catch statement that is works like method
definitions which handle the exception.
Ex 1:
class Sample
{
public static void main(String args[ ] )
{
int a,b,c,x,y;
a=10;
b=c=5;
try
{
x=a/(b-c);
}
catch(ArthmeticException e)
{
System.out.println(:Value of Y:”+y);
}
}
Ex2: import java.io.*;
class Sample
{
public static void main(String args[ ])throws IOException
{
int a,b,c,x,y,z;
a = 10;
b = c = 5;
DataInputStream D = new DataInputStream(System.in);
System.out.println(“Enter A Number other then Zero”);
z = a % z;
System .out.println(“x:” +x);
y = a/(b+c);
System.out.println(“y:”+y);
}
}
67
Gudur, Tirupati Dist, AP. (India)
The diagram below shows the standard exception and error classes defined in Java,
organized in the Java exceptions hierarchy:
A try block may have more than one catch blocks. So times we may create more than one catch
statement like the following.
Syntx:- ------------
------------
try
{
Statement;
}
68
Gudur, Tirupati Dist, AP. (India)
catch(Exception - type1 e)
{
Statement;
}
catch(Exception - type2 e)
{
Statement;
}
catch(Exception - typen e)
{
Statement;
}
-------------
-------------
In the above Syntax any one of the catch block is raised, that is depending upon the
matching the type of exception in the catch statement.
Example Program:-
class Multiplication
{
public static void main(String args[ ])
{
int a[ ] ={10,20};
int b=10,x;
try
{
x = a[2]/b-a[1];
}
catch(ArithmeticExceptionae)
{
System.out.println(“Division By Zero Error”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index Error”);
}
catch(ArrayStoreException e)
{
System.out.println(“Wrong Data Type”);
}
x = a[1]/a[0];
69
Gudur, Tirupati Dist, AP. (India)
Java supports another statement in try – block area is known as finally statement. It is
used to handle an exception which is not caught by any one of the previous catch statements. It is
always raised even there is an exception or not.
Syntax: ------------
-------------
try
{
----------
-----------
}
catch(---------)
{
----------
-----------
}
catch(------)
{
----------
-----------
}
finally
{
----------
-----------
}
Example Program:-
class Finally
{
public static void main(String args[ ])
{
int x;
try
{
x = 5/0;
}
70
Gudur, Tirupati Dist, AP. (India)
catch(ArithmeticExceptionae)
{
System.out.println(“Division By Zero Error”);
}
finally
{
System.out.println(Division By Zero Error”);
}
}
}
CREATINGOWN EXCEPTION SUB CLASSES
Sometimes it is required to develop meaningful exceptions based on the application
requirements. We can create our own exceptions by extending Exception class in Java
User-defined exceptions in Java are also known as Custom Exceptions.
Steps to create a Custom Exception
CustomException class is the custom exception class this class is extending Exception
class.
Create one local variable message to store the exception message locally in the class
object.
We are passing a string argument to the constructor of the custom exception object. The
constructor set the argument string to the private string message.
toString() method is used to print out the exception message.
We are simply throwing a CustomException using one try-catch block in the main method
and observe how the string is passed while creating a custom exception. Inside the catch
block, we are printing out the message.
Example
71
Gudur, Tirupati Dist, AP. (India)
}
public class MainException {
public static void main(String args[]) {
try {
throw new CustomException("This is a custom message");
} catch(CustomException e) {
System.out.println(e);
}
}
}
Output: Custom Exception Occurred : This is a custom message
THREADS
A thread is similar to program that has a single flow of control. It has a beginning, a
body, an end and executes commands sequentially.
All java programs in our earlier example can be called single threaded programs. A
program that contains multiple flow of control can be called Multi-Threading.
Creating Thread:-
Creating thread is simple to create run( ) method of thread object. The run method is
heart and soul of any thread. The general form of run method is as follows.
We can extend the class from java.lang.Thread to do this. We follow the following steps.
Declaring the class :The thread class can be extended like the following.
72
Gudur, Tirupati Dist, AP. (India)
73
Gudur, Tirupati Dist, AP. (India)
A a= new A( );
B b=new B( );
a.start( );
b.start ( );
}
}
Stopping a thread.
Blocking a thread.
Stopping A Thread:
Whenever we want to stop a thread from running further, we may execute the stop( )
method of the specified thread.The general form of stop( ) method is as follows:
Syntax :Threadname.stop( );
Ex: a.stop( );
Blocking a Thread : A thread can also be temporarily suspended or blocked from the running
state.The following methods are used to block the thread.
Sleep( );
Suspend( );
Wait( );
Ex: a.sleep(1000);
Suspend( ): This method is used to suspend the thread until the method resume( ) is executed.
Syntax :Threadname.suspend( );
Ex: a.suspend( );
Wait( ): This method is used to wait the thread for a specific period until the method notify( ) is
executed.
74
Gudur, Tirupati Dist, AP. (India)
Syntax :Threadname.wait( );
Ex: a.wait( );
class MySleeping
{ public static void main(String args[ ])
{ Sleeping s = new Sleeping( );
s.start( );
}}
A thread is a group of statements, which are executed as a single task. During lifetime of a
thread, there are many states it can enter, they are
Newborn State
Runnable State
Running State
Blocked state.
Dead State.
75
Gudur, Tirupati Dist, AP. (India)
A thread is always is one of these five states. It can move from one state to another state via a
variety of ways as shown in the below following Diagram.
Newborn State : when we Create a thread objects, the thread is born and is said to be in
Newborn Sate. At this state we can do only one of the following methods.
Runnable state :- The runnable states means that the thread is ready for exection and is waiting
for the availability of the processor.That is the thread is joined the Queue processor(FIFO).In this
state , executing yield( ) method, to provide a priority.
Running State:- Running state means that the processor has given its time to the thread for its
execution. while running the thread we may execute any one of the following methods.
->Suspend
->sleep(1000);
76
Gudur, Tirupati Dist, AP. (India)
->Wait( );
Blocked State:- A method is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state. Simply the blocked thread is considered not
runnable but not dead therefore fully qualified to run again.
Dead State:-Every thread has a life cycle. A running thread ends its life when it has completed
executing its run( ) method. It is a natural death. However we can kill it at any state even newly
born or blocked state.
77
Gudur, Tirupati Dist, AP. (India)
SYNCHRONIZATION
………..
………..
synchronized (lock-object) {
………..
………..
When we declare a method synchronized, java create a Monitor and hands it over to the
thread that calls the mehtod first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of code. A monitor is like a key as the thread that holds the
key only open the lock.
Ex: Thread A
Synchronized mehtod2()
{
synchronized method1()
{
………..
…………
………..
78
Gudur, Tirupati Dist, AP. (India)
}
}
Thread B
Synchronized mehtod1()
{
synchronized method2()
{
………..
…………
………..
}
}
INTERTHREAD COMMUNICATION
Interthread communication is important when we develop an application where two or
more threads exchange some information.
There are three simple methods and a little trick which makes thread communication possible. All
the three methods are listed below:
1
public void wait()
Causes the current thread to wait until another thread invokes the notify().
2
public void notify()
Wakes up a single thread that is waiting on this object's monitor.
3
public void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in
all the classes. All three methods can be called only from within a synchronized context.
Example:
79
Gudur, Tirupati Dist, AP. (India)
This examples shows how two threads can communicate using wait() and notify() method.
You can create a complex system using the same concept.
classChat{
boolean flag =false;
publicsynchronizedvoidQuestion(String msg){
if(flag){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(msg);
flag =true;
notify();
}
publicsynchronizedvoidAnswer(String msg){
if(!flag){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(msg);
flag =false;
notify();
}
}
class T1 implementsRunnable{
Chat m;
String[] s1 ={"Hi","How are you ?","I am also doing fine!"};
public T1(Chat m1){
this.m = m1;
newThread(this,"Question").start();
}
publicvoid run(){
for(int i =0; i < s1.length; i++){
m.Question(s1[i]);
}
}
}
80
Gudur, Tirupati Dist, AP. (India)
class T2 implementsRunnable{
Chat m;
String[] s2 ={"Hi","I am good, what about you?","Great!"};
public T2(Chat m2){
this.m = m2;
newThread(this,"Answer").start();
}
publicvoid run(){
for(int i =0; i < s2.length; i++){
m.Answer(s2[i]);
}
}
}
publicclassTestThread{
publicstaticvoid main(String[] args){
Chat m =newChat();
new T1(m);
new T2(m);
}
}
DAEMON THREADS
Daemon thread in Java is a service provider thread that provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
We can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
o It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.
81
Gudur, Tirupati Dist, AP. (India)
Example:
A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread group
has a parent.
A thread is allowed to access information about its own thread group, but it cannot access
the information about its thread group's parent thread group or any other thread groups. The
following example is used to group the threads.
82
Gudur, Tirupati Dist, AP. (India)
Multitasking Multithreading
The multitasking component involves While the multithreading component does not
multiprocessing. involve multiprocessing.
Isolation and memory protection exist in Isolation and memory protection does not exist
multitasking. in multithreading.
83
Gudur, Tirupati Dist, AP. (India)
Multitasking Multithreading
84
Gudur, Tirupati Dist, AP. (India)
UNIT –IV
APPLETS
In java we can develop applets for doing anything from simple animated Graphics to
computer games and utilities. Since applets are embedded in html document and run inside a web
page. They are two types of Apples in java.
*Local Applets.
*Remote Applets.
*Local Apples:- An applet which is stored and executed in a local system is known as local
applet.
Remote Applets: A remote applet is that which is developed by someone else and stored on a
remote computer connected to the internet.
85
Gudur, Tirupati Dist, AP. (India)
Applets and applications are java programs, but there is a difference between them.
Applets are not full-featured application programs where are applications are full-featured
applications. Generally, applications are used as any kind of applications where as applets are
used for internet applications only. The difference between applets and application are shown
below.
CREATING APPLET
To create an applet, we use the services of the two classes, namely Applet and Graphics
classes from library. Applet class of java.applet package provides the methods like init(), start(),
stop() and paint() for starting, running, stopping and painting the applet code. The paint() method
uses Graphics class to display text, graphics, animations etc. on the page. So that, we import
java.awt package for the Graphics class. The general form of paint method is as follows.
In the above method, class Graphics of java.awt package helps us to do all operations on
the webpage. The simple example of applet is as follows.
86
Gudur, Tirupati Dist, AP. (India)
import java.applet.*;
----------------
-----------------
public class AppletClassName extends Applet
{
----------------------
-----------------------
public void paint(Graphics g)
{
---------------- // Applet code.
-----------------
}
}
In the above example, “AppletClassName” is the main class for the applet. When the
applet is loaded, the methods of that class are executed and print something on the screen.
Example Program:
importjava.awt.*;
import java.applet.*;
public class App extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello Java”, 10,50);
}
}
In the above program contains only one statement i.e g.drawString(“Hellojava”,10,50)
which displays on the screen like the following.
50
Hello Java
10
87
Gudur, Tirupati Dist, AP. (India)
*Running State.
*Idle state.
*Display State.
An applet is always in one of the above states. It can move from one state to another state
via. a variety of ways as shown in the following diagram.
88
Gudur, Tirupati Dist, AP. (India)
These are activated by calling the init( ) method of AppletClass. It occurs only
Once in the applet life cycle. The general form of init( ) method is as follows.
89
Gudur, Tirupati Dist, AP. (India)
import java.awt.*;
import java.appet.*;
public class App extends Applet
{
public void paint(Graphics g)
{
int x = 50;
String s = String.valueOf(x);
g.drawString(“value :”+5,10,50);
}
}
<HTML>
<Applet code =App.class width = 300 height = 400>
</Applet>
</HTML>
Param Tag
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value of
the parameter respectively. For example, the param tags for passing name and age parameters
looks as shown below:
90
Gudur, Tirupati Dist, AP. (India)
Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.
getParameter() Method
The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:
Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:
import java.awt.*;
import java.applet.*;
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
{
g.drawString("Name is: " + n, 20, 20);
91
Gudur, Tirupati Dist, AP. (India)
</applet>
AWT EVENTS
User interaction with the elements of Graphical User Interface(GUI) of a Java program
leads to events. These elements could be a button, checkbox, radio button, menu, list, table,
scrollbar, mouse, window etc. Such elements are also known as source of an event and there is a
specific class corresponding to each source and each event. There are several events some of them
are given bellow.
Java follows a Delegation Event Model to handle the events. The two main components of this
model are as follows -
Source
Listener
Source
Interaction with a source generates an event, which is an object of event class describing
the current state of source. A source must register the listener class that wishes to listen and
respond to its event, by calling a method, which has a general form of -
For example - A click on a source such as button raises to an event, which is an object of
type ActionEvent class, hence a source button must call its method addActionListener() to
register any class that wishes to listen and respond to its button event of type ActionEvent.
Listener
92
Gudur, Tirupati Dist, AP. (India)
The event is delegated to the registered listener classes. In order to listen and respond to
events, such registered listener class must implement EventTypeListener interface,
where, EventType could be replaced by the name of the type of event.
For example - A class wishing to listen and respond to the a button click event(which is
an object of type ActionEvent), must implement ActionListener interface.
Interaction with elements of GUI raises events, which are nothing but objects
of classes. EventObject is the superclass of all the events. Let's see a table containing some
different kinds of event classes and the description of their events.
Event classes and Event Listener interfaces are used to perform various actions on AWT
tools. To do actions on events, we should be implemented event classes and their corresponding
interfaces in order to listen and respond to the events. The following table shows the event classes
and event listener interface.
93
Gudur, Tirupati Dist, AP. (India)
ActionEvent ActionListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
KEYBOARD EVENTS
A user interacts with the application by pressing either keys on the keyboard or
by using mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing these
events will enable the programmer to write his code according to the key pressed or mouse
event.
KeyListener interface of java.awt.event package helps to know which key is pressed or
released by the user. It has 3 methods
1. Public void keyPressed(KeyEvent ke): This method is called when a key is pressed on
the keyboard. This include any key on the keyboard along with special keys like function
keys, shift, alter, caps lock, home, end etc.
2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on the
keyboard. This is same as keyPressed() method but this method is called when general
keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the key
presed by the user.
94
Gudur, Tirupati Dist, AP. (India)
MOUSE EVENTS
The user may click, release, drag, or move a mouse while interacting with athe
application. If the programmer knows what the user has done, he can write the code according to
the mouse events. To trap the mouse events, MouseListener and MouseMotionListener interfaces
of java.awt.event package are use.
1. int getButton(): this method returns a value representing a mouse button, when it is
clicked it retursn 1 if left button is clicked, 2 if middle button, and 3 if right button is
clicked.
2. int getX(): this method returns the horizontal x position of the event relative to the source
component.
3. int getY(): this method returns the vertical y postion of the event relative to the source
component.
ADAPTER CLASSES
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
95
Gudur, Tirupati Dist, AP. (India)
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
INNER CLASSES
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
Additionally, it can access all the members of the outer class, including private data members and
methods.
96
Gudur, Tirupati Dist, AP. (India)
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
97
Gudur, Tirupati Dist, AP. (India)
AWT HIERARCHY
The Java AWT (Abstract Windowing Toolkit) contains the fundamental classes used for
constructing GUIs. The abstract Component class is the base class for the AWT. Many AWT
classes are derived from it. These are the old AWT components that are no longer in use.
Some of the AWT classes derived from Component are Button, Canvas, and Container.
The diagram shows how the classes of the AWT and Swing fit together. Look it over to get
an overview. Refer back to it occasionally as you read these notes.
The JComponent class is derived from Container and is one of the base classes of Swing.
The JFrame class is derived from the AWT Frame class. It is usually the main container for a GUI
application.
The JApplet class is derived from the AWT Applet class and is used for modern applets.
98
Gudur, Tirupati Dist, AP. (India)
The user interacts with a component (clicks on a button, types in a field, chooses from a
pop-up menu, etc.), an event is generated by the component that you interact with. For each
component of our program, the programmer is required to designate one or more objects to "listen"
for events from that component. Thus if our program has a button labelled "start" we must assign
one or more objects which will be notified when a user clicks on the button. There are several
components, some of them are given bellow.
Label: A label is a constant text that is generally displayed along with a TextField or TextArea.
To create Label, we use Label class. The following example shows the creation of label.
Button: Button class is useful to create Push buttons. It is useful to perform a particular action.
The following example shows the Button creation.
Canvas: The Canvas class controls and represents a blank rectangular area where the application
can draw or trap input events from the user. It inherits the Component class. The following
example shows the creation of canvas.
Scrollbar: The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar
is a GUI component allows us to see invisible number of rows and columns.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar class
extends the Component class. The following example shows the creation of scrollbars.
TextField: The object of a TextField class is a text component that allows a user to enter a single
line text and edit it. It inherits TextComponent class, which further inherits Component class.
The following example shows the creation of text field.
TextArea: It is another text component, we helps us to create text as multiple line. The following
example shows the creation of TextArea.
99
Gudur, Tirupati Dist, AP. (India)
Checkbox: The Checkbox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
The following example shows the creation of CheckBox.
Choice: The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits Component class.
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.
Panel: The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
JscrollPane: A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size can change
dynamically.
Dialog: The Dialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Window class.
MenuBar: A Menu represents a group of options for the user to select from. JMenu class is used
to create menu bar.
Graphics: java.awt.Graphics class provides many methods for graphics programming. Example:
100
Gudur, Tirupati Dist, AP. (India)
public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
LAYOUT MANAGERS
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
1. BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
2.FlowLayout class is used to arrange the components in a line, one after another (in a flow). It is
the default layout of the applet or panel.
101
Gudur, Tirupati Dist, AP. (India)
3. GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
4. CardLayout class manages the components in such a manner that only one component is visible
at a time. It treats each component as a card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap
102
Gudur, Tirupati Dist, AP. (India)
UNIT - V
SWINGS
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.
103
Gudur, Tirupati Dist, AP. (India)
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages
and disadvantages and examples to understand the implementation of MVC in Java.
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using model
designs.
o Model: It represents the business layer of application. It is an object to carry the data that
can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data that
the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:
104
Gudur, Tirupati Dist, AP. (India)
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.
To implement MVC pattern in Java, we are required to create the following three classes.
The Model in the MVC design pattern acts as a data layer for the application. It represents
the business logic for application and also the state of application. The model object fetch and store
the model state in the database. Using the model layer, rules are applied to the data that represents
the concepts of application.
105
Gudur, Tirupati Dist, AP. (India)
View Layer
As the name depicts, view represents the visualization of data received from the model.
The view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.
Controller Layer
The controller layer gets the user requests from the view layer and processes them, with
the necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the controller
and then displayed on the view.
COMPONENTS OF SWING
Class Description
A Component is the Abstract base class for about the non menu
user-interface controls of SWING. Components are represents
Component an object with graphical representation
106
Gudur, Tirupati Dist, AP. (India)
Class Description
A JSpinner this class is a single line input where the field that
JSpinner lets the user select by using a number or an obje
107
Gudur, Tirupati Dist, AP. (India)
SWING CONTAINERS
Containers are an integral part of SWING GUI components. A container provides a space
where a component can be located. A Container in AWT is a component itself and it provides the
capability to add a component to itself. Following are certain noticable points to be considered.
Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden
using setLayout method.
Following is the list of commonly used containers while designed GUI using SWING.
Panel: JPanel is the simplest container. It provides space in which any other component
1
can be placed, including other panels.
JApplet
JApplet is a class of swing package which is used to create applets like application in
java. Simply, it is a class which is derived from Applet class in java AWT. To create JApplet, we
follow the following example.
JFrame
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
108
Gudur, Tirupati Dist, AP. (India)
The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the JComponent
class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don't inherit
JComponent class because they are the child of top-level containers.
The JComponent class extends the Container class which itself extends Component. The Container
class has support for adding components to the container.
Labels and Icons of Swing class feature helps us to create labels and Icons with the help
of Swing’s new Icon interface and an implementation of this interface called ImageIcon. With
The JLabel class allows us to add basic, nonfunctional labels to a user interface. Because of their
inherent simplicity, there is no model class for JLabel components. The following example
shows the creation of label.
JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class. The following example is used to create JTextField.
109
Gudur, Tirupati Dist, AP. (India)
JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JCheckBox
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz. It should be added in
ButtonGroup to select one radio button only. The following example is used to create Radio
Buttons.
JComboBox
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
110
Gudur, Tirupati Dist, AP. (India)
JTabbedPane
JscrollPane
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in the tree.
It inherits JComponent class. The declaration of JTree is as follows.
JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns. The following example is used to create the JTable.
111
Scanned by CamScanner
Scanned by CamScanner