Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
75 views

Oops Java

This document provides an overview of object-oriented programming concepts in Java. It discusses the features of Java like being compiled and interpreted, platform independent, object oriented, robust, distributed, familiar, simple, small, multithreaded and high performance. It then describes object-oriented programming concepts like classes, objects, data abstraction and encapsulation.

Uploaded by

Krishnaveni Yata
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Oops Java

This document provides an overview of object-oriented programming concepts in Java. It discusses the features of Java like being compiled and interpreted, platform independent, object oriented, robust, distributed, familiar, simple, small, multithreaded and high performance. It then describes object-oriented programming concepts like classes, objects, data abstraction and encapsulation.

Uploaded by

Krishnaveni Yata
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

B.Tech V Semester: Computer Science & Engineering(AI)


Course code Category Hours/week Credits Maximum Marks
L T P C CIA SEE TOTAL
20AI502 PC
3 0 0 3 30 70 100
Contact Classes:60 Tutorial Classes: 0 Practical Classes: 0 Total Classes:60
OBJECTIVES:
The course should enable the students to :
1. Gain knowledge about basic Java language syntax and semantics to write Java
programs
2. Use concepts such as variables, conditional and iterative execution methods etc.
3. Understand the fundamentals of object-oriented programming in Java
4. Define classes, objects, invoking methods etc and exception handling mechanisms.
5. Understand the principles of inheritance, packages and interfaces.
UNIT-I BASICS CONCEPTS OF JAVA & STREAMS Classes:12
Java Basics- Features of java, OOPs Concepts, Data types, variables, scope and life time
of variables, arrays, operators, expressions, control statements, type conversion and
casting, simple java program, classes and objects – concepts of classes, objects,
constructors, methods, access control, this keyword, garbage collection, overloading
methods and constructors, parameter passing, recursion, string handling.
Streams- Byte Streams, Character Streams, Data Streams
UNIT-II INHERITANCE,POLYMORPHISM, INTERFACES & Classes:12
PACKAGES
Inheritance- Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance- specialization, specification, construction, extension,
limitation, combination, benefits of inheritance, casts of inheritance. Member access rules,
super uses, using final with inheritance, Object class and its methods.
Polymorphism- Method overriding, abstract classes.
Interfaces and Packages-Differences between classes and interfaces, defining an
interface, implementing interface, applying interfaces, variables in interface and extending
interfaces, Accessing implementations through Interface reference. Defining, Creating
and Accessing a Package, Understanding CLASSPATH, importing packages, Exploring
packages – java.io, java.util.
UNIT-III EXCEPTION HANDLING & THREADS Classes:12
Exception handling - Concepts of exception handling, benefits of exception handling,
Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws
and finally, built in exceptions, creating own exception sub classes.
Threads- Differences between multi threading and multitasking, thread life cycle, creating
threads, synchronizing threads, inter thread communication, Daemon threads,
ThreadGroup.
UNIT-IV APPLETS & AWT Classes:12
Applets : Concepts of Applets, differences between applets and applications, life cycle of
an applet, types of applets, creating applets, passing parameters to applets.
AWT: Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes, inner classes. The AWT class
hierarchy, user interface components- labels, button, canvas, scrollbars, text components,
check box, check box groups, choices, lists panels – scrollpane, dialogs, menubar,
graphics, Layout manager –Types – boarder, grid, flow, card and GridBag.
UNIT-V SWINGS Classes:12
Swings : Introduction, limitations of AWT, MVC architecture, components, containers,
exploring swing- JApplet, JFrame and JComponent, Icons and Labels, text fields, buttons
– The JButton class, Check boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll
Panes, Trees, and Tables.
Text Books:
1. Herbert Schildt, The Complete Reference Java J2SE 7th Edition, TMH Publishing
Company Ltd, NewDelhi.
2. H.M.Dietel and P.J.Dietel, Java How to Program, Sixth Edition, Pearson
Education/PHI
Reference Books:
1. Cay.S.Horstmann and Gary Cornell, Core Java 2, Vol 1, Fundamentals, Seventh
Edition, Pearson Education.
2. Cay.S.Horstmann and Gary Cornell, Core Java 2, Vol 2, Advanced Features,
Seventh Edition, Pearson Education.
Web References:
1. http://www.javatpoint.com/java-tutoria
2. http://www.javatutorialpoint.com/introduction-to-java/
3. http://www.java2s.com/
E-Text Books:
1. http://bookboon.com/en/java-programming-language-ebooks
2. https://en.wikibooks.org/wiki/Java_Programming
Course Outcomes:
At the end of the course, the students will able to
1. Identify the use of object oriented programming and implement for the scenarios
2. Design solutions using Inheritances, interfaces and packages for real
world problems
3. Analyze Thread life cycle and ability to write Multithreading programs.
4. Make use of Exception Handling Mechanisms to write efficient java programs.
5. Develop Programs using user friendly interface using Applets, AWT
Gudur, Tirupati Dist, AP. (India)

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

Object : Data & Methods


The object may communicate each other like the following.
Object - 1 Object - 2

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


- Platform-independent and portable
- Object oriented
- Robust and secure
- Distributed
- Familiar, simple and small
- Multithreaded
- High performance
- Dynamic and extensible

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.

Distributed:- Java is designed as distributed language for creating applications on network. It


has the ability to share both data and programs over 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.

Multithreaded:- Multithreaded means handling multiple tasks simultaneously.This means that


java supports multi threaded programs. The programmer need not wait for the application to
finish one task before beginning another.

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

Flying Bird Non-Flying Bird

Sparrow Parrot Penguin Kiwi

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

Circle Rectangle Triangle

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.

- Creating classes that define objects and their behaviors.


- Creating objects from class definitions.
- Establishing communication among objects etc.

Ex. Employee . Salary(Name);

Object Message Information

4
Gudur, Tirupati Dist, AP. (India)

Benefits and Applications of OOPs

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.

Advantages (Benefits) are:-

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:

a) Real time applications


b) GUI
c) Multimedia applications
d) Hypermedia, Hyper text applications
e) AI (Artificial intelligence)
f) Networking and parallel programming
g) Decision support Systems(DSS)
h) CAD (Computer Aided Design)
i) CIM (Computer Integrated Manufacturing)

5
Gudur, Tirupati Dist, AP. (India)

Java Program Structure

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

main method class


{
main method definition
}

Documentation Section:- The documentation section consists of comments given name of the
programmer, the author and date details. They are:

Single line comment --- //

Multi line comment ---/* ………………..*/

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.

Ex: import Student.test;

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

A smallest individual unit in a program is known as Tokens. Java has a collection of


tokens to design as program. They are:

- 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

Ex: int n=90


float m=55.786
char c=’@’
Operators: Operator is a symbol, which performs an operation. In java several types of
operators like arithmetic, relational, logical etc.

7
Gudur, Tirupati Dist, AP. (India)

Ex: +, -, >, <, && etc.

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.

In ‘Java’ language, the data types are classified as shown below:

Data Types

Primitive (intrinsic) Non-primitive (Derived)

Numeric Non-Numeric Classes Interface Arrays

Integer Floating-point Character Boolean

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

The size and range of integer types are as follows

Data type Size Minimum value Maximum value

byte 1 -128 127

short 2 bytes -32768 32767

int 4 bytes -2147483648 2147483647

long 8 bytes -9223372036854775808 -9223372036854775807

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:

Data type Size Minimum values Maximum values

float 4 bytes 3.4e-38 3.4e+38

double 8 bytes 1.7e-308 1.7e+308

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.

Rules for naming a variable:


1. A variable name can have alphabets, digits and dollar sign character
2. The variable name must not begin with a digit.
3. Upper case and lower case are distinct. This means that variable total not same as TOTAL.
4. Variable name can be any length.
5. Commas are not allowed
6. Blank spaces are not allowed
7. Special symbols other than underscore are not allowed
8. Keywords must not be used as variable names.
9. A variable name must not be repeated (declaration) in the declaration
Examples:
Valid Variables: a salary sum stud_name c123 etc.
Invalid Variables: a+b ( Special Character present)
2abc ( First letter is not an alphabet)
float ( it is a keyword)

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:-

datatype var1, var2, …. ;

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.

-Assigning a value to a variable at the time of declaring it is called initialisation of


variables. If a variable is not initialised it contains garbage value.
Syntax:

datatype var1= value, var2=value, …. ;

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.

DataInputStream Object = new DataInputStream(System.in);


X = Object. readLine();

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.

Ex: class Scope


{
static int x, y; Global variables
...
..
int a, b; Instance variables
void readData()
{
...............
int z; Local variables
..............
}
void printData()
{
............
............
}
}

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.

Syntax: type variable1=(type) variable2;

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.

Example: float x=20.10f;

int y=(int)x;

y=20;

Automatic Converting:- In java, the small type data is automatically converted into larger type.

Ex: int a = 70;

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.

Ex: long b = 789;

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.

Note:- the Narrowing result may loss of information.

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

% Modulo division (Remainder)

Example: a+b, 5*4 etc.

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

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Examples: a>b, 5<90, n==m

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 AND

¦¦ 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)

4. Increment and Decrement Operators:

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:

Conditional expression ? expression-1 : expression-2;

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:

String s = (age>50) ? “Old Age” : “Young Age”;

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.

This statement is also used as nesting of conditional statements.

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

Ex: (a>b) && (x<y)

(a<b) || (x>y) etc

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

DECISION CONTROL STRUCTURES / CONDITIONAL / BRANCHING


STATEMENTS
These statements are used to execute a statement or group of statements
depending on the given condition. There are mainly two types of conditional statements. They are
1. if or if…else statement
2. switch statement

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 ;

In the above syntax, the condition is a relational/logical/Boolean expression that must be


enclosed within parenthesis. If the condition is true then the statements in the statement-block are
executed, otherwise they are not executed. To specify more than one statement in a statement-
block, they must be enclosed within a pair of flower braces ({}).
Examples:
1. if (avg >= 75) System.out.println(“grade is distinction”);
2. if (a < 0) a++;

’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)

Here, if the condition is true then statement-block1 is executed otherwise statement-block2


is executed.

Example-1:
if (a % 2 = = 0)
System.out.println(“Even number”);
else
System.out.println(“Odd Number”);

Nested ‘if’ Statement/elseif ladder:


When the ‘if’ statement is used within another ‘if’ statement then it is called “nested if”
statement. The general format is as follows:

Syntax:
if (condition1)
{
if (condition2)
statement-block1 ;
else
statement-block2 ;
}
else
{
if (condition3)
statement-block3 ;
else
statement-block4 ;
}

In the above syntax,

i. If ‘condition1’ and ‘condition2’ are true then stament-block1 is executed


ii. If ‘condition1’ is true and ‘condition2’ is false then stament-block2 is executed
iii. If ‘condition1’ is false and ‘condition3’ is true then stament-block3 is executed
iv. If ‘condition1’ and ‘condition3’ are false then stament-block4 is executed

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.

The general format of switch statement is as follows:

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:

Conditional expression ? expression-1 : expression-2;

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:

String s = (age>50) ? “Old Age” : “Young Age”;

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.

This statement is also used as nesting of conditional statements.

ITERATIVE / LOOPING / REPETITIVE STATEMENTS


The iterative statements are used to execute a statement or a group of statements repeatedly
for a specified number of times. The iterative statements are also called repetitive(or)
Loopingcontrol statements.

In 'Java' language, there are 3 types of repetitive control structures. They are

1. While structure
2. Do…while structure
3. For structure

While Statement (while loop):


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 entry control
loop statement. The syntax of while statement is as follows:

22
Gudur, Tirupati Dist, AP. (India)

Syntax:

while (Test Condition)


{
statement-block;
}
In the above syntax,

1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.


2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in braces ({}).
Working: The ‘while’ statement executes all the statements in the statement-block as long as the
given condition true. When the condition false then the loop is terminated and the control is
transferred to the statement after the statement-block.

Example: A program to print first ‘n’ natural numbers.

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;

} while (Test condition) ;

In the above syntax,

1. The ‘condition’ is a relational expression that must be enclosed within parenthesis.


2. The statement-block specifies one or more statements. When there is more than one
statement, they must be enclosed in braces ({}).
Working: The ‘do…while’ statement executes all the statements in the statement-block first and
then tests the condition. When the condition true (non-zero) then the loop is repeated otherwise
the loop is terminated.

Example: A program to print first ‘n’ natural numbers.

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:

for(initialisation ; condition ; increment/decrement)


{
statement-block;
}
Here,

 The initialization specifies assignment statements for the loop variable.


 The condition is a relational expression used to execute statements repeatedly and to terminate
the loop
 Increment/decrement specifies assignment statements used to change the value of the loop
variable.
 The statement-block specifies one or more statements. When there is more than one statement,
they must be enclosed in braces ({}).
Working: It evaluates the statement in initialization part and then it checks the condition. If the
condition is true then it executes all the statements in the statement-block. After executing all the
statements, increment/decrement part is executed. This looping process is continued as long as
condition is true. When the condition is false, the loop is terminated.

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.

Ex: a[ i ] // Here i is an index number.

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.

o Declare the array


o Creating memory locations
o Putting values into memory (initialization)

Declare the array:- the following syntax is used to declare the array.

Syntax: type arrayName[];

27
Gudur, Tirupati Dist, AP. (India)

or

Type []arrayName;

Ex: int a[];

Or

int [] a;

Creating memory locations:- the following syntax is used to create memory location to the array.

Syntax: arrayName = new Type[size];


Or
Type arrayName = new type[size];
Ex: a = new int[5]; or int a[] = new int[5];

Putting values into memory: the following syntax is used to put values to the arrays.

Syntax: type arrayName[] = {list of values};

Ex: int a[] = {1,2,3,4,5};

Example program for 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.

- Declare the tow dimensional array.


int a[][]; or int [][] a;
- Creating memory locations.

a = new int [2][2] or int a[][]=new int [2][2];

- Initialization of two dimensional arrays.

int a[][]= {{1,2},{3,4}}

Example program for two dimensional array.

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)

c[i][j]=c[i][j] + a[i][k] * b[k][j];


}
}
}
System.out.println(“Matrix is”);
for(i=0; i<2; i++)
{
for(j=0; j<2;j++)
{
System.out.print(“ ”+c[i][j]);
}
System.out.println();
}
}
}
CLASSES

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.

Syntax:- class ClassName [extends SuperClassName]


{
[fields declaration]
[methods declaration]
}
In the above syntax ClassName and SuperClassName are any java identifiers. The keyword
extends is used to derive the properties of SuperClassName to the ClassName. This type of process
is known as inheritance.

Example:- class Person


{
String name;
int age;
void getdata()
{
--------
}

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.

Example:- class Person


{
String name;
int age;
}
In the above example the field names and age are also known as members of the class person.

Syntax:- datatype fields;

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.

Syntax:- returntype methodName([parameter list])


{
Method body;
}
In the above syntax the returntype represents which type of data has to return of that
method. The method name is an identifier. The parameter first represents number of parameters
with their data types. Finally body represents the number of statements.

Examole:- void getData(String n, int a)


{
Name=n;
Age=a;
}
Creating objects:- An object in java is essentially a block of memory that contains space to
store all the instance variables. The new operate is used to create object of specified class. The
general form of object is as follows.

Syntax:- ClassName object;

Object=new ClassName ();

(or)

31
Gudur, Tirupati Dist, AP. (India)

ClassName object=new ClassName ();

In the above syntax the keyword new is used to create object

Example:- Person p=new Person();

Here ‘p’ is an object of that class Person

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.

Example:- p.name= “Nani”

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)

CONCEPTS OF CLASSES, OBJECTS

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.

A class in java can contain:


• data members
• methods
• constructors
• nested class and
• interfaces

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

A Constructor is a special type of method in java. It is similar to method. It is used to


initialize the instance variables or object. To do this, we follow the following.

- Constructor name and class name should be same.


- Constructor may have or may not have parameters.
- A constructor does not return any value, not even void.
- A constructor automatically called and executed at the time of creating Objects.
- A constructor is called and executed only once per object.

33
Gudur, Tirupati Dist, AP. (India)

Example: class Rectangle


{
int length;
int width;
Rectangle (int x, int y)
{
length = x;
width = y;
}
}
Types of Constructors:- Java supports different types of constructors depending on the
parameter list. They are:

 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.

Ex: Rectangle(int a, int b)


{
…………….
……………
}
Example program for 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.

There are four types of Java access controls:

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).

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

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.

OVERLOADING METHODS AND CONSTRUCTORS

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.

Ex: class Sample


{
static int xs
static void getData()
{
……………..
}
}
In the above example, the members are declared as static. So that they are accessed directly
by the class name rather than object name. The static variables are also available for other classes.
They are also called as general variables.

Ex: class Operation


{
static float x,y;
static float mul()
{
Return (x * y);
}

40
Gudur, Tirupati Dist, AP. (India)

static float div()


{
Return (x / y);
}
}
class MyOperation
{ public static void main(String args[])
{ float a, b;
Operation.x=150.75f;
Operation.y=70.8f;
a = Operation.mul();
b = Operation.div();
System.out.println(“Multiplication = “ + a);
System.out.println(“Division = “ + b);
}
}
In the above example, the static members have called directly by the class name
Operation. Static members have several restrictions (rules). They are.

- A static method can only call another static method.


- The static method can only access static data.
- The static can’t refer to this or super at anywhere.

STRINGS HANDLING

A string is a collection of characters, which are enclosed with in double quotes.


or
A string represents a sequence of characters that are implemented with string operations
like length, copy, reverse, concatenation etc.
The general form of string declaration is as follows.

Syntax: String stringName;


stringName = new String (“String”);
ex: String str;
str = new String(“B.Tech.”);
or
Syn: String stringName = new String(“String “);
Ex: String str = new String(“B.Tech.”);
String Methods: A String class defines a number of methods to manipulate strings.

41
Gudur, Tirupati Dist, AP. (India)

Sl.no Method Description


1 S1=s.toLoweCase Converts the s to all lower case
2 S1=s.toUpperCase Converts the s to all upper case
3 N=s.length Gives the length of s
4 S.concatenate(s1) Concatenates s and s1
5 s.compaeTo(s1) Compare, return negative if s<s1, positive if s>s1, if
equals return zero
6 s.charAt(x) Gives x th character of s
7 s.indexOf(x) Gives the position of x in the string s
8 s.equals(s1) Return true if s == s1
9 s.substring(n) Gives substring starting of nth character

Example program for Strings

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.

FileInputStream This class provides methods to read bytes from a file.

FilterInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.

ObjectInputStream This class provides methods to read objects.

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

The java.io package provides CharacterStream classes to overcome the limitations of


ByteStream classes, which can only handle the 8-bit bytes and is not compatible to work directly
with the Unicode characters. CharacterStream classes are used to work with 16-bit Unicode
characters. They can perform operations on characters, char arrays and Strings.

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.

InputStreamReader This class provides methods to convert bytes to characters.

PipedReader This class provides methods to read characters from the connected piped
output stream.

StringReader This class provides methods to read characters from a string.

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

Hierarchical abstraction is a process of Reusability of an existing class without redefining


the same once again. The mechanism of deriving a new class from old class is called Interface.
The Old class is known as Base class or Super class or Parent class. The new one is known as
Derived class or sub class or Child class. Finally, in inheritance the object of one class acquire the
properties of another class.

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

Defining subclasses:-To define a subclass, we follow the following syntax

class SubclassName extends SuperclassName


{
Fields declaration;
Methods declaration;
}
In the above syntax, the keyword extends specifies the properties of SuperclassName are
extended to SubclassName.

Ex: class Room


{
int length;
int breadth;
Room(int x, int y)
{

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

B - Semi Derived Classes

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)

MEMBER ACCESSS RULES

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)

protected: If protected access modifier is applied to an instance variable, method or with a


constructor inside a class then they will be accessed inside the package only in which class is
present and, in addition, by a sub class in another package.

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.

Syntax: final datatype variable = values;

Ex: final int size = 100;

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.

Syntax: final returntype methodName()


{
……………..
}
Ex: final void display()
{
…………………
}
Final Classes:- The class is defined as final, which is never be sub-classed. The final class helps
us to create a secured programs, which is never be accessed by the others. The general form of
final class is as follows.

Syntax: final class ClassName


{
………………………
}
Ex: final class NonDerived
{
…………………….

51
Gudur, Tirupati Dist, AP. (India)

}
Example program for final fields, methods and classes

final class Final


{
final float PI = 3.14f;
final void display()
{
System.out.println(“The PI value is = “ + PI);
}
}
class ExFinal
{
public static void main(String args[])
{
Final f = new Final(); //Here final class never be derived
f.display();
}
}

OBJECT CLSS AND ITS METHOS


Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class. If a class does not extend any other class then it is a direct child
class of Object and if extends another class then it is indirectly derived. Therefore the Object
class methods are available to all Java classes. Hence Object class acts as a root of inheritance
hierarchy in any Java Program.

 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: abstract class Shape


{
abstract void draw();
……………………………..;
}
In the above example, the method draw() is an abstract method. Like the above, we may
create mother then one method and all are should be declared as an abstract. While using abstract
classes, we should follow the following rules.

- We can’t use abstract classes to instantiate objects directly.


- The abstract methods of an abstract class must be defined in its sub-classes.
- We can’t declare abstract constructors or abstract static methods.

Ex:

abstract class Shape


{
abstract void draw();
}
class Line extends Shape

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)

INTERFACE or MULTIPLE INHERITANCE

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.

The general form of interface is as follows.

Syntax: interface InterfaceName


{
fields;
methods;
}
In the above syntax, the interface is keyword and “interfaceName” is name of the
interface. The variables are declared as constant and methods are as abstract.

*Note:- Interface supports multi-inheritance because we can derive a class from more than one
interface.

Example:- interface Area


{
final float PI = 3.142f;
float compute(float x, float y);
}
In the above example, variable PI is a constant and method compute is public abstract method.

Ex:- interface Area


{
final float PI = 3.142f;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Area
{
Public float compute(float x, float y)
{
return(PI +x*y);
}

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.

Syntax:- interface interfacename2 extends interfacename1


{
Body of interface
}
Example : interface Area2 extends Area1
{
final float PI = 3.142f;
float computer(float x, float y);
}
Implementing Interfaces :-Interfaces are used as superclasses whose properties are inherited by
classes.
Syntax : class Classname implements interfacename
{
body class
}
Example:- interface Area2 extends Area1
{
final float PI = 3.142f;
float compute(float x, float y);
}
Syntax : class Classname implements Interfacename
{
body class
}

57
Gudur, Tirupati Dist, AP. (India)

Example :- class Circle implements Area


{
float compute(foat x ,float y)
{
return(PI*x*y);
}
}
Here the classname implements the interfacename. We may implement more than one
interface like the following.

Syntax :-

Class classname superclassname implements A,B,C


{
body of class
}
Accessing the interface Variables:- The variables of interface are declared as constants. So that
they are available to any class that implements the interface.

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)

class Marks extends Student


{
float mark1,mark2;
void getMark(float x, float y)
{
mark1 = x;
mark2 = y;
}
void putMark( )
{
System.out.println(“Mark-1: “ + Mark1);
System.out.println(“Mark-2:” + Mark2);
}
}
interface Sports
{
float swt = 6.0f;
void putSwt( );
}
class Results extends Marks implements Sports
{
float total;
public void putSwt( );
{
System.out.println(“Sports Weight :”+swt);
}
void display( )
{
total = mark1 + Mark2 + swt;
putNo( );
putMark( );
putSwt( );
System.out.println(“Total Score:”+total);
}
}
class ExInherit
{
Public state void main(String args[ ])
{

Results stu = new Results ( );


stu.getNo(101);
stu.getMark(17.3f, 85.6f);
stu.display( );

59
Gudur, Tirupati Dist, AP. (India)

}
}
Difference between Class and Interfaces

CLASS

1. The Keyword class is used to create classes.


2. Classes may/may not derived.
3.The members of class can be constants (or) not.
4.The methods of class may or may not abstract.
5.It can be declared object.
6.It can use various access specifiers like public, private, protected.
7.class ClassName
{
Body of class
}
8.classes doesn’t support multiple – inheritance.
9. The keyword extends is used to extends the class.

INTERFACE:-

1. The keyword interface is used to create interfaces.


2.The interfaces should be implemented.
3.The members of interface should be constants.
4.The methods of interface should be public and abstract.
5.It cant be declared object.
6.It can only accept public specifier.
7. interface InterfaceName
{
body of interface
}
8.Interface supports multi-inheritance.
9.The keyword implements is used to implements interfaces.

PACKAGES

A package represents a directory that contains related group of classes and interfaces.
Java supports two types of Packages.

 Pre – defined packages(API Packages).


 User – defined 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

lang util io awt net apple

The following table shows the packages and their content.

Package Name Content


java.lang Language supports classes and interface for datatypes, strings etc
java.util Utility classes and interfaces such as vectors, date etc.
java.io This package supports input and output classes and interfaces.
java.awt To implement graphical user interfaces such as windows ,buttons etc.
java.net Networking supports classes & interfaces.
java.applet This package is used to create applets only.
Example :-

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);

Package class method

Creating Packages and Accessing Packages

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.

The general form of package creation is as follows.

Syntax : package packageName;


public class ClassName
{
Body of class

61
Gudur, Tirupati Dist, AP. (India)

}
In the above syntax packageName is the name directory and class name is filename.

Example : package BTech;


public class Study
{
int x;
public void getMTech( )
{
}
}
The following steps must be follow to create our own packages.

*Declare the package at the beginning of program.


*Define a class with public access specifier.
*Create a Sub-directory under the directory; the main source files are stored.
*Save the classname.java in the sub-directory.
*Compile the file in Sub directory.

Accessing the package:-To access the package, we use the keyword “import”.

The general form of import statement is as follows.


Syntax:- import package1.package2.package3..ClassName;
Example : importpack.sum;
In the above example pack is packageName and sum is ClassName.
Example :

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.

Then import the package to next program.

import pack.Fact;
class Fnumber
{
public static void main(String args[ ])
{
Fact f = new Fact( );
f.getFact(5);
}
}
UNDERSTANDING CLASSPATH

CLASSPATH is an environment variable which is used by Application ClassLoader to


locate and load the .class files. The CLASSPATH defines the path, to find third-party and user-
defined classes that are not extensions or part of Java platform. Include all the directories which
contain .class files and JAR files when setting the CLASSPATH.

We need to set the CLASSPATH if:

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

 Compile time errors.


 Run-Time errors.

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.

The following are the most commonly occurring problems.

 Missing – Semicolon.
 Missing – double – quotes.
 Misspelling keywords.
 Use of undeclared variables.
 Missing brackets in classes and methods etc.
 Improper placement of braces.

Example: class Example


{
System.out.println(“Hello World”) // Missing Semicolon.
}
2.Run - Time Errors : Sometimes, a program may compile successfully but not run properly.
Such programs may produce wrong results. These are called run – time errors.

The following are most commonly occurring errors.

->Dividing an integer by Zero.


->Accessing an element that is the out of bounds of Array.
->Converting invalid string to a number etc.
->Trying to change the state of a thread illegally.

Example: class Example


{
int x; //variable.

65
Gudur, Tirupati Dist, AP. (India)

x =5/0; //division by zero.


}

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.

Try block Exception object creation


statements that
causes an
exception
Throws
exception object
Catch block
statements that
handle the Exception handler
exception

The general form of try and catch block is as follows.


Syntax :- ---------
----------
try
{
Statement;
}
catch(Exception-type e)
{
Statement;
}
In the above syntax the try-block can have one or more statements that could generate an
exception. If anyone statement generate an exception, the reaming statements in the block are

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)

BENEFITS OF EXCEPTION HANDLING


1. Exception handling ensures that the flow of the program is maintained when an exception
occurs.
2. By this we can identify the types of errors.
3. By this we can write the error-handling code separately from the normal code.
EXCEPTION HIERARCHY
The class at the top of the exception class hierarchy is the Throwable class, which is a
direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error.

The diagram below shows the standard exception and error classes defined in Java,
organized in the Java exceptions hierarchy:

Multi - Catch Statements

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)

System.out.println(“Value of x:” + x);


}
}
Finally Statements

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.

The general form of finally statement is as follows.

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

class CustomException extends Exception {


String message;
CustomException(String str) {
message = str;
}
public String toString() {
return ("Custom Exception Occurred : " + message);
}

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.

Syntax: public void run( )


{
………………..
Statement(s);
……………………
}
Extending the thread class :

We can extend the class from java.lang.Thread to do this. We follow the following steps.

 Declaring the class.


 Implementing the run( ) method.
 Starting the thread.

Declaring the class :The thread class can be extended like the following.

72
Gudur, Tirupati Dist, AP. (India)

class Mythread extends Thread


{
………..
…………..
}
Implementing the run( ) method : The run method is used to implements the thread concepts.
The run( ) method is implemented like the following.

public void run( )


{
----------------
-----------------
}
Starting the Thread : Starting a new thread. The run method is involved with the help of
another method is known as start( ).
The general form of start( ) method is as follows
MyThread mt = new Mythreaad( );
mt.start( );
Example Program:
class A extends Thread
{
Public void run( )
{
for(int i = 0;i<5;i++)
{
System.out.println(“Thread A :”+i);
}
}
Class B extends Thread
{
public void run( )
{
for(int i = 0;i<5;i++)
{
System.out.println(“Thread B :”+i);
}
}
}
Class Mythreads
{
Public static void main(String args[ ])
{

73
Gudur, Tirupati Dist, AP. (India)

A a= new A( );
B b=new B( );
a.start( );
b.start ( );
}
}

Stopping And Blocking A Thread


A thread may be stopped (or) blocked at any stage. To do this , we follow the
following steps.

 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( );

Sleep( ): This method is to sleep the thread for a specific time.

Syntax: Threadname.sleep(time in milli-secs);

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( );

Ex: class Sleeping extends Thread

{ public void run( )


{ for(int i = 0; i<=10;i++)
{ System.out.println(sample Thread : “ + i );
try{
sleep(1000);
}catch(Exception e){ }
}
}
}

class MySleeping
{ public static void main(String args[ ])
{ Sleeping s = new Sleeping( );
s.start( );
}}

Life Cycle Of Thread:-

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.

->For Running , We use start( ) method.

->For killing, We use stop method.

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.

Ex: class A extends Thread


{
Public void run( )
{
for(int i = 1; i<= 5; i++)
{
if(i==3)yield( );
System.out.println(“Thread A:” + i);
}
}
}
class B extends Thread
{
public void run( )
{
for(int i = 1; i<= 5; i++)
{
if(i==3)Stop( );
System.out.println(“Thread B:” + i);
}
}
}
class LCycle
{
Public static void main(String agrs[ ])
{
A a= new A( );
B b= new B( );
a.start( );
b.start( );
}
}

77
Gudur, Tirupati Dist, AP. (India)

SYNCHRONIZATION

In a multithread program, a resource may be used by more than one thread


simultaneously. For example, one thread may try to read a record from a file while another still
writing to the same file. In this situation, we may get strange results.

To overcome this drawback, we use a technique known as synchronization. In java, the


keyword synchronizedhelps to solve such problems by keeping a watch on such location. The
general form of synchranized is as follows.

synchronized void update() {

………..

………… // code here to synchronized

………..

synchronized (lock-object) {

………..

………… // code here to synchronized

………..

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:

Sr.No. Method & Description

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.

Points to remember for Daemon Threads

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:

public class TestDaemonThread1 extends Thread{


public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
THREADGROUP
Java provides a convenient way to group multiple threads in a single object. In such a
way, we can suspend, resume or interrupt a group of threads by a single method call.

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.

ThreadGroup tg1 = new ThreadGroup("Group A");


Thread t1 = new Thread(tg1,new MyRunnable(),"one");

82
Gudur, Tirupati Dist, AP. (India)

Thread t2 = new Thread(tg1,new MyRunnable(),"two");


Thread t3 = new Thread(tg1,new MyRunnable(),"three");

DIFFERENCES BETWEEN MULTI THREADING AND MULTITASKING

Multitasking Multithreading

While in multithreading, many threads are


In multitasking, users are allowed to created from a process through which computer
perform many tasks by CPU. power is increased.

Multitasking involves often CPU While in multithreading also, CPU switching is


switching between the tasks. often involved between the threads.

In multitasking, the processes share While in multithreading, processes are allocated


separate memory. the same memory.

The multitasking component involves While the multithreading component does not
multiprocessing. involve multiprocessing.

While in multithreading also, a CPU is provided


In multitasking, the CPU is provided in in order to execute many threads from a process
order to execute many tasks at a time. at a time.

In multitasking, processes don’t share


the same resources, each process is While in multithreading, each process shares the
allocated separate resources. same resources.

Multitasking is slow compared to


multithreading. While multithreading is faster.

In multitasking, termination of a process While in multithreading, termination of thread


takes more time. takes less time.

Isolation and memory protection exist in Isolation and memory protection does not exist
multitasking. in multithreading.

83
Gudur, Tirupati Dist, AP. (India)

Multitasking Multithreading

It helps in developing efficient It helps in developing efficient operating


programs. systems.

84
Gudur, Tirupati Dist, AP. (India)

UNIT –IV

APPLETS

Applet is a small program which is developed for internet applications. An applet is


located on a remote computer (server) can be downloaded via internet and executed on a local
computer (client) using a java capable browser such as HotJava.

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)

DIFFERENCES BETWEEN APPLETS AND APPLICATIONS

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.

- Applets do not use main() methods


- Applets cannot run independently, they are run thru HTML code.
- Applets cannot read/write files from local computers
- Applets cannot communicate with other servers on the network.
- Applets cannot run any program from the local computer.
- Applets cannot run methods which are in other languages like C or C++

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.

Syntax : public void paint(Graphics g)

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.

Example : import java.awt.*;

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)

Applet Life Cycle


Applet is a small program, which is developed for internet applications. During lifetime
of an applet, there are many states it can enter. They are:

*Born (or) Initialization state.

*Running State.

*Idle state.

*Dead or Destroy 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.

Born(or)Initialization State:- When we load applet(begin), it enters into the initialization


state. In this state, we may do the following tasks.

*Create objects needed by the applet.


*Setup initial values.
*Load images(or)fonts.
*Setup colors etc.

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.

Syntax:public void init( )


{
-----------
------------ // Action
}
*Running State:- After initializing the applet, it enters into running state by calling start( )
method automatically. It may occur once again if the applet is already in idle state. The start( )
method is called more than once for an applet while leaving and return back to the page. The
general form of start( ) method is as follows.

Syntax : public void start( )


{
----------- \\Action
------------
}
*Idle(or)Stopped State :- After calling method, applet becomes idle state. It is automatically
calls while leaving the page. The stop( ) method is called more than once for an applet. The
general form of stop( ) method is as follows.

Syntax: public void stop( )


{
----------- //Action
------------
}
*Dead State:- An applet is said to be dead when it is removed from memory. This is achieved by
invoking the destroy( ) method. It occurs only once for applet. The general form of destroy( )
method is as follows.

Syntax : public void destroy( )


{
----------//Action
-----------
}
*Display State:- The display state is nothing but displaying information on screen. The Paint( )
method helps us to performs some output operations on the screen. The general form of paint
method is as follows.

89
Gudur, Tirupati Dist, AP. (India)

Syntax : public void paint(Graphics g)


{
------------ //Action
-------------
}
Example Program:

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>

PASSING PARAMETERS TO APPLETS


Passing parameters to applet feature specify extra information that can be passed to an
applet from the HTML page. To do this we use param tag from HTML and getParameter() from
Applet code to passing the parameters.

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:

<param name=”name” value=”Ramesh” />


<param name=”age” value=”25″ />

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:

String getParameter(String param-name)

Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:
import java.awt.*;

import java.applet.*;

public class MyApplet extends Applet


{

String n;

String a;
public void init()

{
n = getParameter("name");

a = getParameter("age");
}

public void paint(Graphics g)

{
g.drawString("Name is: " + n, 20, 20);

g.drawString("Age is: " + a, 20, 40);


}

91
Gudur, Tirupati Dist, AP. (India)

<applet code="MyApplet" height="300" width="500">

<param name="name" value="Ramesh" />

<param name="age" value="25" />

</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.

 A click on button, checkbox, radio button.


 Selecting a menuitem or list item.
 Clicking or movement of a mouse.
 Entering or editing the data in a textfield.
DELEGATION EVENT MODEL

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 -

public void addEventTypeListener(EventTypeListener e1)

where, EventType could be replaced by the name of the type of event.

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 Description


ActionEvent is generated when a source such as a button is
ActionEvent clicked, an item in the list is double-clicked or when a menu
item is selected.
ItemEvent is generated when a source such as a checkbox
ItemEvent
is clicked to check/uncheck it or when a list item is clicked.
KeyEvent is generated when a source such as a key on the
KeyEvent
keyboard pressed in a textfield or a textarea.
MouseEvent is generated when a source such a mouse is
MouseEvent moved, dragged, enters/exits a specific window or when it's
button is clicked/released.
TextEvent is generated when a data in textarea or textfield
TextEvent
is changed.
AdjustmentEvent is generated when a scrollbar is dragged
AdjustmentEvent
around.
WindowEvent is generated when a source such as a
WindowEvent window is activated, minimized, brought up, deactivated
and closed.

EVENT CLASSES AND EVENT LISTENERS

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)

Event Classes Event Listener Interface

ActionEvent ActionListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener

HANDLING MOUSE AND KEYBOARD EVENTS

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.

MouseListener interface has the following methods.

 void mouseClicked(MouseEvent e): void MouseClicked this method is invoked when


the mouse button has been clicked(pressed and released) on a component.
 void mouseEntered(MouseEvent e): this method is invoked when the mouse enters a
component.
 void mouseExited(MouseEvent e): this method is invoked when the mouse exits a
component
 void mousePressed(MouseEvent e): this method is invoked when a mouse button has
been pressed on a component.
 void mouseRelease(MouseEvent e): this method is invoked when a mouse button has
been released ona component.
MouseMotionListener interface has the following methods.

1. void mouseDragged(MouseEvent e): this method is invoked when a mouse button is


pressed on a component and then dragged.
2. void mouseMoved(MouseEvent e): this method is invoked when a mouse cursor has
been moved onto a component and then dragged.
The MouseEVent class has the following methods

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)

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

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.

Adapter class Listener interface

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)

Syntax of Inner class

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.

Label l= new Label(“This is a Text”);

Button: Button class is useful to create Push buttons. It is useful to perform a particular action.
The following example shows the Button creation.

Button b=new Button(“Click Me”);

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.

public class Canvas extends Component implements Accessible

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.

public class Scrollbar extends Component implements Adjustable, Accessible

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.

TextField t = new TextField()

TextArea: It is another text component, we helps us to create text as multiple line. The following
example shows the creation of TextArea.

TextArea ta = new TextArea(rows, cols);

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.

CheckBox cb = new CheckBox();

CheckboxGroup: The object of CheckboxGroup class is used to group together a set


of Checkbox. At a time only one check box button is allowed to be in "on" state and remaining
check box button in "off" state. It inherits the object class.

CheckboxGroup cbg = new CheckboxGroup();

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.

Choice c = new Choice();

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.

List<String> list=new ArrayList<String>();

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.

Panel panel=new Panel();

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.

public class Dialog extends Window

MenuBar: A Menu represents a group of options for the user to select from. JMenu class is used
to create menu bar.

JMenuBar mb=new JMenuBar();

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

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.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING

101
Gudur, Tirupati Dist, AP. (India)

5. public static final int TRAILING

3. GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout Class

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.

Constructors of CardLayout Class

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

5. GridBagLayout class is used to align components vertically, horizontally or along their


baseline.

public class GridBagLayoutExample extends JFrame{


GridBagLayoutExample a = new GridBagLayoutExample();

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.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

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.

No. Java AWT Java Swig

1) AWT components are platform- Java swing components are platform-


dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.

4) AWT provides less components than Swing provides more powerful


Swing. components such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model Swing follows MVC.


View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

MVC ARCHITECTURE IN JAVA

The Model-View-Controller (MVC) is a well-known design pattern in the web


development field. It is way to organize our code. It specifies that a program or application shall
consist of data model, presentation information and control information. The MVC pattern needs
all these components to be separated as different objects.

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.

What is MVC architecture 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.

The MVC pattern architecture consists of three layers:

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.

Advantages of MVC Architecture

The advantages of MVC architecture are as follows:

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.

Implementation of MVC using Java

To implement MVC pattern in Java, we are required to create the following three classes.

o Employee Class, will act as model layer


o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers


Model Layer

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

A Container is a component that can container SWING


Container Components

A JComponent is a base class for all swing UI Components In


order to use a swing component that inherits from JComponent,
component must be in a containment hierarchy whose root is a
JComponent top-level Swing container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls designed to allow


JColorChooser the user to manipulate and select a color

A JCheckBox is a graphical(GUI) component that can be in


JCheckBox either an on-(true) or off-(false) state

The JRadioButton class is a graphical(GUI) component that can


JRadioButton be in either an on-(true) or off-(false) state. in the group

106
Gudur, Tirupati Dist, AP. (India)

Class Description

A JList component represents the user with the scrolling list of


JList text items

A JComboBox component is Presents the User with a show up


JComboBox Menu of choices

A JTextField object is a text component that will allow for the


JTextField editing of a single line of text

A JPasswordField object it is a text component specialized for


JPasswordField password entry

A JTextArea object s a text component that allows for the


JTextArea editing of multiple lines of text

A ImageIcon control is an implementation of the Icon interface


Imagelcon that paints Icons from Images

A JScrollbar control represents a scroll bar component in order


JScrollbar to enable users to Select from range values

JOptionPane provides set of standard dialog boxes that prompt


JOptionPane users for a value or Something

A JFileChooser it Controls represents a dialog window from


JFileChooser which the user can select a file.

As the task progresses towards completion, the progress bar


JProgressBar displays the tasks percentage on its completion

A JSlider this class is lets the user graphically(GUI) select by


JSlider using a value by sliding a knob within a bounded interval.

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.

Sr.No. Container & Description

Panel: JPanel is the simplest container. It provides space in which any other component
1
can be placed, including other panels.

2 Frame: A JFrame is a top-level window with a title and a border.

3 Window: A JWindow object is a top-level window with no borders and no menubar.

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.

public class ExApplet extends JApplet

JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame


class. JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.

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)

JFrame frame = new JFrame("JFrame Example");


JComponent

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.

class MyJComponent extends JComponent


{
------------------
}

LABELS AND ICONS

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

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.

JLabel lb= new JLabel(“Enter Text”);

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.

JTextField t1=new JTextField("Welcome to Java.");

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.

JButton b=new JButton("Click Me");

JCheckBox

JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected .


It displays it state to the user . JCheckBox is an implementation to checkbox . JCheckBox
inherits JToggleButton class. The following example is used to create the Check Box.

JCheckBox c1 = new JCheckBox("Check Box");

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.

JRadioButton r1=new JRadioButton("A) Male");


JRadioButton r2=new JRadioButton("B) Female");

JComboBox

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class .


JComboBox shows a popup menu that shows a list and the user can select a option from that
specified list . JComboBox can be editable or read- only depending on the choice of the
programmer. The following example shows the process of combo boxes.

String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);

110
Gudur, Tirupati Dist, AP. (India)

JTabbedPane

The JTabbedPane class is used to switch between a group of components by clicking on a


tab with a given title or icon. It inherits JComponent class. The declaration of Tabbed pane is as
follows.

public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingCon


stants

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. The following example is used to shown the scroll pane.

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);
JTree

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.

public class JTree extends JComponent implements Scrollable, Accessible


.

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.

String data[][]={ {"101","Ravi","670000"},


{"102","Kumar","780000"},
{"101","Ji","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);

111
Scanned by CamScanner
Scanned by CamScanner

You might also like