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

Java Full Notes

1) The document discusses different programming language paradigms including monolithic, procedural, structured, and object-oriented languages. It provides examples of languages that fall under each paradigm. 2) Object-oriented programming (OOP) is introduced as a paradigm that models the real world using objects that encapsulate both data and behaviors. Key concepts of OOP like classes, objects, encapsulation, inheritance and polymorphism are defined. 3) The core principles of OOP - messaging between objects, responsibilities, methods, classes/instances, and class hierarchies - are explained using an example of sending flowers to a friend.

Uploaded by

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

Java Full Notes

1) The document discusses different programming language paradigms including monolithic, procedural, structured, and object-oriented languages. It provides examples of languages that fall under each paradigm. 2) Object-oriented programming (OOP) is introduced as a paradigm that models the real world using objects that encapsulate both data and behaviors. Key concepts of OOP like classes, objects, encapsulation, inheritance and polymorphism are defined. 3) The core principles of OOP - messaging between objects, responsibilities, methods, classes/instances, and class hierarchies - are explained using an example of sending flowers to a friend.

Uploaded by

swapna sri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 233

II YEAR B.Tech.

CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-I: Object Oriented Thinking: Need for OOP paradigm, A way of viewing
world – Agents, responsibility, messages, methods, classes and instances, class hierarchies
(Inheritance), method binding, overriding and exceptions, summary of OOP concepts, coping
with complexity, abstraction mechanisms.

PROGRAMMING LANGUAGES INTRODUCTION

Programming languages are classified into the following categories.


1. Monolithic programming languages
2. Procedural programming languages
3. Structure programming languages
4. Object Oriented programming languages

1. Monolithic programming languages: In monolithic programming languages,


entire lines of codes are in sequential order. It contains number of lines of data.

1 ---
2 ---
.
.
100 ---

Drawbacks: 1. It is not subroutine concept.


2. The program code is duplicated each time that is to be used.

Ex: Assembly Language, Basic etc.,

2. Procedural programming languages: The important features of procedural


programming languages are:

 Emphasis on algorithm rather than data.


 Programs are organized in the form of subroutine.
 Data move overly around the system from function to function
 It follows top-down approach in program design
 It is suitable for medium size software applications.

GLOBAL DATA

Function Function

Drawbacks: 1. Data security problem.

RAKESH.C.M Page 1
2. Difficult to maintain program code.
3. It doesn’t model to support real world problems.

Ex: FORTRAN, COBOL etc.,

3. Structure programming languages: In structured programming languages


programs consists of multiple modules and each module has a set of functions of
related types. The important features of structured programming languages are:

 Programs are divided into individual procedures that perform discrete tasks.
 Procedures are independent of each other.
 Procedures have their own local data and processing logic.
 Introduction of the concepts of user defined data types.
 Maintenance of a large software system.

GLOBAL DATA

DATA DATA

FUN FUN

MODULE1 MODULE2

Drawbacks: 1. Data security problem.


2. It doesn’t model to support real world problems.

Ex: PASCAL, C etc.,

4. Object Oriented programming languages: The important features of object


oriented programming languages are:

 Programs are divided into objects.


 Functions that operate on the data of an object are together in the data
structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data can be easily added to the functions whenever necessary.
 It follows bottom-up approach in program designing.

OBJECT A OBJECT B

RAKESH.C.M Page 2
DATA Communication DATA

FUNCTION FUNCTION

DATA

FUNCTION

OBJECT C

Ex: C++, JAVA etc.,

Object Oriented Programming:

OBJECT-ORIENTED PROGRAMMING (OOP) represents an attempt to


make programs more closely model the way people think about and deal with the
world.
Object-Orientation is a set tools and methods that enable software engineers to
build reliable, user friendly, and maintainable, well documented, reusable software
systems that fulfill the requirements of its users. It is claimed that object-orientation
provides software developers with new mind tools to use in solving a wide variety of
problems. Object-orientation provides a new view of computation.

Object Orientation as a New Paradigm:

Consider an example of real-world problem as:


Suppose we want to send flowers to a friend named Robin who lives in
another city. To solve this problem we simply walk to our nearest florist run by, lets
say, Fred. We tell Fred the kinds of flowers to send and the address to which they
should be delivered.

Now, lets examine the mechanisms used to solve your problem.

• You first found an appropriate agent (Fred, in this case) and you passed to
this agent a message containing a request.
• It is the responsibility of Fred to satisfy the request.
• There is some method (an algorithm or set of operations) used by Fred to do
this.
• We do not need to know the particular methods used to satisfy the request
such information are hidden from view.
Agents and Communities

RAKESH.C.M Page 3
“An object-oriented program is structured as community of interacting
agents called objects. Each object has a role to play. Each object provides a service
or performs an action that is used by other members of the community.”

Messages and Responsibilities

Action is initiated in object-oriented programming by the transmission of a


message to an agent (an object) responsible for the actions. The message encodes the
request for an action and is accompanied by any additional information
(arguments/parameters) needed to carry out the request. The receiver is the object to
whom the message is sent. If the receiver accepts the message, it accepts
responsibility to carry out the indicated action. In response to a message, the receiver
will perform some method to satisfy the request.

Classes and Instances

“A class is a blueprint that defines the variables and the methods common to
all objects of a certain kind.”

In object-oriented software, it’s possible to have many objects of the same


kind that share characteristics: rectangles, employee records, video clips, and so on. A
class is a software blueprint for objects. A class is used to manufacture or create
objects.

Objects

In object-oriented programming we create software objects that model real


world objects. Software objects are modeled after real-world objects in that they too
have state and behavior. A method is a function associated with an object.
Real-world objects share two characteristics: State and Behavior.
Example:
Students have state (name, student number, courses they are registered for,
gender) and behavior (take tests, attend courses, write tests, party).

“An object is a software bundle of variables and related methods.”


An object is also known as an instance. An instance refers to a particular
object.

Object

RAKESH.C.M Page 4
Object Oriented Programming Concepts

The important concepts of OOP are:

a) Encapsulation
b) Abstraction
c) Inheritance
d) Polymorphism

a) Encapsulation: The mechanism by which the data and functions are bound
together with an object definition. By means of encapsulation, it is possible to protect
the data.

b) Abstraction: It is the process of defining a new data type called abstract data
type (ADT) with the principle of data hiding.
ADT refers to the program defined data type together with a set of operations
that can be performed on the data.
Data hiding is a property where the internal data structure of an object is
hidden from the rest of the program.

c) Inheritance: Inheritance is the mechanism to allow the user to derive new


classes from existing classes. With this, a child class will inherit attributes from a
parent class higher in the structure.

d) Polymorphism: Polymorphism refers to one name multiple forms. It allows the


user to give a single name to different methods with different parameters. Depending
on the parameters only one particular method is executed.

Object Based Programming = Data Encapsulation


+
Data Hiding
+
Polymorphism (Overloading)
Ex: ADA

Dynamic Binding: When a method is called with in a program, it associated with


the program at run time rather than at compile time is known as dynamic binding.

Object Oriented Programming = Object Based Programming


+
Inheritance
+
Polymorphism (Dynamic Binding)

Ex: C++, JAVA etc.,

RAKESH.C.M Page 5
Summary of Object-Oriented Concepts

1. Everything is an object.
2. Computation is performed by objects communicating with each other,
requesting that other objects perform actions. Objects communicate by
sending and receiving messages.
A message is a request for action bundled with whatever arguments may
be necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a
grouping of similar objects, such as integers or lists.
5. The class is the repository for behavior associated with an object. That is,
all objects that are instances of the same class can perform the same
actions.
6. Classes are organized into a singly rooted tree structure, called the
inheritance hierarchy. Memory and behavior associated with instances of
a class are automatically available to any class associated with a
descendant in this tree structure.

***

RAKESH.C.M Page 6
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, ANANTAPUR
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-II: Java Basics: History of Java, Java buzzwords, data types, variables, scope
and lifetime of variables, arrays, operators, expressions, control statements, type conversion
and casting, simple java program, classes and objects – concept of classes, objects,
constructors, methods, Introducing access control, this keyword, garbage collection,
overloading methods and constructors, parameter passing, recursion, string handling.

History of Java

Java programming language was designed by “James Gosling” at Sun


Microsystems in 1991. This language was initially called “oak” but was renamed as
“Java” in 1995. It follows both the features of C and C++ languages.
Java programming language was very useful on Internet Programming. Since,
by using this language we can easily transfer the information from server to the nodes
through the network. It provides active programs when we are viewing the passive
data and self executing programs. Generally, in the case of network programs
security and portability are the main active areas of concern. The java applet
programming provides such facilities.

Java programs are classified into 2 types as:


1. Application programs
2. Applet programs

Application programs are run on the computer under the operating system of the
computer. This is similar to the other programming languages.
Applet programs are designed to be transmitted over the Internet and executed by a
java-compatible web browser.

Java Versions

Java 1.0
Java 1.1
Java 2 (Second Generation)
Java 1.2
J2SE (Java 2 Platform Standard Edition)
J2SE 1.3
J2SE 1.4
J2SE 5
J2SE 1.5
J2SE 6
J2SE 1.6

Java Features / Java Buzz Words

RAKESH.C.M Page 7
a) Platform Independent: Java is a platform independent language. Once we
create the program in one operating system, that program will be worked on any other
operating system that is transmitted to the operating system.

b) Portable: The most significant contribution of Java over other languages is its
portability. Java programs can be easily mover from one computer system to another
anywhere and any time. Changes and upgrades in operating system, processor, and
system resources will not force any changes in Java programming.

c) Object Oriented: Java is a true object oriented language. Since, without class we
can’t run the program but without main function, we can run the program. Almost
everything in java is an object. All program code and data reside within objects and
classes. The object model in Java is simple and easy.

d) Robust & Secure: Java is a Robust language. It provides many safe guards to
ensure reliable code. It is designed as garbage collected language relieving the
programmers, virtually all memory management problems. Java also incorporates the
concept of exception handling, which captures serious errors and eliminates any risk
on crashing the system.
Security becomes an important issue for a language that is used for
programming on internet. Java systems not only verify all memory access but also
ensure that no viruses are communicated with the applet.

e) Distributed: Java is designed as a distributed language for creating application on


network. It has the ability to share both data and program. Java application can open
remote object on internet as easily as they can do in local system.

f) Simple and Small: Java is a simple and small language. Many features of C and
C++ that are sources are unreliable code are not part of java. For example, Java
doesn’t use pointers, preprocessors, header files, goto statements and many others.

g) Multi Threaded: Java was designed to meet the real-world requirement of creating
interactive, networked programs. Java supports multithreaded programming, which
allows to handling multi task simultaneously. This means we need not wait for the
application to finish one task before beginning another one.

h) Dynamic: Java is a dynamic language. Java is capable on dynamically linking in


new class, libraries, methods and objects. Java support functions written in other
language such as C and C++ .These functions are known as native methods. Native
methods are linked dynamically at run time.

i) Compile and Interpreted: Usually a computer language is either compiled or


interpreted. Java combined both these approaches thus making. Java is a two-stage
system. First java compiler translates source code into byte code instruction and
therefore in the second stage java interpreter generates machine code that can be
directly executed by the machine that is running the java program.
Interpreter is called JVM (Java Virtual Machine). Java applications are
platform independent. JVM, JDK are platform dependent. Interpreter is different for
all operating system like DOS, UNIX etc..

RAKESH.C.M Page 8
j) High Performance: Java performance is impressing for an interpreted language due
to the use of intermediate code. Java architecture is also design to reduce overheads
during runtime. The incorporation of multithreading enhances, the overall executions,
speed of Java programs.

BASICS OF JAVA ENVIRONMENT

The entire procedure is divided into 5 phases.

Phase 1: Editor Disk

Phase 2: Compiler Disk

Class Loader Primary


Phase 3: Memory

Disk

Byte Code Primary


Phase 4: Verifier Memory

Phase 5: Interpreter Primary


Memory

Phase 1: Java programs are typed in a text editor (Note Pad, Edit Plus etc.,) and
makes corrections if necessary. The programmer specifies that the file in the editor

RAKESH.C.M Page 9
should be saved. The program is stored on a second storage device such as a disk.
Java program files are stored with .java extension.

Phase 2: The programmer gives the command javac filename.java to compile


the program. At this stage, the Java compiler translates the Java program into byte
code that is the language understood by the Java Interpreter. If the program compiles
correctly, a file called filename.class is produced. This is the file containing byte
codes that will interpret during the execution phase.

Phase 3: This phase is called loading. The program must be place in memory
before it can be executed. This is done by the class loader, which takes the .class file
containing in byte code and translates it into the memory. The .class file can be
loaded from a disk on your system or over a network.

Phase 4: Byte code verifier confirms that all byte codes are valid or don’t valid
the Java security instructions.

Phase 5: Java Interpreter reads byte code and translates them into a language
that the computer can understand and it can be executed the code.

Java Development Kit (JDK)

Java Development Kit is a collection of classes, Java Compiler and Java


Virtual Machine Interpreter. It also consist useful utilities for debugging,
documentation, compiling and run java programs.
The following are the some components of a java development kit.

 javac: The java compiler converts java source code into byte code
Syntax: javac filename.java

 java: The java interpreter ,executes java application byte does directly from
class file.
Syntax: java filename

 jdb: The java debugger that allows to step through the program one line at a
time, set break points and examine variables.
Syntax: jdb filename

 servlet runner : A simple web server to test servlets.

 appletviewer : A java interpreter that executes java applet classes hosted by


HTML.
Syntax: appletviewer filename.html

Java Virtual Machine (JVM)

RAKESH.C.M Page 10
Java provides both compiler and a software machine called JVM for each
computer machine. The java compiler translates the java source code (Java program)
into an intermediate code known as byte code, which executes on special type of
machine. The machine is called Java Virtual Machine and exists only inside the
computer memory. The byte code is machine independent code and can run in any
system.

Source Code Java Compiler Byte Code

The byte code is not a machine specific code. Java interpreter takes the byte code and
translates it into its own system machine language and runs the results.

Byte Code Java Interpreter Machine Code

Just In Time (JIT)

The Java Virtual Machine is an interpreter that translates and runs each byte
code instructions separately whenever it is needed by the computer program. In some
cases it is very slow.

As an alternative, Java also provides local compiler for each system that will
compile byte code file into executable code for faster running. Java calls these
compilers just in Time compilers.

Java Standard Library (JSL)

The Java API (Application Programming Interface) is a collection of classes


and methods grouped in the form of packages. JDK 1.2 has 58 packages, it is also
known as Java Standard Library.

The important packages in Java are


a) java.lang: It contains the main language support class. It contains wrappers,
strings and basic features of Java.
b) java.util: It provides classes that support date, time, basic event processing etc.
c) java.io: It provides reading and writing data in the form of streams.
d) java.awt: It provides classes for creating GUI programs.
e) java.applet: It includes set of classes to support for applet programming.
f) javax.swing: It provides classes for swing operation programming.

Difference between C++ and Java

RAKESH.C.M Page 11
1. Java does not include structure and union.
2. It is not possible to declare unsigned integer in Java.
3. Pointers don’t exist in Java.
4. Java does not have a preprocessor.
5. There are no header files and delete operators.
6. Java does not allow goto, sizeof and typedef.
7. Java does not support the multiple inheritance.

Java Tokens

Tokens are smallest individual units in a program. The compiler reads the
source program one character at a time grouping the source program into a sequence
of atomic units called tokens.
Reserved words, identifiers, constants, operators etc., are the examples of Java tokens.

Keywords

The keywords (or) reserved words have a special and predefined meaning by
the Java compiler. There are 48 reserved words currently used in Java. These words
cannot be used as names for a variable, constant, class or method. Reserved words
are:

abstract boolean break byte case catch


char class const continue default do
double else extends final finally float
for goto if implements import instanceof
int interface long native new package
private protected public return short static
strictfp super switch synchronized this throw
throws transient try void volatile while

true false null

Note: true, false and null are used to represent the values.

Data Types

Data types are used to specify the type of data that a variable can attain. There
are 2 types of data types. Those are
1. Primitive data types
2. Non-Primitive data types

1. Primitive data types: It is also called as standard, intrinsic or built-in data


types. There are eight primitive data types available in Java language. Those are
byte, short, int, long, char, float, double and Boolean. These can be classified into
four groups as:
Integers : byte, short, int, long
Floating point numbers : float, double

RAKESH.C.M Page 12
Characters : char
Boolean : Boolean

TYPE SIZE RANGE


BITS BYTES
Byte 8 1 -128 to 127
boolean 8 1 true / false
Char 16 2 0 to 65535
Short 16 2 -32768 to 32,767
Int 32 4 -2,147,483,648
To
2,147,483,647
float 32 4 3.4 e -0.38
To
3.4 e +0.38
long 64 8 -9,223,372,036,854,775,808
To
9,223,372,036,854,775,807
double 64 8 1.7 e -308
To
1.7 e +308

Note:

1. Java does not support any unsigned data types.


2. Variables of types char, byte, short, int, long, float and double all are given
the values ‘0’ by default.
3. Variables of type boolean holds ‘false’ by default.
4. All primitive data types in Java are portable (Platform Independent).

2. Non-Primitive data types: These are also known as derived or abstract or


reference data types. These are built with the combination of primitive data types.

Ex: string, class, array etc.,

Variables

The name given to the various elements to store the information is called an
identifier or variable. The rules for variables are as follows:

 Variable must be begin with a letter, a dollar ($) symbol or an underscore ( _ )


followed by sequence of letters.
 Variable names must be unique.
 There should be no space in between any two characters of identifiers.
 Keywords cannot be used as variable names.
 Java is case-sensitive language. So that lower and upper case characters are
distinct.

Declaring a Variable:

RAKESH.C.M Page 13
All variables must be declared before they can be used. The basic form of a
variable declaration is:

Syntax: datatype identifier;

Where,
datatype specifies type of the variable
identifier specifies the name of the variable.

Ex: int x;

More than one variable of the same type can be declared in a single statement by
using comma operator.

Syntax: datatype identifier1, identifier2, ……. , identifiern;


Ex: float x,y,z;

Initializing a Variable:

Variables can also be initialized with some value at the time of its declaration
as:
Syntax: datatype identifier = value;
Ex: int x = 100;

Scope & Life-Time of a Variable:

Scope refers to at what extent a variable is possible to use whereas life-time


refers to at what time the variable is alive without destroying.

Identifier that represent local variables in a method i.e., parameters and


variables declared in the method body have automatic duration. Automatic
declaration are created when program control reaches their declaration they exist
while the block in which they are declare is active and they are destroyed when the
block in which they are declared is exceeded. Automatic variables are also known as
local variables.

Java also has identifiers of static duration. Variables and references of static
duration exist from the point at which the class that defines them is loaded into
memory for execution until the program termination.

Identifier scope is where the identifier can be a reference in a program. The


scope of an identifier is class scope and block scope.

Methods and instance variables of a class have class scope. Class scope
begins at the beginning left brace of the class definition and ends at the closing right
brace of the class definition

RAKESH.C.M Page 14
Identifiers declared inside a block have block scope. Block scope begins at
the identifiers declaration and ends at the terminating right brace of the block. Local
variables of the method have block scope.

Comments in a Program

Three types of comments are available in Java. They are

1. Single line comments (//)


2. Multi line comments (/* …… */)
3. Documentation comments (/** ………. */)

1. Single line comments: For single line comment, we use double slash (//) to be
the comment. It ends at the end of the line.
Ex: // JAVA PROGRAM

2. Multi line comments: For more than one line of information, we use multi line
comments. Multi line comments are starts with /* and ends with */.
Ex: /* JAVA
PROGRAM */

3. Documentation comments: For the documentation purpose, we use


documentation comments. Documentation comments are starts with /** and ends
with */.
Ex: /** JAVA PROGRAM
VERSION 1.5
@ VITS.COM */

Input and Output Statements

java.lang package consists a class called “System” which contains console


I/O methods. If we want to take information from the keyboard and display
information on the screen, Java uses Stream Objects. The system provides three basic
streams. Those are
a) System.in b) System.out c) System.err

System.in refers to the standard input stream.


System.out refers to the standard output stream.
System.err refers to the standared error stream.

System.out class consists of two methods to print the strings and values on the screen.
They are: 1. print() 2. println()

RAKESH.C.M Page 15
1. print(): Syntax: System.out.print(list);
This statement prints the values of the variable name specified in the lists of
output unit.
Ex: System.out.print(“HELLO”);
System.out.print(“HAI”);

O/P: HELLOHAI

2. println(): Syntax: System.out.println(list);


This statement prints the values of the variable name in the list, the cursor is
advanced by one line and the next statement is printed in the next line.
Ex: System.out.println(“HELLO”);
System.out.println(“HAI”);

O/P: HELLO
HAI

Note: Java has a version of the ‘+’ operator for string concatenation that enables a
string and a value of another data type.

Ex: int sum = 10;


System.out.println(“Total =” +sum);

O/P: Total = 10

Command Line Arguments

Java has the facility of command line arguments. Java main method consists
of array of string objects. When we run the program, the array will fill with the
values of any arguments it was given in the command line of the operating system.

import statement

import statement is similar to the #include statement in C language. Using the


import statements, we can access to classes that are part of the other packages.

RAKESH.C.M Page 16
BUILDING JAVA PROGRAM

1. Creation of the Program

Java programs contain one or more class definitions.

Syntax: class FName


{
public static void main(String[] args)
{
----
----
}
}

 The keyword class is used to declare the new class is being defined.
 FName is a valid identifier that defines the name of the class.
 Entire class definition will be in between the opening curly brace ‘{‘ and the
closing curly brace ‘}’.
 ‘public’ keyword is an access specifier, which allows the user to control the
visibility of class members.
 ‘static’ keyword allows main( ) function to be called without having to
instantiate a particular instance of the class. Since, main( ) method is called by
the Java Interpreter before creation of any objects.
 ‘void’ keyword used to tell the compiler that main( ) does not return any
value.
 main( ) is a method called when a Java application begins.
 String args[] declares a parameter named args, which is an array of instance of
the class String. args receives any command line arguments present when the
program is executed.

Now, save the file name with .java extension. Since, every java program must end
with .java extension.

Ex: class Example


{
public static void main(String[] args)
{
System.out.println(“Hello”);
}
}

Save the file name as Example.java

RAKESH.C.M Page 17
2. Compiling the Program

To compile the program, use javac compiler by using the syntax as:

Syntax: javac FName.java


Ex: javac Example.java

Here, the Java compiler creates a file called Example.class that contains byte
code version of the program.

3. Running the Program

Now the class file is run by the Java Interpreter called java by using the
syntax as:

Syntax: java FName


Ex: java Example

After performing all these phases successfully, it display the output on output devices
as
O/P : Hello

Note:

Primitive data types are to be converted into object type by using the wrapper
classes. Integer class is used as wrapper class for primitive data type int. parseInt()
method converts string into an int.

// EXAMPLE PROGRAM FOR ADDITION OF GIVEN TWO NUMBERS

import java.lang.*;
class Add
{
public static void main(String[] args)
{
int x,y,z;
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("Total="+z);
}
}

RAKESH.C.M Page 18
javax.swing PACKAGE

javax.swing is a package that contains an important class called


JOptionPane. This class is used to display dialog boxes. It provides two important
predefined methods showInputDialog( ) and showMessageDialog( ) called static
methods. Such methods are always used their class name followed by a dot operator.

1. showInputDialog( ):

Syntax: JOptionPane.showInputDialog(argument);
The argument indicates to the user what to do in the text field.

Ex: JOptionPane.showInputDialog(“Enter x Value”);

When we perform this operation the input dialog box is appeared as

Then, the user type characters in the text filed and click on the ok button, it
returns the string to the program.

2. showMessageDialog( ):

Syntax 1: JOptionPane.showMessageDialog(null, argument1);

The first argument must be null keyword.


The second argument is the string required to display.

Ex: JOptionPane.showMessageDialog(null, “Total=”+sum);

The title bar of message dialog box contains the string “Message” to indicate
that the dialog is presenting a message to the user. The default icon is
INFORMATION_MESSAGE.

RAKESH.C.M Page 19
Syntax 2:

JOptionPane.showMessageDialog(null, argument2, argument3, argument4);

The first argument must be null keyword.


The second argument is the message to display.
The third argument is the string to display in the title bar of the dialog box.
The fourth argument is a value indicating the type of the message dialog. The
message dialogs are:

JOptionPane.PLAIN_MESSAGE

JOptionPane.ERROR_MESSAGE

JOptionPane.INFORMATION_MESSAGE

JOptionPane.WARNING_MESSAGE

JOptionPane.QUESTION_MESSAGE

Ex:

JOptionPane.showMessageDialog(null,"Total="+z,"ADDITION
RESULT",JOptionPane.WARNING_MESSAGE);

RAKESH.C.M Page 20
OPERATORS

Operator is a symbol that performs a specified operation between the data


items. Java provides the following different types of operators.

1. Assignment Operator: ‘=’ is an assignment operator used to assign some value


to a variable.
Syntax: variable = value;
Ex: x = 12;

2. Arithmetic Operators: Arithmetic operators are +, -, *, / and % used to perform


arithmetic operations such as addition, subtraction, multiplication, division and
modulo operations.

3. Arithmetic Assignment Operators:

Syntax: variable operator = expression;

which is equivalent to

variable = variable operator expression;

Operator Example Equivalent Expression

+= a+=4 a=a+4
-= a-=5 a=a–5
*= a*=3 a=a*3
/= a/=5 a=a/5
%= a%=2 a=a%2

4. Increment and Decrement Operators: ‘++’ and ‘- -‘ are increment and


decrement operators. The increment operator increased its operand by one where as
the decrement operator decreased its operand by one.

5. Relational Operators: Relational operators determine the relationship between


the two operands.

OPERATOR MEANING

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or Equal to

RAKESH.C.M Page 21
<= Less than or Equal to
6. Logical Operators: Logical operators are used to check for compound
conditions, which are formed by the combination of two or more relation expressions.
Java provides the following logical operators and these are follows truth tables and
produce Boolean values.

Operators : Logical AND &&


Logical OR ||
Logical NOT !

Logical AND && Truth Table:

EXP1 EXP2 EXP1 && EXP2


T T T
T F F
F T F
F F F

Logical OR | | Truth Table:

EXP1 EXP2 EXP1 && EXP2


T T T
T F T
F T T
F F F

Logical NOT ! Truth Table:

EXP1 ! EXP1
T F
F T

7. Conditional Operator: Java has a decision operator called conditional operator.


“? :” are conditional operators. These operators are also called as ternary operators.

Syntax: TestCondition ? Expression 1 : Expression 2

Here, If the TestCondition is TRUE, then Expression 1 is evaluated


Otherwise, Expression 2 is evaluated.

Ex: Max = (a>b) ? a : b;

RAKESH.C.M Page 22
8. Bit-Wise Operators: Bit-Wise operators are used to perform on bits of the
operands. Java language supports the following bit-wise operators.

OPERATOR MEANING

~ Bit-Wise Unary NOT


& Bit-Wise AND
| Bit-Wise OR
^ Bit-Wise Exclusive OR
>> Right Shift
<< Left Shift
|= Bit-Wise OR Assignment
^= Bit-Wise Exclusive OR Assignment
>> = Right Shift Assignment
<< = Left Shift Assignment

Bit-Wise Logical operators ( &, |, ^, and ~ ) follows the following truth tables.

OP1 OP2 OP1 | OP2 OP1 & OP2 OP1 ^ OP2 ~ OP1
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0

CONTROL STATEMENTS

Depending on the results of the computations the flow of control may


necessary to change the position from one place to another place; such statements are
called control statements. In Java control statements are classified into three
categories as:

1. Decision (Conditional) control statements


2. Loop control statements
3. Jump control statements

1. Decision (Conditional) control statements

In decision control statements, depending on the result of evaluation of an


expression, a statement or block of statements are executed. The condition involves
Boolean values either true or false. Java provides the following decision control
statements.

a) if statement
b) if-else statement
c) Nested if-else statement
d) switch statement

RAKESH.C.M Page 23
a) if statement: The if statement process the statements when the specified
condition is true.

Syntax: if(condition)
{
// Block Statements
}
Next Statements

Flowchart:

Condition T Block Statements

Next Statements

Here,
If the condition is true then Block Statements are executed. Otherwise, Block
Statements are not executed and the control directly reaches to Next Statements
available after the if block statements.
The statements are either simple or compound statements. If the statements
are simple statement pair of braces is not necessary. If the statements are compound
statements, they must be placed within pair of braces.

// EXAMPLE PROGRAM FOR IF STATEMENT

class Max
{
public static void main(String[] args)
{
int a=10,b=78;
if(a>b)
System.out.println("Max="+a);
if(b>a)
System.out.println("Max="+b);
}
}

RAKESH.C.M Page 24
b) if-else statement: The general format of if-else statement is:

Syntax: if(condition)
{
// True Block Statements
}
else
{
// False Block Statements
}

Flowchart:

Condition F
False Block Statements

True Block Statements

Next Statements

Here,
First the condition is evaluated.
If the condition is true, then True Block Statements are executed,
Otherwise, False Block Statements are executed.

// EXAMPLE PROGRAM FOR IF-ELSE STATEMENT


class Max1
{
public static void main(String[] args)
{
int a=90,b=78;
if(a>b)
System.out.println("Max="+a);
else
System.out.println("Max="+b);
}
}

RAKESH.C.M Page 25
c) Nested if-else statement: The if-else statement is placed within another if-else
statement; such methods are called nested if-else statements.

Syntax: if(condition 1)
{
// Block 1 Statements
}
else if(condition 2)
{
// Block 2 Statements
}
.
.
.
else
{
// Block n Statements
}
Next Statements

Example: Write a Java program that prints all real solutions to the
quadratic equation ax2+bx+c = 0.

import javax.swing.*;
import java.lang.*;

class Quadratic
{
public static void main(String args[])
{
double a,b,c,dis,r1,r2;
a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value"));
b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value"));
c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value"));
dis=b*b-4*a*c;
if(dis>0)
{
r1=(-b+Math.sqrt(dis))/(2*a);
r2=(-b-Math.sqrt(dis))/(2*a);
JOptionPane.showMessageDialog(null,"Roots are real. r1="+r1+" "+"r2="+r2);
}
else if(dis==0)
{
r1=r2=-b/(2*a);
JOptionPane.showMessageDialog(null,"Roots are equal.r1=r2="+r1);
}
else
JOptionPane.showMessageDialog(null,"Roots are imaginary");
}
}

RAKESH.C.M Page 26
d) switch statement: The switch statement allows section among the multiple section
of a code depending on the value of an expression. The objective is to check several
possible constant values for an expression.

Syntax: switch(Expression)
{
case value1 : Block 1 Statements
break;
case value2 : Block 2 Statements
break;
.
.
case valuen : Block n Statements
default : Default Block Statements
}

Here,
First the switch statement evaluates the expression and check whether the
evaluated value is coinciding with any case value or not. If any value is coinciding, it
executes that particular block of statements until the break statement is reached. After
executing the statements the control is transferred out of the statements that are
available after the switch statement.
If any value is not coinciding with the case value, then it executes Default
Block Statements. Default block is an optional block.

Note: Case values are either integer constants or character constants.

// EXAMPLE PROGRAM FOR SWITCH STATEMENT

class Color1
{
public static void main(String[] args)
{
char ch='G';
switch(ch)
{
case 'R':System.out.println("RED");
break;
case 'G':System.out.println("GREEN");
break;
case 'B':System.out.println("BLUE");
break;
default: System.out.println("INVALID SELECTION");
}
}
}

RAKESH.C.M Page 27
2. Loop Control Statements

A loop statement allows running a statement or block of statements


repeatedly for a certain number of times. Repetitive execution of statements is
called looping. Java provides three types of loop control statements. They are:
a) while statement
b) do-while statement
c) for statement

a) while statement: while loop executes the statements repeatedly as long as the
becomes true. When the condition becomes false, then the control immediately
passes to next statements available after the loop statements.

Syntax : while(condition)
{
// Block Statements
}

Flowchart:

Condition F Next Statements

T
Block Statements

The statements are either simple or compound statements. If the statements


are simple statement pair of braces is not necessary. If the statements are compound
statements, they must be placed within pair of braces.

// PROGRAM TO PRINT FIRST N FIBONACCI SEQUENCE NUMBERS

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

int a=1,b=1,c,i=3,n;
System.out.println(a+" ");
System.out.println(b+" ");
n=Integer.parseInt(args[0]);

RAKESH.C.M Page 28
while(i<=n)
{
c=a+b;
a=b;
b=c;
System.out.println(c+" ");
i++;
}
}
}

b) do-while statement: In do-while statement, first the control executes the


statements and then the control enters into condition section. The statements are
executed repeatedly as long as the condition becomes true. If the condition reaches to
false, then the control comes out from the loop and reaches to the next statements
available after the loop.

Syntax: do
{
// Block Statements
}
while(condition);

Next Statements

Flowchart:

Block Statements

T
Condition

Next Statements

Note: The main difference between while and do-while statements is do-while
statement executed the block statements at least once even the condition becomes
false.

RAKESH.C.M Page 29
// PROGRAM TO PRINT THE FIRST N FIBONACCI SEQUECE NUMBERS

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

int a=1,b=1,c,i=3,n;
System.out.println(a+" ");
System.out.println(b+" ");
n=Integer.parseInt(args[0]);
do
{
c=a+b;
a=b;
b=c;
System.out.println(c+" ");
i++;
}
while(i<=n);
}
}

c) for statement: The for statement also repeat a statement or compound


statements for a specified number of times. The general for of for statement is:

Syntax: for(Initialization ; Condition ; Increment/Decrement)


{
// Block Statements
}
Next Statements

Flowchart:

Initialization

Condition F

Block Statements Next Statements

RAKESH.C.M Page 30
Here,
First the control reaches to Initialization section. Initialization starts with
assigning value to the variable and executes only once at the start of the loop. Then
control enters into Condition section.
In Condition section, if the outcome of the Condition is true, then control
enters into Block Statements and is to be executed. After executing the statements
control reaches to Increment/Decrement section.
After incrementing or decrementing the variable in Increment/Decrement
section, again control reaches to Condition section.
This procedure is repeated as long as the condition becomes true. If the
Condition becomes false, then control comes out of the loop and the control reaches
to Next statements available after the loop.

// EXAMPLE PROGRAM

class Fact
{
public static void main(String[] args)
{
int i,n,f=1;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
f=f*i;
System.out.println("Factorial Value:"+f);
}
}

Note:

1. Multiple initializations are possible by comma operator.


Ex: for( i=1, f=1 ; i<=n ; i++)
2. At the place of condition section, it is also possible to use relational
expressions.

3. Jump Control Statements

Java provides the following jump control statements.


a) break statement
b) continue statement
c) return statement
d) exit statement

a) break statement: break statement placed in while, do-while, for and switch
statement causes immediate exit from that structure. It can be used in two ways as
unlabeled break and labeled break statements.

RAKESH.C.M Page 31
Unlabeled break:

Syntax: break;

// EXAMPLE PROGRAM FOR UNLABELED BREAK STATEMENT

class Loop1
{
public static void main(String[] args)
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
System.out.print(" "+i);
}
}
}

Labeled break: To break out of nested structures, we can use the labeled break
statements. This statement when executed in a while, do-while and for statements
causes immediate exit from that structure and any number of enclosing repetition
structures. Program execution resumes with the first statement after the enclosing
labeled compound statement.

// EXAMPLE PROGRAM FOR LABELED BREAK STATEMENT

class Loop2
{
public static void main(String[] args)
{
int i,j;
stop:
{
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
break stop;
System.out.print(" "+i);
}
System.out.println();
}
}
}
}

RAKESH.C.M Page 32
b) continue statement: continue statement placed in a while, do-while or for
statements causes to skip the remaining statements available after the continue
statement and the control reaches to next iteration of the loop. It can also be used in
two ways as unlabeled continue and labeled continue statements.

Unlabeled continue:

Syntax: continue;

// EXAMPLE PROGRAM FOR UNLABELED CONTINUE STATEMENT

class Loop3
{
public static void main(String[] args)
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
continue;
System.out.print(" "+i);
}
System.out.println();
}
}
}

Labeled continue: The labeled continue statement placed in a repetition structure


that skips the remaining statements in that structure body and any number of
enclosing repetitions on the structure and proceeds with the next iteration of an
enclosed labeled repetition.

// EXAMPLE PROGRAM FOR LABELED CONTINUE STATEMENT

class Loop
{
public static void main(String[] args)
{
int i,j;
stop:
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
if(i==3)
continue stop;

RAKESH.C.M Page 33
System.out.print(" "+i);
}
System.out.println();
}
}
}

c) return statement: The return statement is used to explicitly return from a


method. This causes program control to transfer back to the caller of the method.
The return statement immediately terminates the method in which it executes.
Syntax: return;

d) exit statement: The method exit( ) is defined in System class. The


purpose of exit is to terminate the program with a specific exit code.
Syntax: System.exit(Code);

The program finish normally by placing Code as ‘0’; other value means error.

Syntax: System.exit(0);

Example: Write a Java program that prompts the user for an integer and
then print out all prime numbers up to that integer.

import javax.swing.*;
class Prime
{
public static void main(String args[])
{
int n,temp;
n=Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
System.out.println("The prime numbers from 1 to" +n+" are");
for(int i=2;i<=n;i++)
{
temp=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
temp=1;
break;
}
}
if(temp==0)
System.out.println(i);
}
}
}

RAKESH.C.M Page 34
ARRAYS

An array is a group of homogeneous data items that are stored in


successive memory locations shared with a common name. A particular value
is indicated by writing a number called ‘index number’ or ‘subscript’ in square
brackets after the array name. Arrays are classified into different types as:
1. One-dimensional array
2. Two-dimensional array
3. Multi-dimensional array

1. One-dimensional array: A one-dimensional array is a list of


homogeneous items given in one variable name using only one subscript.
Individual value of an array is called as an element. Like an ordinary
variable, arrays must be declared and created in the computer memory before
they are used.
Creation of an array contains two sections. They are:
Declaration of the array
Creating memory locations

Syntax: datatype ArrayName[]; // Declaration


ArrayName = new datatype[size]; // Memory Allocation

Or
Syntax: datatype ArrayName[] = new datatype[size];

Where,
datatype defines type of the variables stored in the array
ArrayName defines name of the array
new operator used to allocate dynamic memory in computer for the array
size defines the number of memory locations of the array.

Ex: int number[] = new int[10];

It can also be possible to initialize array automatically, when they are declared.
For this use the syntax as:

Syntax: datatype ArrayName[ ] = {list of values};

Where,
List of values are separated by comma operator and surrounded by curly
braces.
Ex: int x[] = { 11,34,78,90};

In Java, all arrays are storing the allocated size in a variable named length. We
can access the length of the array using the syntax as:

Syntax: ArrayName.length;

RAKESH.C.M Page 35
// EXAPLE PROGRAM TO SORT LIST OF NUMBERS IN ASCENDING ORDER
import javax.swing.*;
class Arr1
{
public static void main(String[] args)
{
int n,temp,i,j;
n=Integer.parseInt(JOptionPane.showInputDialog("Enter how many numbers:"));
int x[]=new int[n];
for(i=0;i<n;i++)
x[i]=Integer.parseInt(JOptionPane.showInputDialog("Enter "+"x["+i+"]"));
for(i=0;i<=n-2;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(x[i]>x[j])
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}
for(i=0;i<n;i++)
System.out.print(" "+x[i]);
}
}

2. Two-dimensional array: A two-dimensional array is a collection of


homogeneous data elements that share a common name using two subscripts. It stores
table of data. This representation is very useful for matrix representations as first
subscript represents the number of rows and second subscript represents the number
of columns.

Syntax: datatype ArrayName[][]; // Declaration


ArrayName = new datatype[size1][size2]; // Memory Allocation
Or
datatype ArrayName[][] = new datatype[size1][size2];
Where,
datatype defines type of the variables stored in the array
ArrayName defines name of the array
new operator used to allocate dynamic memory in computer for the array
size1 defines the number of rows of memory allocation of the array
size2 defines the number of columns of memory allocation of the array.

Ex: int number[][] = new int[10][8];

RAKESH.C.M Page 36
It can also be possible to initialize array automatically, when they are declared.
For this use the syntax as:

Syntax: datatype ArrayName[ ][ ] = {list of values};

Or

datatype ArrayName[ ][ ] = { {Row1 Values} ,


{Row2 Values},
.
.
}

Example: Write a Java program to multiply two given matrices.

import javax.swing.*;
class Matmul
{
public static void main(String args[])
{
int[][] a=new int[10][10];
int b[][]=new int[10][10];
int c[][]=new int[10][10];
int m,n,p,q,i,j,k;
m=Integer.parseInt(JOptionPane.showInputDialog("Enter Rows of Matrix 1:"));
n=Integer.parseInt(JOptionPane.showInputDialog("Enter Columns of Matrix 1:"));
p=Integer.parseInt(JOptionPane.showInputDialog("Enter Rows of Matrix 2:"));
q=Integer.parseInt(JOptionPane.showInputDialog("Enter Columns of Matrix 2:"));
if(n==p)
{

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter a["+i+"]["+j+"]:"));
}
}
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter b["+i+"]["+j+"]:"));
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;

RAKESH.C.M Page 37
for(k=0;k<p;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
System.out.println("The resultant matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
else
System.out.println("Matrix multiplication is not possible");
}
}

3. Multi-dimensional array: Multi-dimensional array is a list of values shared


by a common name using multiple subscripts. If the array contains three subscripts
then the array is called as three-dimensional array and so on.

Syntax:
datatype ArrayName[][]…[] = new datatype[size1][size2]……[sizen];

Ex: int x[][][] = new int[2][2][3];

// EXAPLE PROGRAM FOR MULTI-DIMESIONAL ARRAY

class Mt
{
public static void main(String[] args)
{
int i,j,k;
int x[][][]={ { {11,22},{33,44}},{{1,7},{3,4}}};
for(i=0;i<2;i++)
{
System.out.println();
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
System.out.print(" "+x[i][j][k]);
System.out.println();
}
}
}
}

RAKESH.C.M Page 38
TYPE CONVERSION AND CASTING

Java permits mixing of constants and variables of different types, but during
execution it follows type conversions. The process of converting data item from one
data type to another data type is called type casting.
In Java, type casting can be done in two ways. They are:
1. Implicit type casting
2. Explicit type casting

1. Implicit type casting: In an expression, if the operands are of different types,


the lower type is automatically converted to the higher type before the operation
proceeds by the Java Interpreter. The result is of the higher types. Such type of
casting is called implicit type casting. In implicit type casting there is no loss of data.
The following are some of implicit type castings with no loss of data.

FROM TO

byte short, char, int, long, float, double


short char, int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

2. Explicit type casting: If we want to force to convert the operands of an


expression from one type to another type depending on user choice, such type of
casting is called explicit type casting. In explicit type casting there is a chance of data
loss when we convert the operands from higher data type to lower data type. The
general from of explicit type casting is:

Syntax: (datatype) Expression;

Ex: x = (int) 7.5;

Note: The final result of an expression is converted to the type of the variable before
assigning to the left hand side variable. In such cases the following observations are
made.

 float to int causes truncation of the fractional part.


 double to float causes rounding of digits.
 long to int causes dropping of the excess of higher order bits.

RAKESH.C.M Page 39
Class: A class is a non-primitive data type that contains member variables (data) and
member functions (methods) that operates on the variables. A class is declared by the
use of the class keyword. The general form of class definition is as follows.
Syntax: class class-name
{
datatype instance-variable1;
datatype instance-variable2;
-
-
datatype instance-variablen;
datatype methodname1(parameter-list)
{
// method body
}
-
-
datatype methodnamem(parameter-list)
{
// method body
}
}

The data, or variables defined with in a class are called instance variables.
The code is present with in methods. Collection of methods and variables defined
with in a class are called members of the class.

Example: class box


{
double width, height, depth;
double volume( )
{
return width*height*depth;
}
}

Creating Objects: An object in Java is a block of memory that contains space to


store all the instance variables. Creating an object of a class is a two-step process.

1. Declare a variable of the class type. At this stage, the variable refers to an
object only.
2. Assigning an actual, physical copy of the object and assign it to that
variable by means of ‘new’ operator. The new operator dynamically
allocates memory for an object and returns a reference to that object.

Example: Rectangle rect1; // reference


rect1 = new Rectangle(); // instantiation
(or)
Rectangle rect1 = new Rectangle();

RAKESH.C.M Page 40
The first statement declares a variable to hold the object reference.

null

rect1

The second statement assigns the object reference and allocates memory

Rectangle
rect1 object

Note: Each object contains its own instance variables of its class. This means that
any changes to the variables of one object have no effect on the variables of another.
But the function name is name for both objects.
It is also possible to create two or more references to the same object.

Example: Rectangle r1 = new Rectangle( );


Rectangle r2 = r1;

r1
Rectangle
object

r2

Methods: Methods allows the programmer to modularize a program. All variables


declared in method definition are local variables and method parameters are also local
variables. All methods must define inside a class definition. The general form of a
method is as
Syntax: type method-name (parameter-list)
{
// body of the method
}
where,
 type specifies the type of data returned by the method. If the method does not
return any value, its return type must be void
 The method-name is a valid identifier
 parameter-list is a sequence of type and identifier pairs separated by commas.
The variable receives the value of the arguments passed to the method when it
is called. If the method has no parameters, then the parameter list will be
empty
 body of the method describes the operations to be performed on the data

RAKESH.C.M Page 41
Example: int sum(int a, int b)
{
int c;
c=a+b;
return c;
}

Accessing class members: All variables must be assigned values before they
are used in our program. All class members are accessed by means of “dot” operator.
The general format of accessing instance variable of the class by dot operator is as:

Syntax: objectname.variablename;

Where,
objectname is name of the object, variablename is the name of the instance
variable.

Example: rect1.length=15;
rect1.width=10;

15 rect1.length
rect1
10 rect1.width

The general format of accessing instance methods of the class by dot operator is as:

Syntax: objectname.methodname(parameter-list);

Where,
objectname is name of the object, methodname is the name of the instance
method that calls with the object and paramerter-list is a list of actual values separated
by commas.

Example: void getdata(int x, int y)


{
length=x;
width=y;
}

rect1.getdata(10,20);

RAKESH.C.M Page 42
// Write a program to calculate the area of a rectangle.

class Rectangle
{
int length1,width1;
void getdata(int x,int y)
{
length1=x;
width1=y;
}
int calarea()
{
int area=length1*width1;
return area;
}
}

class prg
{
public static void main(String[] args)
{
int a,b;
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();

rect1.length1=15;
rect1.width1=4;
a=rect1.length1*rect1.width1;
System.out.println("Area of Rectangle1="+a);

rect2.getdata(2,3);
b=rect2.calarea();
System.out.println("Area of Rectangle2="+b);
}
}

Method Overloading: In Java it is possible to define two or more methods within


the same class that share the same name as long as these methods have different sets
of parameters (Based on the number of parameters, the types of the parameters and
the order of the parameters). Then the methods are said to be overloaded, and the
process is referred as Method Overloading.
When the overload method is called the Java compiler selects the proper
method by examine the number, type and order of the arguments in the call. Method
Overloading is commonly used to create several methods with same name that
perform fast accessing.

Note: Two methods differ in only by return type will result in a syntax error.

RAKESH.C.M Page 43
// EXAMPLE PROGRAM FOR METHOD OVERLOADING

class overload
{
int square(int x)
{
return x*x;
}
double square(double x)
{
return x*x;
}
}
class check
{
public static void main(String[] args)
{
overload r1=new overload();
int k=r1.square(3);
double p=r1.square(4.0);
System.out.println("k value="+k);
System.out.println("p value="+p);
}
}

// EXAMPLE PROGRAM FOR METHOD OVERLOADING WITH SAME RETURN TYPE

class overload1
{
int sum(int x)
{
return x+x;
}
int sum(int x,int y,int z)
{
return x+y+z;
}
}
class check1
{
public static void main(String[] args)
{
overload1 r1=new overload1();
int k=r1.sum(3,5,7);
System.out.println("k value="+k);
}
}

RAKESH.C.M Page 44
Constructors: A constructor is a special method of class, which is invoked
automatically, whenever an object of a class is created. It has the same name as its
class and resides similar to a method. A constructor has the following characteristics.
 It doesn’t have any return type not even void
 The constructor can be declared as public
 It can be overloaded
 It is normally used to initialize the member of the object

Different types of Constructors:

1) Default Constructor: A constructor that accepts no parameters is called the


default constructor. If no constructors are defined for a class, the Java system
automatically generates the default constructor.

// EXAMPLE PROGRAM FOR DEFAULT CONSTRUCTOR

class Time1
{
int hour,min,sec;
public Time1()
{
hour=10;
min=45;
sec=23;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
}
}
class const1
{
public static void main(String[] args)
{
Time1 t=new Time1();
t.printdata();
}
}

O/P: 10hours:45minutes:23seconds

2) Parameterized Constructor: A constructor that takes arguments as parameters is


called parameterized constructor. If any constructors are defined by a class with the
parameters, Java will not create a default constructor for the class.

// EXAMPLE PROGRAM FOR PARAMETERIZED CONSTRUCTOR

class Time1
{
int hour,min,sec;

RAKESH.C.M Page 45
public Time1(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");
}
}
class const2
{
public static void main(String[] args)
{
Time1 t=new Time1(10,9,4);
t.printdata();
}
}

O/P: 10hours:9minutes:4seconds

Constructor Overloading: An interesting feature of the constructor is that a class


can have multiple constructors. This is called Constructor Overloading. All the
constructors have the same name as corresponding to the class name that they are
differ only interms of their signature as number of arguments or data types or order.

// EXAMPLE PROGRAM FOR CONSTRUCTOR OVERLOADING

class Time1
{
int hour,min,sec;
public Time1()
{
hour=0;
min=0;
sec=0;
}
public Time1(int h)
{
hour=h;
min=0;
sec=0;
}
public Time1(int h, int m)
{
hour=h;
min=m;
sec=0;
}

RAKESH.C.M Page 46
public Time1(int h,int m,int s)
{
hour=h;
min=m;
sec=s;
}
void printdata()
{
System.out.println(hour+"hours:"+min+"minute:"+sec+"sec");
}
}
class const3
{
public static void main(String[] args)
{
Time1 t=new Time1();
t.printdata();
Time1 t1=new Time1(9);
t1.printdata();
Time1 t2=new Time1(7,8);
t2.printdata();
Time1 t3=new Time1(10,9,4);
t3.printdata();
}
}

Static Class Members: Generally each class contains instance variables and
instance methods. Every time the class is instantiated, a new copy of each of them is
created. They are accessed using the objects with the dot operator.
If we define a member that is common to all the objects and accessed without
using a particular object i.e., the member belong to the class as a whole rather than the
objects created from the class. Such facility can be possible by using “static”
keyword.
The members declared with the static keyword are called static members.

Example: static int x;


static int show(int x,int y);

The important points about static class members are


 Static members can be accessible without the help of objects. It can be
accessible by using the syntax: classname.members;
 A static method can access only static members (data + method)
 A static block will be executed first (before main). Static variables are
initialized first
 A static member data store the same memory for all objects
 Static method cannot be referred to ‘this’ or ‘super’ in anyway.

RAKESH.C.M Page 47
Example1:

class static1
{
static int c=0;
void increment()
{
c++;
}
void display()
{
System.out.println("Value="+c);
}
}
class Mstatic
{
public static void main(String[] args)
{
static1 s=new static1();
static1 s1=new static1();
static1 s2=new static1();
s.increment();
s1.increment();
s2.increment();
s.display();
s1.display();
s2.display();
}
}

O/P: value=3
value=3
value=3

without static keyword 0 0 0

s1 s2 s3

with static keyword 0

s1 s2 s3

RAKESH.C.M Page 48
Example2:

class static1
{
static int a=10;
static int b=34;
static void call()
{
System.out.println("Value1="+a);
}
}
class Mstatic1
{
public static void main(String[] args)
{
static1.call();
System.out.println("Value2="+static1.b);
}
}

O/P: Value1=10
Value2=34

Example3:

class static2
{
static int a=10,b;
static void method(int x)
{
System.out.println("x="+x);
System.out.println("a="+a);
System.out.println("b="+b);
}
static
{
System.out.println("static block");
b=a*4;
}
}
class Mstatic2
{
public static void main(String[] args)
{
static2.method(35);
}
}

O/P: static block x=35 a=10 b=40

RAKESH.C.M Page 49
Access Modifiers/Control:

Java provides four types of Access Modifiers. They are public, protected, default and
private.

Access Location public protected friendly or private


default
Same class Y Y Y Y
Sub class in same package Y Y Y N
Other classes in same Y Y Y Y
package
Sub classes in other Y Y N N
packages
Non-sub classes in other Y N N N
packages

For good programming technique place member data as private and member functions
as public.

// EXAMPLE PROGRAM TO DEMONSTRATE ACCESS CONTROL

class modi
{
private int k=6;
void display()
{
System.out.println("K VALUE="+k);
}
}
class ex
{
public static void main(String[] args)
{
modi obj=new modi();
obj.display();
//System.out.println("k in main="+obj.k);
//this statement provides error since private variable
//can not be possible to access by other class
}
}

this keyword: Java define “this” keyword, that can be used inside any method to
refer the current object. “this” is always a reference to the object on which method
was invoked. “this” reference is implicitly used to refer to both the instance variables
and methods of current object.

RAKESH.C.M Page 50
// EXAMPLE PROGRAM FOR THIS KEYWORD
class Box
{
int len,dep,hei;
Box(int len,int dep, int hei)
{
this.len=len;
this.dep=dep;
this.hei=hei;
}
int volume()
{
return len*dep*hei;
}
}
class this1
{
public static void main(String[] args)
{
Box obj=new Box(1,2,3);
int x=obj.volume();
System.out.println("volume="+x);
}
}
O/P: volume=6

“this” reference is also used explicitly refer to the instance variables.

// EXAMPLE PROGRAM

class Box
{
int len=10;
void method()
{
int len=40;
System.out.println("local value="+len);
System.out.println("Instance value="+this.len);
}
}
class this2
{
public static void main(String[] args)
{
Box obj=new Box();
obj.method();
}
}

O/P: local value=40


Instance value=10

RAKESH.C.M Page 51
Argument Passing: Arguments passed to a sub-routine (method) is falls into two
categories.
1. Call by value
2. Call by reference

1. Call by Value: Call by value copies the value of an argument into the formal
parameter of the sub-routine. Therefore, if changes made to the parameter of the sub-
routine have no effect on the argument used to call it.

// EXAMPLE PROGRAM FOR CALL BY VALUE


class Test
{
void change(int i, int j)
{
i*=2;
j/=2;
}
}
class cbv
{
public static void main(String[] args)
{
Test obj=new Test();
int a=4,b=7;
System.out.println("Before calling a="+a+" b="+b);
obj.change(a,b);
System.out.println("After calling a="+a+" b="+b);
}
}

O/P: Before calling a=4 b=7


After calling a=4 b=7

2. Call by Reference: In this method, a reference to an argument is passed to the


parameter. Inside the parameter, this reference is used to access the actual argument
specified in the call. Therefore, any changes made to the parameter will effect the
argument used to call it. This one is also referred as passing an object as parameter to
a method.

// EXAMPLE PROGRAM FOR CALL BY REFERENCE


class Test
{
int a,b;
Test(int i,int j)
{
a=i;
b=j;
}

RAKESH.C.M Page 52
void change(Test ox)
{
ox.a*=2;
ox.b/=2;
}
}
class cbr
{
public static void main(String[] args)
{
Test obj=new Test(4,5);
System.out.println("Before calling a="+obj.a+" b="+obj.b);
obj.meth(obj);
System.out.println("After calling a="+obj.a+" b="+obj.b);
}
}

O/P: Before calling a=4 b=5


After calling a=8 b=2

Recursion: A recursive method is a method that calls itself either directly or


indirectly through another method. A method call itself is termed as Recursion.
Recursion can be classified into two types as:
1. Direct recursion
2. Indirect recursion

1. Direct recursion: A method calls itself is called direct recursion.

Ex: void sum()


{
--
sum();
--
}

2. Indirect recursion: A method calls another method, which initiates to call the
initial method is called indirect recursion.

Ex: void sum()


{
---
call();
---
}
void call()
{
--
sum();
}

RAKESH.C.M Page 53
// Write a program to print the factorial of a given number using recursion

class a
{
double fact(double x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
}
class recur
{
public static void main(String[] args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
double t=obj.fact(p);
System.out.println("facatorial="+t);
}
}

// Write a program to print the first n Fibonacci sequence numbers using recursion

class a
{
int fib(int x)
{
if(x==0||x==1)
return x;
else
return (fib(x-1)+fib(x-2));
}
}
class Fibonacci
{
public static void main(String[] args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
for(int i=1;i<=p;i++)
{
int t=obj.fib(i);
System.out.println(" "+t);
}
}
}

RAKESH.C.M Page 54
// Write a program to print the sum of ‘n’ numbers using the recursive formula
sum (n) = 0 ; if n = 0
n + sum(n-1) ; if n  1

Example: Write a Java program that used both recursive and non-recursive
functions to print the nth value in the Fibonacci sequence.

import javax.swing.*;

class Fibo
{
int fibrec(int n)
{
int result;
if(n==1||n==2)
return 1;
else
return fibrec(n-1)+fibrec(n-2);
}
void fibnon(int n)
{
int a=1,b=1,i=3,c;
System.out.print(a+" "+b+" ");
while(i<=n)
{
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
i++;
}
System.out.println();
}
}
class Fibonacci
{
public static void main(String args[])
{
int n,p;
String sn;
Fibo obj=new Fibo();
sn=JOptionPane.showInputDialog("Enter how many numbers:");
n=Integer.parseInt(sn);

System.out.println("Fibonacci sequence with recursion:");


for(int i=1;i<=n;i++)
{
p=obj.fibrec(i);
System.out.print(" "+p);
}

RAKESH.C.M Page 55
System.out.println("\nFibonacci series without recursion\n");
obj.fibnon(n);
}
}

Random Number Generation: The elements of change can be introduced through


the random method.
Consider the following statement

double value = Math.random( );

The random( ) method generates a double value from 0.0 to 1.0(not included). The
range of values produced directly by random is often different than what is needed in
a specific application.

Example: A program that stimulates rolling six-sided die would required random
integers in the range (1,6)

The general formula for this type of problems using random method is:

a+(int)(Math.random( )*b)

Where,
‘a’ is a shifting value that is equal to the fist number in the range of integers
‘b’ is the scaling factor that is equal to the width of range of the integer.

// EXAMPLE PROGRAM FOR RANDOM NUMBER GENERATION

class random
{
public static void main(String[] args)
{
for(int i=1;i<=20;i++)
{
int s=1+(int)(Math.random()*6);
System.out.print(s);
if(i%5==0)
System.out.print("\n");
}
}
}

RAKESH.C.M Page 56
Recursion Vs Iteration:

Recursion Iteration

1. Recursion uses a selection structure like 1. Iteration uses a repetitive


structure
if, if-else etc., like while, do-while etc.,
2. Recursion terminates when base case is 2. Iteration terminates when the
loop
recognized Continuation condition fails
3. It can occur infinitely 3. It can occur infinitely
4. Extra memory is required 4. Extra memory is not required

Nested Class and Inner Classes It is possible to define a class within another
class such classes are known as nested classes. A nested class has access to all of the
variables and methods of its outer class. But the outer class doesn’t access the
variables and methods of nested class. Since the scope of a nested class is bounded
by the scope of its enclosing class.

There are two types of nested classes: static and non-static

A static nested class is a class started with ‘static’ modifier. Due to the static
it must access the members of its enclosing class through an object. Direct access
cannot be possible.
A non-static class is a class as ordinary representation of class. The most
important type of the non-static class is “Inner class”. The inner class has access to
all of the variables and methods of its outer class. Thus, inner class scope is fully
within the scope of its outer class.

Example:

class outer
{
int out_x=34;
void test()
{
inner in=new inner();
in.display();
}
class inner
{
void display()
{
System.out.println("value="+out_x);
}
}
}

RAKESH.C.M Page 57
class test
{
public static void main(String[] args)
{
outer y=new outer();
y.test();
}
}

STRINGS

A string is a collection of characters. Java implements strings as object type of String.


Java provides three types of string handling classes.

1. String Class
2. StringBuffer Class
3. StringTokenizer Class
4.
String and StringBuffer classes are defined in java.lang pacakage.
StringTokenizer are defined in java.util package.

1. String Class:

A string is an object of class String. String literals or constants written as a sequence


of characters in double quotes. A string may be assigned in declaration to string
reference as
String color = ”blue”;

It initializes string reference color to refer the anonymous string object blue.

Note: 1. Once we create a string object, we cannot change the contents of string
instance.
2. A variable declared as a string reference can be changed at any time.

String Constructors: String class provides several types of constructors. They are
a) String( ): It creates an empty string with no characters in it.
b) String(String): It takes one String as a parameter.
c) String(StringBuffer): Allocates a new string that contains the sequence of
characters currently contained in the string buffer argument.
d) String(byte[] bytes): Construct a new String by converting the specified array
of bytes using the platform's default character encoding.
e) String(bytes byte[], int startindex, int numberofcharacters): Allocates new
string positioned with the startindex by counting the number of charactes.
f) String(char chars[]): Creates a string initialized by an array of characters.
g) String(char chars[], int startindex, int numberofcharacters): Creates a string
initialized by an array of characters with the startindex by counting the number
of charactes.

RAKESH.C.M Page 58
Methods:
1. int length( ): It returns the number of characters in a given string.
Example: class len
{
public static void main(String[] args)
{
String s1=new String("hello");
System.out.println(s1.length());
}
}

2. char charAt(int where): It returns the character at the specified location. “where”
must be a nonnegative specified location within the string. The first element of a
string is considered to be at position “zero”.

Example:
class pos
{
public static void main(String[] args)
{
String s1=new String("hello java");
char c=s1.charAt(7);
System.out.println("character="+c);
}
}

3. void getChars(int sourcestart, int sourceend, char target[], int targetstart): It


extracts more than one character at a time and copy the characters of the string into a
character array.
The first argument is the starting index from which characters are copied in
the string. The second argument is the index that is one part of the last character to be
copied from the string. The third argument is the array into which the characters are
copied. The last argument is the starting index where the copied characters are placed
in the character array.
Example:
class get
{
public static void main(String[] args)
{
String s1="java programming language";
char c[]=new char[10];
s1.getChars(3,8,c,0);
for(int i=0;i<(8-3);i++)
System.out.print(c[i]);
}
}

O/P: a prog

RAKESH.C.M Page 59
4. boolean equals( ): It compares the two strings and returns true if the strings contain
the same characters in the same order, and false otherwise. The comparison is case-
sensitive.
Syntax: boolean equals(Object string);

Example:

class equal
{
public static void main(String[] args)
{
String s1=new String("india");
String s2=s1;
if(s1.equals(s2))
System.out.println("Strings are Equal");
else
System.out.println("Strings are not Equal");
}
}

5. boolean equalsIgnoreCase( ): It compares the two strings and returns true if the
strings contain the same characters in the same order, and false otherwise by ignoring
the case characters.
Syntax: boolean equalsIgnoreCase(String str);

Example:

class equall
{
public static void main(String[] args)
{
String s1=new String("india");
String s2=new String(“InDia”);
if(s1.equalsIgnoreCase(s2))
System.out.println("Strings are Equal");
else
System.out.println("Strings are not Equal");
}
}

6. int compareTo(String str ): It returns ‘0’ if the two strings are equal. ‘Negative
number’ if the invoking string is less than str and ‘postivite number’ if the invoking
string is greater than str that is passed as an argument. The comparision is case-
sensitive.

Example:

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

RAKESH.C.M Page 60
{
String s1=new String("hello");
String s2=new String("india");
if((s1.compareTo(s2))>0)
System.out.println("S1 is greater than s2");
else if((s1.compareTo(s2))<0)
System.out.println("S2 is greater than s1");
else
System.out.println("Two stings are equal");
}
}

O/P: S2 is greater than s1

If we want to ignore case differences when comparing two strings, we use the
syntax of the form: int compareToIgnoreCase(String str)
This method was added by Java 2.

7. regionMatches( ): It compares a specific region inside a string with another


specific region in another string. It follows two methods.

1. boolean regionMatches(int startIndex, String str2, int str2StartIndex, int


numchars)
2. boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int
str2StartIndex, int numchars)

The first argument is the starting index of the string that invokes the method. The
second argument is a comparison string. The third argument is starting index in the
comparison string. The last argument is the number of characters to compare between
the two strings. IgnoreCase is true the method ignores the case of the objects being
compared.

Example 1:

class rmatch1
{
public static void main(String[] args)
{
String s1=new String("happy birthday");
String s2=new String("Happy birthday");
if(s1.regionMatches(0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not Match");
}
}

RAKESH.C.M Page 61
Example 2:

class rmatch1
{
public static void main(String[] args)
{
String s1=new String("happy birthday");
String s2=new String("Happy birthday");
if(s1.regionMatches(true,0,s2,0,5))
System.out.println("Match");
else
System.out.println("Not Match");
}
}

8. int indexOf(int ch):


int indexOf(String str):
int indexOf(char ch): It search for the first occurrence of a character. If
the character is found the index of that characters in the string is returned. Otherwise,
it returns ‘-1’.

Example:
class index
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.indexOf('v')); //O/P: 2
System.out.println(letter.indexOf("programming")); //O/P: 5
System.out.println(letter.indexOf('A')); //O/P: -1
}
}

9. int indexOf(int ch, int startIndex):


int indexOf(String ch, int startIndex):
int indexOf(char ch, int startIndex): It searches the occurrence of character
from the startIndex argument.

Example:

class indexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.indexOf('m',2)); //O/P: 11
}
}

RAKESH.C.M Page 62
10. int lastIndexOf(int ch):
int lastIndexOf(char ch):
int lastIndexOf(String ch): It searches the last occurrence of the character. The
search is performed from the end of the string towards the beginning of the string. If
the character is found the index of that character in the string is return. Otherwise, it
returns ‘-1’.

Example:

class lindexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.lastIndexOf('n')); //O/P: 19
System.out.println(letter.lastIndexOf("language")); //O/P: 17
}
}

11. int lastIndexOf(int ch, int startIndex):


int lastIndexOf(String ch, int startIndex):
int lastIndexOf(char ch, int startIndex): It searches the last occurrence of
the character starting with the startIndex to search the string from ending to the
beginning.

Example:

class lindexof
{
public static void main(String[] args)
{
String letter=new String("Java programming language");
System.out.println(letter.lastIndexOf('n',11)); //O/P: -1
}
}

12. String substring(int startIndex): It returns a copy of the sub string that begins
that startIndex and return to the end of the invoking string.

Example:

class sub
{
public static void main(String[] args)
{
String s=new String("Java programming language");
System.out.println(s.substring(8));
}
}
O/P: gramming language

RAKESH.C.M Page 63
13. String substring(int startIndex, int endIndex): It returns all the characters from
the beginning index upto but not including the ending index.

Example:

class s13
{
public static void main(String[] args)
{
String s=new String("program");
System.out.println(s.substring(2,5)); //O/P: ogr
}
}

14. boolean startsWith(String str):


boolean endsWith(String str): The startsWith( ) method determines whether a
given string begins with a specified string or not. Conversely, endsWith( ) method
determines whether string ends with a specified string or not.

Example:

class s14
{
public static void main(String[] args)
{
String s=new String("Java is a program");
if(s.startsWith("is"))
System.out.println("Match");
else
System.out.println("Not Match");
}
}

O/P: Not Match

15. String concat(String str): It concatenates two string objects.

Example:

class s15
{
public static void main(String[] args)
{
String s=new String("Java ");
String s1=s.concat("program");
System.out.println(s1);
}
}

O/P: Java program

RAKESH.C.M Page 64
16. String replace(char original, char replacement): It replace all characters of one
character in the invoking string with another character.

Example:

class s16
{
public static void main(String[] args)
{
String s="Hello";
System.out.println(s.replace('l','w')); //O/P: Hewwo
}
}

17. String toLowerCase(): It converts all uppercase characters into lowercase


characters of a string.

Example:

class s17
{
public static void main(String[] args)
{
String s="HELLO";
System.out.println(s.toLowerCase()); //O/P: hello
}
}

18. String toUpperCase():It converts all lowercase characters into uppercase


characters of a string.

Example:

class s17
{
public static void main(String[] args)
{
String s="hello";
System.out.println(s.toUpperCase()); //O/P: HELLO }
}

19. String trim(): It returns a copy of the invoking string from which any leading and
lining white space has been removed.

Example:

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

RAKESH.C.M Page 65
String s=" hello";
System.out.println(s.trim());
}
}

20. char[] toCharArray(): It returns a character array containing a copy of the


characters in a string.

Example:

class s20
{
public static void main(String[] args)
{
String s="hello";
char ch[]=s.toCharArray();
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}

21. String toString(): It converts all objects into strings objects.

Example:

class s21
{
public static void main(String[] args)
{
Integer i=new Integer(10);
System.out.println(i.toString()); //O/P: 10
}
}

Example: Write a program for sorting a given list of names in ascending


order.

class lab5
{
public static void main(String[] args)
{
String ch[]={"india","hai","andhra"};
String temp;
for(int i=0;i<ch.length-1;i++)
{
for (int j=i+1;j<ch.length;j++)
{

RAKESH.C.M Page 66
if((ch[i].compareTo(ch[j]))>0)
{
temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
}
}
}
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]);
}
}

Example : Write a program to check whether a given string is palindrome or not.

import javax.swing.JOptionPane;
class lab4
{
public static void main(String[] args)
{
String s;
s=JOptionPane.showInputDialog("Enter a String");
char ch[]=s.toCharArray();
int i,j,count=0;
for(i=0,j=ch.length-1;i<j;i++,j--)
{
if(ch[i]!=ch[j])
{
System.out.println("Not polindrome");
count=1;
break;
}
}
if(count==0)
System.out.println("Polindrome");
}
}

2. StringBuffer Class:
Once a string object is created its contents cannot be changed. But the
StringBuffer class provides the feature of creating and manipulating dynamic string
information i.e., mutable strings. Every StringBuffer class is capable for storing a
number of characters specified by its capacity. If the capacity of StringBuffer
exceeded the capacity is automatically expanded to accommodate the additional
characters.

RAKESH.C.M Page 67
StringBuffer Constructors:

a) StringBuffer(): It is a default StringBuffer Constructor to create StringBuffer with


no characters init and an initial capacity of 16 characters.

b) StringBuffer(String str): It takes a string argument to create a StringBuffer


containing the characters of the string argument. The initial capacity is the number of
arguments in the string argument + 16.

c) StringBuffer(int size): It takes an integer argument and creates a StringBuffer with


no characters init. The initial capacity is specified by the integer.

Example:

class sb
{
public static void main(String[] args)
{
StringBuffer s1,s2,s3;
s1=new StringBuffer();
s2=new StringBuffer("hello");
s3=new StringBuffer(45);
System.out.println(s1.capacity()+s2.capacity()+s3.capacity()); //O/P: 82
}
}

Methods:

1. int length(): It returns the number of characters in a StringBuffer.

Example:

class sb1
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
System.out.println(s.length()); //O/P: 5
}
}

2. int capacity(): It returns the number of characters that can be stored in a


StringBuffer without allocating more memory.

RAKESH.C.M Page 68
Example:
class sb2
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
System.out.println(s.capacity()); //O/P: 21
}
}

3. void ensureCapacity(): It is provided to allow the programmer to guarantee that a


StirngBuffer has a minimum capacity where capacity specifies the size of the buffer.

Example:
class sb3
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("hello");
s.ensureCapacity(75);
System.out.println(s.capacity()); //O/P: 75
}
}

4. void setLength(int len): It increase or decrease the length of StringBuffer.

Example:
class sb4
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdefghijkl");
s.setLength(5);
System.out.println(s); //O/P: abcde
}
}

5. char charAt(int where): It returns a character at the specified where position.

Example:
class sb5
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdefghijkl");
System.out.println(s.charAt(7)); //O/P: h
}
}

RAKESH.C.M Page 69
6. void setCharAt(int where, char ch): It takes an integer and a character argument
and sets the character at the specified position of the character argument.

Example:

class sb6
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdef"); //O/P: Hbcdef
s.setCharAt(0,'H');
System.out.println(s);
}
}

7. void getChars(int Sourcestart, int Sourceend, char Target[], int Targetstart):


It copies the sub string of a StringBuffer into character array. Sourcestart specifies
the starting index from which characters should be copied in StringBuffer. Sourceend
specifies the index one past the last character to be copied from the StringBuffer.
Target specifies the character array into which the characters are to be copied.
Targetstart specifies the starting location of the character array from where the first
character should be placed.

Example:

class sb7
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abc def");
char ch[]=new char[s.length()];
s.getChars(3,s.length(),ch,0);
for(int i=0;i<ch.length;i++)
System.out.println(ch[i]); //O/P: def
}
}

8. StringBuffer reverse(): It returns the reverse contents of the StringBuffer.

Example:

class sb8
{
public static void main(String[] args)
{
StringBuffer s=new StringBuffer("abcdef");
System.out.println(s.reverse());
}
}

RAKESH.C.M Page 70
3. StringTokenizer class:

In programming languages, statements are divided into individual pieces like


identifiers, keywords, and operators etc., called Tokens. Java provides
StringTokenizer class that breaks a string into its component tokens. This class is
available in java.util package. Tokens are separator from one another by delimiters
(special operators), white space characters such as blank, tab, new line and carriage
return.

StringTokenizer Constructors:

a) StirngTokenizer(Stirng str)
b) StirngTokenizer(Stirng str, String delimiters)
c) StirngTokenizer(Stirng str, String delimiters, boolean delimiterAsToken)
In all versions str is a string that is tokenized.
In the first version, the default delimiters are used.
In the second version and third versions delimiters in string that specifies the
delimiters.
In the third version if “delimiterAsToken” is true then the delimiters also
returned as tokens when the string is tokenized otherwise, the delimiters are not
returned. Delimiters are not returned as tokens by the first two forms.

Methods:
1. int countTokens(): Using the current set of delimiters the method determines the
number of tokens left to be tokenized and return the result.
2. boolean hasMoreTokens(): It returns true if one or more tokens remain in the
string and returns false if there are none.
3. String nextToken(): It returns the next token as string.

Example:

import java.util.*;
class st
{
public static void main(String[] args)
{
String s=new String("abc def gh");
StringTokenizer t=new StringTokenizer(s);
System.out.println(t.countTokens());
while(t.hasMoreTokens())
System.out.println(t.nextToken());
}
}

O/P: 3
abc
def
gh

RAKESH.C.M Page 71
Example: Write a program that reads a line of integers, then displays each integer and
the sum of all the integers
import javax.swing.JOptionPane;
import java.util.*;
class lab2c
{
public static void main(String[] args)
{
String s;
s=JOptionPane.showInputDialog("Enter the string");
StringTokenizer t=new StringTokenizer(s,"$");
int a,sum=0;
System.out.println("Integers Count:");
System.out.println(t.countTokens());
System.out.println("Given Values are:");
while(t.hasMoreTokens())
{
a=Integer.parseInt(t.nextToken());
System.out.println(a);
sum=sum+a;
}
System.out.println("Total="+sum);
}
}
Example: Write a java program to make frequency count of words in a given text
import java.io.*;
import java.lang.*;
import java.util.*;
class Frequency
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the line of text");
String str=dis.readLine();
System.out.println("Enter the string");
String s1=dis.readLine();
StringTokenizer st=new StringTokenizer(str);
int count=0;
while(st.hasMoreTokens())
{
if(s1.compareTo(st.nextToken())==0)
count++;
else
continue;
}
System.out.println("Frequency="+count);
}
}

RAKESH.C.M Page 72
Garbage Collection

Objects are dynamically allocated by using the new operator such objects are
destroyed automatically and their memory released for later reallocation in Java. The
technique that accomplishes this is called “Garbage Collection”. Garbage collection
works when no references to an object exist, the object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed. Java run-time
implementations will take various approaches to garbage collection.

finalize( ) method:

The garbage collector of an object called this method when the garbage
collection determines that those are no more references to the object. It is also placed
some actions inside the finalized method. The following points are related to
finalize() method.

1. Every class has Object class as a super class


2. Every class in Java can have a finalize( ) method that returns resources to
the system
3. A class should have only one finalize( ) method that takes no argument.
Method finalize( ) is originally defined in class Object

The finalize( ) method has the following syntax

Syntax: protected void finalize( )


{
// finalization code
}

Example:

class Garbage extends Object


{
int x,y;
void setdata(int a,int b)
{
x=a;
y=b;
}
void printdata()
{
System.out.println("x="+x+" y="+y);
}
protected void finalize()
{
System.out.println("finalizer");
}
}

RAKESH.C.M Page 73
class Mg
{
public static void main(String[] args)
{
Garbage obj=new Garbage();
Garbage obj1=new Garbage();
obj.setdata(10,20);
obj.printdata();
obj1=null;
System.gc(); // method to call garbage collector
//obj1.setdata(2,3); //error
obj.printdata();
}
}

O/P: x=10 y=20


finalizer
x=10 y=20

***

RAKESH.C.M Page 74
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY,
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-III: Inheritance: Hierarchical abstractions, Base class object, sub class,


subtype, substitutability, forms of inheritance – specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance, Member
access rules, super uses, using final with inheritance, polymorphism – method overriding,
abstract classes.

INHERITANCE

The mechanism of deriving a new class from an old one is called inheritance.
A class that is inherited (old class) is called a super class or base class or parent class.
The class that does the inheriting (new class) is called a subclass or derived class or
child class. Inheritance allows subclasses to inherit all the variables and methods of
their parent classes.

Inheritance is classified into different forms.

a) Single Inheritance: Derivation a subclass from only one super class is called
Single Inheritance.

A Super class (or) Base class (or) Parent class

B Subclass (or) Derived class (or) Child class

b) Hierarchical Inheritance: Derivation of several classes from a single super class


is called Hierarchical Inheritance.

B C D

RAKESH.C.M Page 75
c) Multilevel Inheritance: Derivation of a class from another derived class s called
Multilevel Inheritance.

d) Multiple Inheritance: Derivation of one class from two or more super classes is
called Multiple Inheritance. But Java does not support Multiple Inheritance directly.
It can be implemented by using Interface concept.

A B

e) Hybrid Inheritance: Derivation of a class involving more than one form of


Inheritance is called Hybrid Inheritance.

B C

RAKESH.C.M Page 76
Defining a Subclass: A subclass is defined as

Syntax: class subclass-name extends superclass-name


{
variable declaration;
method declaration;
}

The keyword extends signifies that the properties of the super class name are
extended to the subclass name. The subclass will now contain its own variables and
methods as well as those of the super class. But it is not vice-versa.

// EXAMPLE PROGRAM FOR SINGLE INHERITANCE

class A
{
int len,bre;
void getdata(int x,int y)
{
len=x;
bre=y;
}
void printdata()
{
System.out.println("length="+len);
System.out.println("Breadth="+bre);
}
}
class B extends A
{
int wid;
void putdata(int x,int y,int z)
{
len=x;
bre=y;
wid=z;
}
void printdata1()
{
printdata();
System.out.println("Width="+wid);
}
void calarea()
{
int area=len*bre*wid;
System.out.println("Area="+area);
}
}

RAKESH.C.M Page 77
class Single
{
public static void main(String[] args)
{
B obj=new B();
obj.putdata(10,20,30);
obj.printdata1();
obj.calarea();
}
}

// EXAMPLE PROGRAM FOR HIERARCHICAL INHERITANCE

class A
{
int len,bre;
void getdata(int x,int y)
{
len=x;
bre=y;
}
void printdata()
{
System.out.println("length="+len);
System.out.println("Breadth="+bre);
}
}

class B extends A
{
int wid;
void getdata1(int x,int y)
{
getdata(x,y);
}
void calarea()
{
printdata();
int area=len*bre;
System.out.println("Area="+area);
}
}

class C extends A
{
int wid;
void putdata(int x,int y,int z)
{
len=x;

RAKESH.C.M Page 78
bre=y;
wid=z;
}
void printdata1()
{
printdata();
System.out.println("Width="+wid);
}
void calarea1()
{
int area=len*bre*wid;
System.out.println("Area="+area);
}
}

class Hierarchical
{
public static void main(String[] args)
{
B obj=new B();
obj.getdata1(10,20);
obj.calarea();

C obj1=new C();
obj1.putdata(1,2,3);
obj1.printdata1();
obj1.calarea1();
}
}

// EXAMPLE PROGRAM FOR MULTILEVEL INHERITANCE

import javax.swing.JOptionPane;
class Student
{
int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
void printdata1()
{
System.out.println("Roll Number="+rno);
}
}

RAKESH.C.M Page 79
class Exam extends Student
{
int m1,m2,m3;
void readdata2()
{
readdata1();
m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));
m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));
m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));
}
void printdata2()
{
printdata1();
System.out.println("Sub 1 marks="+m1);
System.out.println("Sub 2 marks="+m2);
System.out.println("Sub 3 marks="+m3);
}
}
class Results extends Exam
{
int avg;
void printdata3()
{
printdata2();
avg=(m1+m2+m3)/3;
if(avg<35)
System.out.println("FAIL");
else if(avg>=35 && avg<50)
System.out.println("THIRD CLASS");
else if(avg>=50 && avg<60)
System.out.println("SECOND CLASS");
else if(avg>=60 && avg<75)
System.out.println("FIRST CLASS");
else if(avg>=75)
System.out.println("DISTINCTION");
}
}

class Multilevel
{
public static void main(String[] args)
{
Results obj=new Results();
obj.readdata2();
obj.printdata3();
}
}

RAKESH.C.M Page 80
Member Access Rules:

1. By means of sub class object it is possible to access all the instance variables and
instance methods of the super class.
2. By means of sub class object it cannot be possible to access the instance variable of
super class, if it is declared as private. Since, the data is protected in that class.

import javax.swing.JOptionPane;
class Student
{
private int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
}
class Exam extends Etudent
{
void printdata1()
{
readdata1();
System.out.println("Roll Number="+rno); // produces compilation error
}
}
class MLevel
{
public static void main(String[] args)
{
Exam obj=new Exam();
obj.printdata1();
}
}

3. Referring to super class object with a subclass reference produces syntax error. In
such case we need type casting.

Example:

import javax.swing.JOptionPane;
class Student
{
int rno;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
}
}

RAKESH.C.M Page 81
class Exam extends Student
{
void printdata1()
{
readdata1();
System.out.println("Roll Number="+rno);
}
}
class Mit
{
public static void main(String[] args)
{
Student s1=new Exam();
Exam e1=(Exam)s1;
e1.printdata1();
}
}

super keyword: A subclass constructor is used to construct the instance variable


of both the subclass and the super class. The subclass constructor uses the keyword
super to invoke the constructor method of the super class. The keyword super is used
subject to the following conditions.

 super may be used only within the subclass constructor method


 The call to super class constructor must appear as the first statement with in
the subclass constructor
 If a parameterized constructor is used, then the signature is matched with the
parameters passed to the super method as super(parameter-list);

Example 1:

class Student
{
public Student()
{
System.out.println("super");
}
}
class Exam extends Student
{
public Exam()
{
System.out.println("sub");
}
}

RAKESH.C.M Page 82
class St
{
public static void main(String[] args)
{
Exam obj=new Exam();
}
}

O/P: super
sub

Example 2:

class Student
{
public Student()
{
System.out.println("super");
}
}
class Exam extends student
{
public Exam()
{
super( ); // explicit call of super( )
System.out.println("sub");
}
}
class Stl
{
public static void main(String[] args)
{
Exam obj=new Exam();
}
}

O/P: super
sub

Example 3:

class Student
{
int len,bre;
public Student(int a,int b)
{
len=a;
bre=b;
}

RAKESH.C.M Page 83
int area()
{
return len*bre;
}
}
class Exam extends Student
{
int ht;
public Exam(int x,int y,int z)
{
super(x,y);
ht=z;
}
int volume()
{
return len*bre*ht;
}
}
class s
{
public static void main(String[] args)
{
Exam obj=new Exam(2,3,4);
System.out.println("area="+obj.area());
System.out.println("volume="+obj.volume());
}
}

Another important use of super is applicable to situations in which member


names of a subclass hide members by the same name in the super class. It is similar
to the ‘this’ keyword except that it always refers to the super class of the subclass in
which it is used. The general form is as:

super.member;

Where,
member can be either a method or an instance variable

Example:

class A
{
int i=7;
}
class B extends A
{
int i=6;

RAKESH.C.M Page 84
void show()
{
System.out.println("super i="+super.i);
System.out.println("sub i="+i);
}
}

class s1
{
public static void main(String[] args)
{
B obj=new B();
obj.show();
}
}

FORMS OF INHERITANCE

The various forms of inheritance follows the lists as:

Specialization : The child class is a special case of the parent class; in


otherwords, the child class is a subtype of the parent class.

Specification: The parent class defines behavior that is implemented in the


child class but not in the parent class.

Construction: The child class makes use jof the behavior provided by the
parent class but is not a subtype of the parent class.

Extension: The child class adds new functionality to the parent class, but
does not change any inherited behavior.

Limitation: The child class restricts the use of some of the behavior
inherited from the parent class.

Combination: The child class inherits features from more than one parent
class. Although multiple inheritance is not supported directly
by Java, it can be simulated in part by classes that used both
inheritance and implementation of an interface, or implementj
two or more interfaces.

BENEFITS OF INHERITANCE

Important benefits of the inheritance are:

1. Software Reusability:

When behaviour is inherited from another class, the code that provides that
behavior doesnot have to be rewritten.

RAKESH.C.M Page 85
2. Increased Reliability:

When the same components are used in two or more applications, the code
will be exercised more than code that is developed for a single application. Thus, the
bugs in each such code tends to be discovered more quickly, and later application
gains the benefit of using components that are more error free.

3. Code Sharing:

Code sharing can occur on several levels with object oriented techniques.
Form of sharing occurs when two or more classes developed by a single programmer
as part of a probject inherits from a single parent class.

4. Consistency of Interface:

When two or more classes inherits from the same upper class, we are assured
that the behavior they inherts will be same on all cases.

5. Software Components:

Inheritance enables programmers to construct reusable software


components.The goal is to permit the development of new and novel applications that
nevertheless require little or no actual coding.

6. Rapid Prototyping:

When a software system is constructed largely out of reusable components,


developers can concentrate their time on understanding the new and unusual portion
of the system. Thus, software system can be generated more quickly and easily,
leading to a style of programming known as rapid prototyping or exploratory
programming.A prototype system is developed ,users experiment with it, a second
system is produced that is based on experience with the first further experimentation
takes place, and so on for several iterations.

7. Polymorphism and Frameworks:

Polymorphism in programming language permits the programmer to generates


high level reusable components that can be tailored to fit different applications by
change in their low-level parts.

8. Information Hiding:

A programmer who reuses a software components need only to understand the


nature of the component and its interface.It is not necessary for the programmer to
have detailed information concerning matters such as the technique used to implement
the component.

RAKESH.C.M Page 86
THE COSTS OF INHERITANCE

1. Execution Speed
2. Program Size
3. Message-Passing Overhead
4. Program Complexity

POLYMORPHISM

Method Overriding
A method in a subclass has the same name, type of the variables and order of
the variables as a method in its super class, then the method in the subclass is said to
be override the method in the super class. The process is called Method Overriding.
In such process the method defined by the super class will be hidden.
When the method is called, the method defined in the super class has invoked
and executed instead of the method in the super class. The super reference followed
by the dot (.) operator may be used to access the original super class version of that
method from the subclass.

Note: 1. Method Overriding occurs only when the name and type signature of
the two methods are identical.
2. If method name is identical and the type signature is different, then the
process is said to be Method Overloading.

Example 1:

class A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}

RAKESH.C.M Page 87
class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
System.out.println("k="+k);
}
}
class override
{
public static void main(String[] args)
{
B obj=new B(1,2,3);
obj.show();
}
}

O/P: k=3

Example 2:

class A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}

class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}

RAKESH.C.M Page 88
void show()
{
super.show();
System.out.println("k="+k);
}
}
class Override
{
public static void main(String[] args)
{
B obj=new B(1,2,3);
obj.show();
}
}

O/P: i=1
j=2
k=3

Resolve the method call at compile time is known as “compile time” or


“early binding” or “static binding”. Resolve the method at run time is known as
“run time” or “late binding” or “dynamic binding”.

Method Overriding forms on the basis of Java concept Dynamic Method


Dispatch. It is the mechanism by which a call to an overridden function is resolved at
run time, rather than compile time. And this method is very useful to show for Java
implements run-time polymorphism.

“Super class reference variable can refer to a subclass object” is the principle
to resolve calls to overridden methods at run time. If a super class contains a method
that is overridden by a subclass, then when different types of objects are referred to
through a super class reference variable, different version of the methods are executed
and the determination is made at run time.

// Example program for Java supports Run time Polymorphism.

class Figure
{
double dim1,dim2;
Figure(double x,double y)
{
dim1=x;
dim2=y;
}
double area()
{
System.out.println("Area undefined");
return 0;
}
}

RAKESH.C.M Page 89
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Rectangle Area");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("Triangle Area");
return dim1*dim2/2;
}
}
class Run
{
public static void main(String[] args)
{
Figure obj=new Figure(10,10);
Rectangle obj1=new Rectangle(9,5);
Triangle obj2=new Triangle(10,8);

figure a; //a is a reference of type figure(super class)


a=obj1; //a refers to object of rectangle(sub class)
System.out.println("Area="+a.area());

a=obj; //a refers to object of figure


System.out.println("Area="+a.area());

a=obj2; //a refers to object of triangle


System.out.println("Area="+a.area());
}
}

O/P: Rectangle Area


Area=45.0
Area undefined
Area=0.0
Triangle Area
Area=40.0

RAKESH.C.M Page 90
ABSTRACT CLASS

Classes from which objects cannot be instantiated with new operator are called
Abstract Classes. Each abstract class contains one or more abstract methods. In a
class if there exist any method with no method body is known as abstract method. An
abstract method is declared as:

Syntax: abstract type method-name (parameter-list);

“abstract” is a keyword used for declaring abstract methods. To declare a


class as abstract, use the abstract keyword in front of the class keyword at the
beginning of the class declaration. No objects are created to an abstract class. For the
abstract methods, the implementation code will be defined in its subclass.

// EXAMPLE PROGRAM FOR ABSTRACAT CLASS

abstract class Figure


{
double dim1,dim2;
Figure(double x,double y)
{
dim1=x;
dim2=y;
}
abstract double area();
}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Rectangle Area");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("Triangle Area");
return dim1*dim2/2;
}
}

RAKESH.C.M Page 91
class Abst
{
public static void main(String[] args)
{
//Figure obj=new Figure(10,10); //error

Rectangle obj1=new Rectangle(9,5);


System.out.println("Area="+obj1.area());

Triangle obj2=new Triangle(10,8);


Figure a;
a=obj2;
System.out.println("Area="+a.area());
}
}

Example: Write a java program to create an abstract class name Shape that
contains an empty method named numberOfSides().Provide three classes named
Trapezoid, Triangle, Hexagon such that each one of the classes extends the class
Shape. Each one of the classes contains only the method numberOfSides() that
shows the number of sides in the given geometrical figures.

abstract class Shape


{
public abstract void numberOfSides();
}

class Trapezoid extends Shape


{
public void numberOfSides()
{
System.out.println("Number of sides"+4);
}
}
class Triangle extends Shape
{
public void numberOfSides()
{
System.out.println("Number of sides"+3);
}
}
class Hexagon extends Shape
{
public void numberOfSides()
{
System.out.println("Number of sides"+6);
}
}

RAKESH.C.M Page 92
public class Sides
{
public static void main(String[] args)
{
Trapezoid t=new Trapezoid();
Triangle t1=new Triangle();
Hexagon h=new Hexagon();
t.numberOfSides();
t1.numberOfSides();
h.numberOfSides();
}
}

Note: 1. We cannot declare any abstract constructors.


2. Concrete (general) methods are also being inside any abstract class.
3. Abstract classes are used for general purposes.
4. An abstract class must be subclass and override it methods.
5. Super class has only method name and signature end with semicolon.
6. Abstract classes cannot be used to instantiate objects, but they can used to
create object reference due to Java supports Run-time Polymorphism.

final keyword

A final is a keyword used for three purposes. They are

a) final as constant: A variable can be declared as constant with the keyword final. It
must be initialized while declaring. One we initialized the variable with final
keyword it cannot be modified in the program. This is similar to the const in C/C++.
Example: final int x = 10;
x = 45 //error

b) final to prevent overriding: A method that is declared as final cannot be


overridden in a subclass method. It the methods that are declared as private are
implicitly final.

Example: class A
{
final void show( )
{
System.out.println(“Hello”);
}
}

RAKESH.C.M Page 93
class B extends A
{
void show( )
{ //error
System.out.println(“Hai”);
}
}

c) final to prevent inheritance: The class that is declared as final implicitly declares
all of its methods as final. The class cannot be extended to its subclass.

Example: final class A


{
void show( )
{
System.out.println(“Hello”);
}
}
class B extends A //error
{
void show( )
{
System.out.println(“Hai”);
}
}

OBJECT CLASS

Java provides a special class called “Object” class that is available in java.lang
package. It is the super class of all other classes. So, a reference variable of type
Object is created, it refers to object of any other class. Object class defines the
following methods that are available in every object.

Method Purpose
Object clone( ) Creates a new object that is the same as the
object being cloned
boolean equals(Object object) Determines whether one object is equal to
another
void finalize( ) Called before an unused object is recycled
Class getClass( ) Obtains the class of an object at run time
int hashCode( ) Returns the hash code associated with the
invoking object
void notify( ) Resumes execution of a thread waiting on
the invoking object
void notifyAll( ) Resumes execution of all threads waiting
on the invoking object
String toString( ) Returns a string that describes the object

RAKESH.C.M Page 94
void wait( ) Waits on another thread of execution
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds)

Array of Objects: To instantiate more than one object for a single class, we use
Array of Objects.

Example:

import javax.swing.JOptionPane;
class A
{
int x,y;
void readdata()
{
x=Integer.parseInt(JOptionPane.showInputDialog("Enter x value"));
y=Integer.parseInt(JOptionPane.showInputDialog("Enter y value"));
}
void printdata()
{
System.out.println("x="+x+"\n"+"y="+y);
}
}
class Aob
{
public static void main(String[] args)
{
a ob[]=new a[5];
for(int i=0;i<5;i++)
{
ob[i]=new a();
ob[i].readdata();
ob[i].printdata();
}
}
}

***

RAKESH.C.M Page 95
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY,
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-IV: Packages and Interfaces: Defining, Creating and Accessing a Package,


Understanding CLASSPATH, importing packages, differences between classes and
interfaces, defining an interface, implementing interface, applying interfaces, variables in
interface and extending interfaces, Exploring packages – java.io, java.util.

INTERFACES

Interface is a collection of method declaration and constants that one or more


classes of objects will use. Interface definition is same as class except that it consists
of the methods that are declared have no method body. They end with a semicolon
after the parameter list. Syntax for an interface is as follows.

Syntax: <access specifier> interface <it-name>


{
type varname1=value;
type varname2=value;
.
.
returntype method-name1(parameter-list);
returntype method-name2(parameter-list);
.
.
}

Here,
 access specifier is public or not used. public access specifier indicates that the
interface can be used by any class. Otherwise, the interface will accessible to
class that are defined in the same package as in the interface.
 interface keyword is used to declare the class as an interface.
 it-name is the name of the interface and it is a valid identifier.
 Variables declared inside the interface are implicitly final and static. They
cannot be changed in the implementing class.
 All the methods in an interface are implicitly abstract methods. Method
implementation is given in later stages.
 The main difference between a class and interface is class contains methods
with method body and the interface contains only abstract methods.

Example: public interface shape


{
int radius=2;
public void area(int a);
}

RAKESH.C.M Page 96
Implementing Interfaces: Once an interface has been defined, one or more classes
can implement that interface. “implements” keyword used for implementing the
classes. The syntax of implements is as follows.

Syntax: class class-name implements interface1, interface2, .. interfacen


{
……..
…….. // class body
……..
}

If a class implements more than one interface, the interfaces are separated with
a comma operator. The methods that implement an interface must be declared public.
Also type signature of the implementing method must match exactly the type
signature specified in the interface definition.

Example:

interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it2 obj=new it2();
obj.add(3,4);
obj.sub(5,2);
System.out.println(obj.x+obj.y);
obj.x=70; // error since x is final variable in interface
}
}

Note:
1. Interface methods are similar to the abstract classes so, that it cannot be
instantiated.
2. Interface methods can also be accessed by the interface reference variable
refer to the object of subclass. The method will be resolved at run time. This process
is similar to the “super class reference to access a subclass object”.

RAKESH.C.M Page 97
Example:

interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it2 obj=new it2();
it1 ref;
ref=obj;
System.out.println(ref.x+ref.y);
}
}

3. If a class includes an interface but does not fully implement the methods
defined by that interface, then the class becomes abstract class and must be declared
as abstract in the first line of its class definition.

Example:

interface it1
{
int x=10,y=20;
public void add(int a,int b);
public void sub(int a,int b);
}
abstract class it2 implements it1
{
public void add(int s,int w)
{
System.out.println("Addition="+(s+w));
}
}

RAKESH.C.M Page 98
class it3 extends it2
{
public void sub(int s,int w)
{
System.out.println("Subtraction="+(s-w));
}
public static void main(String[] args)
{
it3 obj=new it3();
obj.add(5,6);
}
}

Various forms of Interface Implementations:

1. interface A

implements
B
class
extends

class C

2. interface A
implements implements

interface B interface C

3.
class A D interface

extends extends
implements
class B E interface

extends

class C

RAKESH.C.M Page 99
4. interface A B interface

implements implements

C
interface

implements

D
class

Multiple Inheritance: Multiple Inheritances does not support by Java directly.


Multiple Inheritances enables to derive a class from multiple parent classes.

Let A and B are parent classes and C is the derived class

A B

Java provides Interface approach to support the concept of Multiple


Inheritance. A class can also implement multiple interfaces.

Example:
class Test
{
int sub1,sub2,sub3;
void readdata1(int x,int y,int z)
{
sub1=x;
sub2=y;
sub3=z;
}
void printdata1()
{
System.out.println("sub1 marks="+sub1);
System.out.println("sub2 marks="+sub2);
System.out.println("sub3 marks="+sub3);

}
}
RAKESH.C.M Page 100
interface Sports
{
int smarks=55;
public void printdata2();
}

class Result extends Test implements Sports


{
int sum;
public void printdata2()
{
printdata1();
sum=sub1+sub2+sub3+smarks;
System.out.println("Total Marks="+sum);
}
}

class Multiple
{
public static void main(String[] args)
{
Result obj=new Result();
obj.readdata1(35,67,89);
obj.printdata2();
}
}

Hybrid Inheritance: Derivation of a class involving more than one form of


Inheritance is called Hybrid Inheritance.

B C

RAKESH.C.M Page 101


Example:

import javax.swing.JOptionPane;
class Student
{
int rno;
String name;
void readdata1()
{
rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));
name=JOptionPane.showInputDialog("Enter name");
}
void printdata1()
{
System.out.println("Roll number="+rno);
System.out.println("Name ="+name);
}
}
class Test extends Student
{
int m1,m2,m3;
void readdata2()
{
m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));
m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));
m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));
}
void printdata2()
{
System.out.println("Sub1="+m1+" Sub2="+m2+" Sub3="+m3);
}
}
interface Sports
{
int smarks=55;
public void printdata3();
}

class Result extends Test implements Sports


{
int sum;
public void printdata3()
{
System.out.println("Sports marks="+smarks);
}
public void readdata3()
{
readdata1();
readdata2();
}

RAKESH.C.M Page 102


public void printdata4()
{
sum=m1+m2+m3+smarks;
printdata1();
printdata2();
printdata3();
System.out.println("Total Marks="+sum);
}
}

class Hybrid
{
public static void main(String[] args)
{
Result obj=new Result();
obj.readdata3();
obj.printdata4();
}
}

PACKAGES

Package is a collection of related classes. Each class defines number of methods.


Java packages are classified into 2 types.

1. Java API (Application Programming Interface) packages (or) Predefined


packages (or) Built-in packages: These packages are defined by the system.
Some of the example for system defined packages are:
Ex: java.lang, java.util, java.io, java.awt, java.applet etc.,

2. User defined packages: These packages are defined by the user.

Defining a Package:

To define a package, place “package” command as the first statement in the


Java source file. So, that any class declared within that file will belong to the
specified package. The syntax of package creation is as follows.

Syntax: package pack-name;

Where,
pack-name is the name of the package.

RAKESH.C.M Page 103


Example: package mypack;
public class number
{
public void add (int a,int b)
{
System.out.println(“Sum=”+(a+b));
}
}

 The class that is defined in the package must be start with the public access
modifier. So, that it can be accessible by any another of them. If it is not
public, it is possible to access only in that package.
 Java uses file system directories to store packages. We save the program with
number.java and compile the package is as

javac –d . number.java

Due to this compilation mypack directory is automatically created and .class


file is stored in that directory.
 Package creation has completed. The package information is now including in
our actual program by means of “import” statement. “import” is a keyword
that links the package with our program. It is placed before the class
definitions.
import mypack.*;
or
import mypack.number;

Example 1:

import mypack.number;
class pack
{
public static void main(String[] args)
{
number obj=new number();
obj.add(3,4);
}
}

Example 2:

package math1;
public class Mcal
{
public void square(int x)
{
System.out.println("Square of "+x+" is"+(x*x));
}

RAKESH.C.M Page 104


public void cube(int x)
{
System.out.println("cube "+x+" is"+(x*x*x));
}
}

import math1.Mcal;
class calc
{
public static void main(String[] args)
{
Mcal obj=new Mcal();
obj.square(3);
obj.cube(4);
}
}

Example 3:

package p6;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal<0)
{
System.out.println(name+"---"+bal);
}
}
}

import p6.Balance;
class Account
{
public static void main(String[] args)
{
Balance c[]=new Balance[3];
c[0]=new Balance("John",123.33);
c[1]=new Balance("Arun",157.02);

RAKESH.C.M Page 105


c[2]=new Balance("Siri",-12.33);
for(int i=0;i<3;i++)
c[i].show();
}
}

Note:

1. Java source file contains only one public class and any number of non-
pubic classes. The filename should be same as the name of the public class with .java
extension.

2. Package contain any number of public and default classes.

Example: package p1;


public class x
{
// body of x this class is accessible
}
class y
{
// body of y not accessible due to non-use
of public access modifier
}

Let we want to access all the classes of information then the classes are
stored in different files with the same package name.

Example: package mypack;


public class number
{
public void add (int a,int b)
{
System.out.println(“Sum=”+(a+b));
}
}

package mypack;
public class number1
{
public void sub(int a,int b)
{
System.out.println("sub="+(a-b));
}
}

RAKESH.C.M Page 106


import mypack.number;
import mypack.number1;
class pack
{
public static void main(String[] args)
{
number obj=new number();
obj.add(3,4);
number1 obj1=new number1();
obj1.sub(6,2);
}
}

Sub Packages: It is also possible to create sub packages for the main package.

Syntax: package pack1.pack2;


Where,
pack1 is the main package and pack2 is the sub package.

Example:
package pack1;
public class x
{
public void show()
{
System.out.println("Super");
}
}
package pack1.pack2;
public class y
{
public void display()
{
System.out.println("Sub");
}
}

import pack1.x;
import pack1.pack2.y;
class che
{
public static void main(String[] args)
{
x obj=new x();
obj.show();
y obj1=new y();
obj1.display();
}
}
RAKESH.C.M Page 107
Access Protection

Java provides four types Access modifiers as public, private, default and
protected. Any variable declared as public, it could be accessed from anywhere. Any
variable declared as private cannot be seen outside of its class. Any variable declared
as default, it is visible to subclasses as well as to other classes in the same package.
Any variable declared as protected, it allows an element to be seen outside of current
package, but only to classes that subclass directly.

public private default protected


Same class Yes Yes Yes Yes
Same package sub class Yes No Yes Yes
Same package non-subclass Yes No Yes Yes
Different package sub class Yes No No Yes
Different package non-subclass Yes No No No

Example:

package p1;
public class protect
{
int n=1;
private int n_pri=2;
protected int n_pro=3;
public int n_pub=4;
public protect()
{
System.out.println("Super constructor");
System.out.println("default="+n);
System.out.println("private="+n_pri);
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}

package p1;
class derive extends protect
{
derive()
{
System.out.println("Sub constructor");
System.out.println("default="+n);
//System.out.println("private="+n_pri);
//since it is a private variable in package p1
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}

RAKESH.C.M Page 108


import p1.protect;
class same
{
public static void main(String[] args)
{
protect obj=new protect();
}
}

CLASSPATH

A class path is an environmental variable, which tells the java virtual machine and
other java tools (java, javac), where to find the class libraries, including user-defined
class libraries.

By default, java uses the classpath as

C:\jdk1.2.1\lib\classes.zip

A user defined class path is set for the environment as

C:\>SET CLASSPATH=%CLASSPATH%;C:\P

RAKESH.C.M Page 109


FILES

Data storage in variables and arrays is temporary. The data is loss when the
program terminates. Files are used for long term storage of large amounts of data,
even after the program that created the data terminates.

File: A File is a collection of related records placed in a specific area on the disk.
Data that is stored in files is often called persistent data. A record is a collection of
several fields and the field is a collection of characters. Each character in a computer
character set is represented as a pattern of 1’s and 0’s.
Creation, Updating, Managing data etc., using file is known as ‘File Processing’.

File Class: java.io package supports for Input & Output operations on files. This
package provides a class known as File Class to creating Files. File Object is used to
manipulate or obtain the information associated with a disk file, such as permission,
data, directory path and soon.

The following constructors are used to create a File Object.

File (String directorypath)


File (String directorypath, String filename)
File (File object, String filename)

Methods:

1. boolean canRead( )
2. boolean canWrite( )
3. boolean exists( )
4. String getName( )
5. String getParent( )
6. String getPath( )
7. boolean isDirectory( )
8. boolean isFile( )
9. long length( )
10. long lastModified( )
11. boolean isHidden( )
12. String getAbsolutePath( )
13. boolean isAbsolute( )
14. String [] list( )

RAKESH.C.M Page 110


Example:

import java.io.*;
class FileDemo
{
public static void main(String[] args)
{
File f=new File("D:/shabbir/wish.java");
System.out.println(f.canRead()); //true
System.out.println(f.canWrite()); //true
System.out.println(f.exists()); //true
System.out.println(f.getName()); //wish.java
System.out.println(f.getParent()); //D:\shabbir
System.out.println(f.getPath()); //D:\shabbir\wish.java
System.out.println(f.isDirectory()); //false
System.out.println(f.isFile()); //true
System.out.println(f.length()); //210
System.out.println(f.lastModified()); //1165345688000
System.out.println(f.isHidden()); //false
System.out.println(f.getAbsolutePath()); //D:\shabbir\wish.java
System.out.println(f.isAbsolute()); //true
}
}

Example: Write a program to display all files in the given directory

import java.io.*;
class All
{
public static void main(String[] args)
{
File f=new File("D:/shabbir");
String str[]=null;
if(f.isDirectory())
str=f.list();
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
}

FilenameFilter Interface: list( ) method, it returns all the files existed in the given
directory. When we want to limit the number of files returned by the list( ) method to
include only those files that match a certain filename pattern or filtered, such case use
the second form of list( ) method as

Syntax: String [] list(FilenameFilter obj)

RAKESH.C.M Page 111


Here, obj is an object of class that implements the FilenameFilter interface.
FilenameFilter interface defines only a single method, accept( ), which is called once
for each file in a list. Its general format is as:

Syntax: boolean accept(File directory, String filename)

The accept( ) method returns true for files in the directory specified by
directory that should be included in the list; otherwise false.

Example: Write a program to list the filenames that are ended with .java extension

import java.io.*;
class Filter implements FilenameFilter
{
public boolean accept(File f,String str)
{
if(str.endsWith(".java"))
return true;
else
return false;
}
}
class AllDemo
{
public static void main(String[] args)
{
File f=new File("D:/shabbir");
Filter obj=new Filter();
String str[]=null;
if(f.isDirectory())
str=f.list(obj);
for(int i=0;i<str.length;i++)
System.out.println(str[i]);
}
}

STREAMS

A Stream is an abstraction that either produces of consuming information i.e.,


flow of data. A stream is linked to a physical device by the java I/O system. So, that
an input stream can abstract many kinds of input from a disk file, keyboard, network
socket etc., output stream refers to file, network connection, printer etc.,

When a file is opened, an object is created and a stream is associated with the
object. Three stream objects are created by the java system automatically when the
program execution begins. They are:

1) System.in 2) System.out 3) System.err

RAKESH.C.M Page 112


System.in : It is a standard input stream object. It enables a program to input bytes
from the keyboard.
System.out: It is a standard output stream object. It enables a program to output data
to the screen.
System.err: It is a standard error stream object. It enables a program to output error
message to the screen.

I/O STREAM HIERARCHY:

I/O Streams

Byte Streams Character Streams

InputStream OutputStream Reader Writer

Java 2 defines two types of Streams called Byte Streams and Character
Streams.
Byte Stream provides a convenient way for handling input and output of bytes of data.
Character Stream provides a convenient way for handling input and output of
characters of data.

Byte Streams: Byte Stream classes are used for processing the data in the form of
bytes. This class defines two important abstract classes called InputStream and
OutputStream.

InputStream: It is an abstract class that defines Java’s model of streaming byte input.
The system is reading the data in the form of bytes from the physical device using
InputStream. The methods that are provided by the InputStream class are:

a) int available( ): Returns number of bytes of input currently available for


reading
b) void close( ): Closes this input stream and releases any system resources
associated with the stream.
c) int read( ): Reads the next byte of data from the input stream. The value byte
is returned as an int in the range 0 to 255. If no byte is available because the
end of the stream has been reached, the value -1 is returned.
d) int read(byte []b): It reads upto b.length bytes into b and return the actual
number of bytes that were successfully read. –1 is returned when the end of
file is encountered.

RAKESH.C.M Page 113


e) int read(byte []b, int off, int n): It attempt to read n number of bytes into byte
array b starting from the off and returns number of bytes when successfully. –
1 is returned when the end of file is encountered.
f) long skip(long n): Skips over and discards n bytes of data from this input
stream and returns the number of bytes skipped.

OutputStream: It is an abstract class that defines Java’s model of streaming byte


output. The system is sending the data in the form of bytes to the physical device
using OutputStream. The methods that are provided by the OutputStream class are:

a) void close( ): Closes this output stream and releases any system resources
associated with this stream.
b) void flush( ): It clears the output buffers.
c) void write(int b): Write a single byte b to an output stream.
d) void write(byte buf[]):Writes buf.length bytes from the specified byte array
to this output stream.
e) void write(byte buf[], int off, int len): Writes len bytes from the specified
byte array starting at offset off to this output stream.

FileInputStream

FileInputStream is derived from InputStream and used to read bytes of data


from a file. Constructors of FileInputStream are:

FileInputStream (String filepath)


FileInputStream (File fileobj) IS
Here, filepath is the full path name of the file
fileobj is a File object that describes the file.
FIS

Example:

import java.io.*;
class FISDemo
{
public static void main(String[] args)throws IOException
{
FileInputStream fis=new FileInputStream("d:/shabbir/wi.txt");
System.out.println(fis.available());
int k;
while((k=fis.read())!=-1)
System.out.print((char)k);
fis.close();
}
}

RAKESH.C.M Page 114


FileOutputStream

FileOutputStream is derived from OutputStream and used to send bytes of


data into a file. Constructors of FileOutputStream are:

FileOutputStream (String filepath)


OS
FileOutputStream (File fileobj)
FileOutputStream (String filepath, boolean append)

Here, filepath is the full path name of the file FOS


fileobj is a File object that describes the file
if append is true, then the file is in append mode.

Example 1:

import java.io.*;
class FOSDemo1
{
public static void main(String[] args)throws IOException
{
FileOutputStream fos=new FileOutputStream("d:/shabbir/tt.txt");
fos.write(65); //O/P: A
fos.close();
FileOutputStream fos1=new FileOutputStream("d:/shabbir/tt.txt",true);
byte buf[]={66,67,68,69,70};
fos1.write(buf); //O/P: ABCDEF
fos1.close();

}
}

Example 2:

import java.io.*;
class FO SDemo2
{
public static void main(String[] args)throws IOException
{
FileOutputStream fos=new FileOutputStream("d:/shabbir/wi1.txt");
String s=new String("hello");
byte b[]=s.getBytes(); //this method converts string into byte array
fos.write(b);
fos.close();
}
}

//O/P: hello

RAKESH.C.M Page 115


// Example program to copy the contents of a file into another using FileInputStream
and FileOutputStream.

import java.io.*;
class CopyDemo
{
public static void main(String[] args)throws IOException
{
FileInputStream fis=new FileInputStream("d:/shabbir/wi.txt");
FileOutputStream fos=new FileOutputStream("d:/shabbir/ci.txt");
int k;
while((k=fis.read())!=-1)
fos.write(k);
fos.close();
fis.close();
}
}

DataInputStream:

DataInputStream is an input stream that contains methods for reading the Java
standard data types.
DataInputStream extends FilterInputStream, which extends InputStream,
and it implements the DataInput interface.

Constructor: DataInputStream(InputStream is)

Methods:

1. double readDouble() throws IOException


2. boolean readBoolean() throws IOException
3. int readInt() throws IOException

DataOutputStream:

DataOutputStream is an output stream that contains methods for writing the


Java standard data ypes.
DataOutputStream extends FilterOutputStream, which extends
OutputStream.

Constructor: DataOutputStream(OutputStream is)

Methods:

1. final void writeDouble(double value) throws IOException


2. final void writeBoolean(Boolean value) throws IOException
3. final void writeInt(int value) throws IOException

RAKESH.C.M Page 116


Example: Write a java program that reads a filename from the user and
display the information whether the file exists or not, whether the file is
readable, whether the file is writable, whether it is a file, and length of file in
bytes.

import java.io.*;
class Fileoperation
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter filename");
String str=dis.readLine();
File f=new File(str);
if(f.exists())
{
System.out.println("File exists");
if(f.canRead())
System.out.println("File is readable");
else
System.out.println("File is not readable");
if(f.canWrite())
System.out.println("File is writable");
else
System.out.println("File is not writable");
if(f.isFile())
System.out.println("Given string is a file");
else
System.out.println("Given string is not a file");
System.out.println("Length of file="+f.length()+" bytes");
}
else
System.out.println("File doesn't exists");
}
}

Example: Write a java program that reads a file and displays the file on the
screen with a line number before each line

import java.io.*;
class Addlineno
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
String str;
System.out.println("Enter a filename");
str=dis.readLine();
File f=new File(str);
FileInputStream fis=new FileInputStream(f);

RAKESH.C.M Page 117


char ch;
String st;
int count=0;
for(int i=0;i<f.length();i++)
{
st=" ";
do
{
ch=(char)fis.read();
st+=ch;
}while(ch!='\n');
++count;
System.out.println(count+" "+st);
}
}
}

Example: Write a java program that displays the no.of characters, lines and
words in a text file

import java.io.*;
class Count
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter a file name");
String str=dis.readLine();
FileInputStream fis=new FileInputStream(str);
int k,nc=0,nw=1,nl=1;
while((k=fis.read())!=-1)
{
char ch=(char)k;
if(ch==' '||ch=='\t'||ch=='\n')
nw++;
if(ch=='\n')
nl++;
nc++;
}
System.out.println("No.of characters="+nc);
System.out.println("No.of words="+nw);
System.out.println("No.of lines="+nl);
fis.close();
}
}

RAKESH.C.M Page 118


Buffer

Character Streams: Character Stream classes are used for processing the data in the
form of characters. This class defines two important abstract classes called Reader
and Writer.

Reader: It is an abstract class that defines Java’s model of streaming character input.
The system is reading the data in the form of characters from the physical device
using Reader. The methods that are provided by the Reader class are:

a) void close( ): Closes the input source. Further read attempts will generate
an IOException

b) int read( ): Returns an integer representation of the next available


character for the invoking stream. –1 is returned when the end of file is
encountered.

c) int read(char buf[]) : Attempts to read up to buf.length characters into


buffer and returns the actual number of characters that were successfully
read. –1 is returned when the end of file is encountered.

d) int read(char buf[], int off, int num): Attempts to read up to num
characters into buffer starting at buffer[off], returning the number of
characters successfully read. –1 is returned when the end of file is
encountered.

e) long skip(long numchars): Skips over numchars characters of input,


returning the number of characters actually skipped.

Writer: It is an abstract class that defines Java’s model of streaming character output.
The system is sending the data in the form of characters to the physical device using
Writer. The methods that are provided by the Writer class are:

a) void close( ): Closes the output stream. Further write attempts will
generate an IOException.

b) void write(int ch): Writes a single character to the invoking output


stream.

c) void write(char buf[ ]): Writes a complete array of characters

***

RAKESH.C.M Page 119


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-V: Exception handling and multithreading: Concepts of exception handling,


benefits of exception handling, Termination or resumptive models, exception hierarchy, usage
of try, catch, throw, throws and finally, java built in exceptions, creating own exception sub
classes. Differences between multi threading and multitasking, thread life cycle, creating
threads, synchronizing threads.

EXCEPTION HANDLING

Exception: An exception is an abnormal event that rises during the execution of a


program and disturbs the normal flow of instructions i.e., exception is a run-time
error.
Consider the following example:

class hello
{
public static void main(String[] args)
{
int a=10,b;
b=a/0;
System.out.println("value="+b);
}
}

When we try to compile this program, it does not produce any errors. But
when it runs the program it produces a message as “java.lang.ArithmeticException: /
by zero”. This exception error message is displayed and the program terminates
without executing the remaining statements.

Exception Handling: Exception Handling is designed for error processing. It


enables a program to catch all types of exceptions of certain type or related type.
Exception handling is designed for dealing with Synchronous errors such as an
attempt to divide by zero, out of bounds exception etc., It is not designed to deal with
Asynchronous errors such as mouse checks, key strokes etc.,

Exception Handling is used in situation arises the system can recover from
causing the exception. The procedure is called Exception Handling and done by the
Exception Handler.

All exception types are subclasses of built-in class Throwable. It is a super


class. The class is available in java.lang package. It contains errors and exceptions.

RAKESH.C.M Page 120


Throwable (super class)

Errors Exceptions
(Asynchronous) (Synchronous)

Run-time Exceptions IO Exceptions

Java defines several exception classes inside the java.lang package. These are
all subclass of Run-time Exceptions. The following are the some of the examples of
exceptions and these are unchecked exceptions because the compiler does not check
to see if a method handles or throws these exceptions.

Exception Meaning

ArithmeticException Arithmetic error, such as divide-by-zero


ArrayIndexOutOfBoundsException Array index is out-of-bounds
IllegalArgumentException Illegal argument used to invoke a method
IllegalThreadStateException Requested operation not compatible with
current thread state
IndexOutOfBoundsException Some type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric
format
StringIndexOutOfBounds Attempt to index outside the bounds of a
string

java.lang package contains some another type of exceptions that does not
handle itself. Here, the compiler checks that what is to be done when this arise,
because of this checking that they are called checked exceptions. Examples for
checked exceptions are

Exception Meaning

ClassNotFoundException Class not found


IllegalAccessException Access to a class is denied
InterruptedException One thread has been interrupted by another
thread
NoSuchMethodException A requested method does not exist

RAKESH.C.M Page 121


Exception-Handling Fundamentals

Java exception handling is managed through five keywords. They are 1) try
2)catch 3) throw 4) throws 5) finally. The general format of an exception-handling
block is as:

Syntax: try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exob)
{
// exception handler for exception type1
}
catch (ExceptionType2 exob)
{
// exception handler for exception type2
}
.
.
finally
{
// block of code to be executed before of try block ends
}

Here, ExceptionType is the type of exception that has occurred and exob is the
exception object.

try block: The statements that are produces exception are identified in the program
and the statements are placed with in a try block

Syntax: try
{
// block of code to monitor for errors
}

If an exception occurs within the try block, the appropriate exception handler
(catch block) associated with the try block handles the exception immediately.

catch block: The catch block is used to process the exception raised. The catch
block is placed immediately after the try block.

Syntax: catch (ExceptionType exob)


{
// exception handler for exception type
}

RAKESH.C.M Page 122


finally block: This block is placed after the last catch block. This block is executed
regardless of whether or not an exception is raised.

Syntax: finally
{
// block of code to be executed before of try block ends
}

1. The control enters into the try block and executes the statements. If an
exception is raised, the exception throws and it caught by exception handler catch
block. And the particular catch block statements are executed. The control never
backs again to the try block. If no exceptions raised, catch blocks are not executed the
control directly passed to the finally block.
2. No statements are placed between try block and catch block.

Example 1:

class ex11
{
public static void main(String[] args)
{
try
{
int a=10,b;
b=a/0;
System.out.println("b="+b);
}
catch(ArithmeticException e)
{
System.out.println("Exception raised");
}
System.out.println("Quit");
}
}

O/P: Exception raised


Quit

Example 2:

class ex12
{
public static void main(String[] args)
{
int x[]=new int[10];
try
{
x[20]=100;
}

RAKESH.C.M Page 123


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception caught");
}
finally
{
System.out.println("Not possible to print");
System.out.println("Quit");
}
}
}

Methods of Exception Object

a) String getMessage( ): It returns the descriptive string stored in an exception.

Example: / by zero

b) String toString( ): It returns an error message with the class name of the exception
the descriptive string to be stored in the exception.

Example: java.lang.ArithmeticException: / by zero

package

class

string

c) void printStackTrace( ): This is the standard output error stream. It displays the
error message with the class name of the exception the descriptive string to be stored
in the exception along with the line number and name of the program.

Example: java.lang.ArrayIndexOutOfBoundsException
at ex12.main (ex12.java:8)

class name file name

method name line number

Example 1:

class ex12
{
public static void main(String[] args)
{
int x[]=new int[10];

RAKESH.C.M Page 124


try
{
x[20]=100;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
}

Example 2:

class ex12
{
public static void main(String[] args)
{
String s=new String("Java programming language");
try
{
System.out.println(s.substring(45));
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
}

Example 3:

import java.text.DecimalFormat;
class n
{
public static void main(String[] args)
{
try
{
double x=25.6776;
DecimalFormat d=null;
System.out.println(d.format(x));
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
System.out.println(e.toString());

RAKESH.C.M Page 125


e.printStackTrace();
}
}
}

Multiple Catch Statements

Multiple catch clauses handle the situation where more than one exception
could be raised by a single piece of code. In such situations specify two or more catch
blocks, each specify different type of exception. Multiple catch statements are
arranged in respective order of exceptions that araised by the try block (optional).

Example:

class cat
{
public static void main(String[] args)
{
try
{
int a=args.length;
System.out.println("a="+a);
int b=42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
}

Note: A subclass must come before their super classes in a series of catch statements.
Exception class is the super class of all exceptions.

Example:

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

RAKESH.C.M Page 126


try
{
int a=0;
int b=42/a;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Nested try Statements

A try block is placed inside the block of another try block is termed as Nested
try block statements. If any error statement is in outer try block it goes to the
corresponding outer catch block. If any error statement is in inner try block first go to
the inner catch block. If it is not the corresponding exception next goes to the outer
catch, which is also not corresponding exception then terminated.

Example:

class ntry
{
public static void main(String[] args)
{
try
{
int a=args.length;
int b=42/a;
System.out.println("a="+a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
int c[]={1};
c[42]=99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Exception:"+e);
}
}

RAKESH.C.M Page 127


catch(ArithmeticException e)
{
System.out.println("Arithemetic exception:"+e);
}
}
}

Example:

class ntry1
{
public static void main(String[] args)
{
try
{
int a=args.length;
int b=42/a;
System.out.println("b="+b);
}
catch(ArithmeticException e)
{
System.out.println("Arithemetic exception:"+e);
}
finally
{
System.out.println("final block");
}
System.out.println("after try block");
}
}

throw statement

All previous exceptions are catching that are thrown by the java run time
system. It is also possible to create for a program that throws an exception explicitly,
using the “throw” statement. The general format of throw statement is:

Syntax: throw throwable-instance;

Here,
throwable-instance must be an object type of Throwable class or subclass of
Throwable. There are two ways to obtain a Throwable object.

1. Using a parameter into a catch clause


2. Creating one with the new operator

RAKESH.C.M Page 128


Example:
class ntry2
{
public static void main(String[] args)
{
try
{
throw new ArithmeticException("hello");
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
O/P: hello

Example:
class t
{
public t()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("caught");
throw e; //rethrow the exception
}
}
}
class ntry2
{
public static void main(String[] args)
{
try
{
t obj=new t();
}
catch(NullPointerException e)
{
System.out.println("Recaught");
}
}
}
O/P: caught
Recaught
RAKESH.C.M Page 129
throws statement

If a method is capable of causing an exception that it doesn’t handle, it must


specify the behavior to the callers of the method can guard themselves against that
exception. This can be done by throws statement in the method declaration.
A throws statement lists the types of exceptions that a method might throw.
This is necessary for all exceptions except that those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a method
can throw must be declared in the throws statement. Otherwise, it reports compile
time error. The general format of throws statement is as:

Syntax: type method-name(parameter-list) throws exception-list


{
// method body
}

Here, exception-list is a comma-separated list of the exceptions that a method can


throw.

Example:

class t
{
public t()throws NullPointerException
{
System.out.println("caught");
throw new NullPointerException("demo");
}
}
class ntry3
{
public static void main(String[] args)
{
try
{
t obj=new t();
}
catch(NullPointerException e)
{
System.out.println("Recaught");
}
}
}

O/P: caught
Recaught

RAKESH.C.M Page 130


User-defined Exceptions

It is also possible to create our own exceptions types to handle situations


specific to our application. Such exceptions are called User-defined Exceptions.
User-defined exceptions are created by extending Exception class. The throw and
throws keywords are used while implementing user-defined exceptions.

Example:

class own extends Exception


{
own(String msg)
{
super(msg);
}
}

class Test1
{
public static void main(String[] args)
{
try
{
int mark=Integer.parseInt(args[0]);
if(mark>100)
{
throw new own("Greater than 100");
}
catch(own e)
{
System.out.println("Exception caught");
System.out.println(e.getMessage());
}
finally
{
System.out.println("completed");
}
}
}

O/P: Exception caught


Greater than 100
completed

RAKESH.C.M Page 131


Example: Write a java program that implements STACK ADT

import java.util.*;
class StackEmptyException extends Exception
{
public StackEmptyException()
{
super();
}
public StackEmptyException(String s)
{
super(s);
}
}
class StackFullException extends Exception
{
public StackFullException()
{
super();
}
public StackFullException(String s)
{
super(s);
}
}
interface Stack1
{
public boolean isEmpty();
public int size();
public Object peek()throws StackEmptyException;
public Object pop()throws StackEmptyException;
public void push(Object x)throws StackFullException;
public String toString();
}
class ArrayStack implements Stack1
{
protected Object stk[];
protected int top;
public ArrayStack()
{
top=-1;
stk=new Object[10];
}
public ArrayStack(int cap)
{
if(cap<1)
throw new IllegalArgumentException("Initial capacity must be >1");
top=-1;
stk=new Object[cap];
}

RAKESH.C.M Page 132


public boolean isEmpty()
{
return top==-1;
}

public int size()


{
return top+1;
}

public Object peek()throws StackEmptyException


{
if(isEmpty())
throw new StackEmptyException("Stack underflow");
else
return stk[top];
}

public Object pop()throws StackEmptyException


{
if(isEmpty())
throw new StackEmptyException("Stack underflow");
Object rele=stk[top];
--top;
return rele;
}

public void push(Object x)throws StackFullException


{
if(top==stk.length-1)
throw new StackFullException("Stack overflow");
stk[++top]=x;
}

public String toString()


{
StringBuffer sb=new StringBuffer();
for(int i=top;i>=0;i--)
sb.append(stk[i]+"\n");
return new String(sb);
}
}

class MArraystack
{
public static void main(String args[])
{
ArrayStack a=new ArrayStack();
Scanner s=new Scanner(System.in);
int ch,k,m;

RAKESH.C.M Page 133


while(true)
{
System.out.println("\nStack Operation");
System.out.println("------------------------------");
System.out.println("1.isEmpty");
System.out.println("2.Size");
System.out.println("3.Peek");
System.out.println("4.Push");
System.out.println("5.Pop");
System.out.println("6.Display");
System.out.println("7.Exit");
System.out.println("Enter your choice(1-7):");
ch=s.nextInt();

switch(ch)
{
case 1: if(a.isEmpty())
System.out.println("Stack empty");
else
System.out.println("Stack is not empty");
break;

case 2: System.out.println("Stack size:"+a.size());


break;

case 3: try
{
System.out.println("The top element in stack is"+a.peek());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
break;

case 4: System.out.println("Enter the element");


k=s.nextInt();
try
{
a.push(k);
}

catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Stack elements:"+a);
break;

RAKESH.C.M Page 134


case 5: try
{
System.out.println("The popped element is"+a.pop());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
break;

case 6: System.out.println("The elements of stack are");


System.out.println(a);
break;

case 7: System.exit(0);
}
}
}
}

Example: Write a program to convert infix expression to postfix expression

import java.util.*;
import java.io.*;
class StackEmptyException extends Exception
{
public StackEmptyException()
{
super();
}
public StackEmptyException(String s)
{
super(s);
}
}

class StackFullException extends Exception


{
public StackFullException()
{
super();
}
public StackFullException(String s)
{
super(s);
}
}

RAKESH.C.M Page 135


interface Stack1
{
public boolean isEmpty();
public Object pop()throws StackEmptyException;
public void push(Object x)throws StackFullException;
}

class ArrayStack implements Stack1


{
protected Object stk[];
protected int top;
public ArrayStack()
{
top=-1;
stk=new Object[10];
}

public ArrayStack(int cap)


{
if(cap<1)
throw new IllegalArgumentException("Initial capacity must be >1");
top=-1;
stk=new Object[cap];
}

public boolean isEmpty()


{
return top==-1;
}

public Object pop()throws StackEmptyException


{
if(isEmpty())
throw new StackEmptyException("Stack underflow");
Object rele=stk[top];
--top;
return rele;
}

public void push(Object x)throws StackFullException


{
if(top==stk.length-1)
throw new StackFullException("Stack overflow");
stk[++top]=x;
}
}

RAKESH.C.M Page 136


class Intopost
{
public void conversion(String in)throws StackEmptyException,StackFullException
{
StringBuffer sb=new StringBuffer(in);
sb.append(")");
StringTokenizer st=new StringTokenizer(new String(sb));
ArrayStack a=new ArrayStack(in.length());
a.push("(");
StringBuffer post=new StringBuffer();
String str,s1;
int m,n;
char c;
while(!a.isEmpty())
{
str=st.nextToken();
c=str.charAt(0);
switch(c)
{
case '(': a.push("(");
break;
case '+':
case '-':
case '*':
case '/': s1=(String)a.pop();
m=rank(s1);
n=rank(str);
while(m>=n)
{
post.append(s1+' ');
s1=(String)a.pop();
m=rank(s1);
}
a.push(s1);
a.push(str);
break;
case ')': s1=(String)a.pop();
while(!s1.equals("("))
{
post.append(s1+' ');
s1=(String)a.pop();
}
break;
default: post.append(str+' ');
break;
}
}
System.out.println("The Postfix expression is"+ post);
}

RAKESH.C.M Page 137


public int rank(String s)
{
int r=0;
switch(s.charAt(0))
{
case ')':
case'(' : r=1;
break;
case '+':
case '-': r=2;
break;
case '*':
case '/': r=3;
break;
}
return r;
}
}

class Infix
{
public static void main(String[] args) throws IOException
{
Intopost i=new Intopost();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter an infix expression");
String s=dis.readLine();
try
{
i.conversion(s);
}
catch(StackEmptyException e)
{
System.out.println(e);
}
catch(StackFullException e)
{
System.out.println(e);
}
}
}

RAKESH.C.M Page 138


Example: Write a java program that evaluates the postfix expression

import java.io.*;
import java.util.*;

class StackEmptyException extends Exception


{
public StackEmptyException()
{
super();
}
public StackEmptyException(String s)
{
super(s);
}
}
class StackFullException extends Exception
{
public StackFullException()
{
super();
}
public StackFullException(String s)
{
super(s);
}
}
interface Stack1
{
public boolean isEmpty();
public Object pop()throws StackEmptyException;
public void push(Object x)throws StackFullException;
}

class ArrayStack implements Stack1


{
protected Object stk[];
protected int top;
public ArrayStack()
{
top=-1;
stk=new Object[10];
}
public ArrayStack(int cap)
{
if(cap<1)
throw new IllegalArgumentException("Initial capacity must be >1");
top=-1;
stk=new Object[cap];
}

RAKESH.C.M Page 139


public boolean isEmpty()
{
return top==-1;
}
public Object pop()throws StackEmptyException
{
if(isEmpty())
throw new StackEmptyException("Stack underflow");
Object rele=stk[top];
--top;
return rele;
}
public void push(Object x)throws StackFullException
{
if(top==stk.length-1)
throw new StackFullException("Stack overflow");
stk[++top]=x;
}
}

class PostEval
{
public void eval(String in)throws StackEmptyException,StackFullException
{
StringBuffer sb=new StringBuffer(new String(in));
sb.append(")");
StringTokenizer st=new StringTokenizer(new String(sb));
ArrayStack a=new ArrayStack(in.length());
String str;
int x,y,z=0;
char c;
while(!(str=st.nextToken()).equals(")"))
{
c=str.charAt(0);
if((c=='+')||(c=='-')||(c=='*')||(c=='/'))
{
x=(Integer)a.pop();
y=(Integer)a.pop();
switch(c)
{
case '+': z=y+x; break;
case '-' : z=y-x; break;
case '*': z=y*x; break;
case '/' : z=y/x; break;
}
a.push(z);
}
else
a.push(Integer.parseInt(str));
}

RAKESH.C.M Page 140


System.out.println("Value="+a.pop());
}
}

class Postfix
{
public static void main(String[] args)
{
PostEval p=new PostEval();
Scanner s=new Scanner(System.in);
System.out.println("Enter the postfix expression");
String str=s.nextLine();
try
{
p.eval(str);
}
catch(StackEmptyException e)
{
System.out.println(e);
}
catch(StackFullException e)
{
System.out.println(e);
}
}
}

RAKESH.C.M Page 141


MULTITHREADED PROGRAMMING

A Multithreaded program contains two or more parts that can run


concurrently. Each part of such program is called a thread, and each thread defines a
specific path of execution. Multithreading is a specialized form of Multitasking.

Multitasking: All modern operating systems support the concept of multitasking.


Multitasking is the feature that allows the computer to run two or more programs
concurrently. CPU scheduling deals with the problem of deciding for which of the
process, the ready queue is to be allocated. It follows CPU (Processor) scheduling
algorithms.

a) Priority Scheduling:

Process Burst time Priority

P1 10 2
P2 01 4
P3 02 2
P4 01 1
P5 05 3

P2 P5 P1 P3 P4

0 1 6 16 18 19

The priority scheduling follows on Sun Solaris systems. But it doesn’t work
on the present operating systems like windows NT etc., The thread with a piece of
system code is called the thread scheduler. It determines which thread is running
actually in the CPU.
The Solaris java platform runs a thread of given priority to completion or until
a higher priority thread becomes ready at that point preemption occurs.

b) Round-Robin Scheduling:

Process Burst time

P1 24
P2 10
P3 03
Time Quantum (or) Time Sliced : 04

P1 P2 P3 P1 P2 P1 P2 P1 P1 P1

0 4 8 11 15 19 23 25 29 33 37

RAKESH.C.M Page 142


Round Robin scheduling is available on Windows 95 and Windows NT is time
sliced.
Java supports thread implementation depending on round robin scheduling.
Here, each thread is given a limited amount of time called time quantum. While
executing the process when that time quantum expires the thread is made to wait state
and all threads that are equal priority get their chances to use their quantum in round
robin fashion.

Difference between Multiprocessing and Multithreading

Multiprocessing Multithreading

1. More than one process running simultaneously 1. More than one thread running
simultaneously
2. Its part of a program 2. Its part of a program
3. It’s a heavy wait process 3. It’s a light wait process
4. Process is divided into threads 4. Threads are divided into
sub threads
5. There is no communications between 5. Within the process threads are
processors directly communicated

Note: 1. Java provides built-in support for multithreaded programming


2. Java multithreading is a platform independent
3. Elimination of main loop/polling is the main benefit of multithreaded
programming.

Thread States (or) Lift-Cycle of a Thread


The life cycle of a thread contains several states. At any time the thread is
falls into any one of the states.

RAKESH.C.M Page 143


 The thread that was just created is in the born state.
 The thread remains in this state until the threads start method is called. This
causes the thread to enter the ready state.
 The highest priority ready thread enter the running state when the system
assigns a processor to the thread i.e., the thread begins executing.
 When a running thread calls wait the thread enters into a waiting state for the
particular object on which wait was called. Every thread in the waiting state
for a given object becomes ready on a call to notify all by another thread
associated with that object.
 When a sleep method is called in a running thread, that thread enters into the
suspended (sleep) state. A sleeping thread becomes ready after the
designated sleep time expires. A sleeping thread cannot use a processor even
if one is available.
 A thread enters the dead state when its run( ) method complete (or) terminates
for any reason. A dead thread is eventually be disposed of by the system.
 One common way for a running thread to enter the blocked state is when the
thread issues an input or output request. In this case a blocked thread becomes
ready when the input or output waits for completes. A blocked thread can’t
use a processor even if one is available.

Thread class constructors

1. Thread( )
2. Thread(String Threadname)
3. Thread(Runnable obj)
4. Thread(Runnable obj, String name)
5. Thread(ThreadGroup tg, String Threadname)

Methods

1. String getName( ): It obtains the name of the thread.


2. void setName(String str): It sets the name of the thread.
3. int getPriority( ): It obtains the priority of the thread.
4. void setPriority(int): It sets the priority of the thread.
5. boolean isAlive( ): Determines if a thread is still running or not. It returns true if
the thread upon which it is called is still running. Otherwise, it returns false.
6. void sleep(long milliseconds): Suspend a thread for a period of time.
7. void start( ): Start a thread by calling its run method.
8. void run( ): It defines the code that constitutes the new thread. When ever the
start( ) method executes it automatically call of run( ) method.
9. void join( ): This method waits until the thread on which it is called terminates.
10. Thread currentThread( ): It returns a reference to the currently executing thread.
11. void yield( ): A thread can call the yield method to give other threads a chance to
execute.
12. ThreadGroup getThreadGroup( ): It returns the name of the thread group
which contain currently running thread. ThreadGroup represents set of Threads. It
has one constructor method as ThreadGroup(String name).

RAKESH.C.M Page 144


Main Thread:

When a java program starts up, one thread begins running immediately. This
one is main thread, which is created by virtual machine. It is executed in the program
for the first time. It must be the last thread to finish execution. When the main
thread stops the program terminates.
Even though the main thread is automatically created when the program starts,
it can be controlled through Thread object. For this we obtain a reference to by
calling the method “currentThread( )”.

Example:

class demo
{
public static void main(String[] args)
{
Thread obj=Thread.currentThread();
System.out.println("current="+obj);
obj.setName("india");
System.out.println("after="+obj);
}
}

O/P: current=Thread[main,5,main]
after=Thread[india,5,main]

Example:

class demo
{
public static void main(String[] args)
{
Thread obj=Thread.currentThread();
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
obj.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("exception");
}
}
}

RAKESH.C.M Page 145


Creating a new Thread

A new thread can be created in two ways


1. implements the Runnable interface
2. extends the Thread class itself
1. implements the Runnable interface: Runnable is a system defined interface.
Once we create a class, it implements the Runnable interface forms a thread class. To
implement Runnable, a class need only implement a single method called run( ).

Example:
class new1 implements Runnable
{
Thread t;
public new1()
{
t=new Thread(this,"child thread");
System.out.println("sub thread="+t);
t.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("child="+n);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("child exception");
}
System.out.println("child exit");
}
}
class demo1
{
public static void main(String[] args)
{
new new1();
try
{
for(int n=5;n>0;n--)
{
System.out.println("main="+n);
Thread.sleep(1000);
}
}

RAKESH.C.M Page 146


catch(InterruptedException e)
{
System.out.println("main exception");
}
System.out.println("main exit");
}
}

2. extending the Thread class: The second way to create a thread is to create a new
class that extends Thread, and then create an instance of that class. The extending
class must override the run( ) method. It must also call start( ) to begin execution of
the new thread.

Example:

class newthread extends Thread


{
public newthread()
{
super("child thread");
System.out.println("sub thread="+this);
start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("child="+n);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("child exception");
}
System.out.println("child exit");
}
}
class demo2
{
public static void main(String[] args)
{
new newthread();
try
{

RAKESH.C.M Page 147


for(int n=5;n>0;n--)
{
System.out.println("main="+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("main exception");
}
System.out.println("main exit");
}
}

Example:

class a extends Thread


{
public void run()
{
for(int n=0;n<5;n++)
{
if(n==3)
yield();
System.out.println("child 1="+n);
}
}
}
class b extends Thread
{
public void run()
{
for(int n=0;n<5;n++)
{
try
{
sleep(1000);
}
catch(Exception e)
{
}
System.out.println("child 2="+n);
}
}
}

class c extends Thread


{
public void run()
{

RAKESH.C.M Page 148


for(int n=0;n<5;n++)
{
if(n==2)
stop();
System.out.println("child 3="+n);
}
}
}

class demo3
{
public static void main(String[] args)
{
a obj=new a();
b obj1=new b();
c obj2=new c();
obj.start();
obj1.start();
obj2.start();
}
}

Example:

class b implements Runnable


{
Thread t;
b(String tname)
{
t=new Thread(this,tname);
t.start();
}
public void run()
{
try
{
for(int n=0;n<5;n++)
{
System.out.println("child 1="+n);
//sleep(1000); can't work in the case implementing interface
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("child exception");
}
}
}

RAKESH.C.M Page 149


class demo4
{
public static void main(String[] args)
{
b obj1=new b("one");
b obj2=new b("two");
System.out.println("b is alive:"+obj1.t.isAlive());
System.out.println("c is alive:"+obj2.t.isAlive());
try
{
obj1.t.join();
obj2.t.join();
}
catch(InterruptedException e)
{
System.out.println("child exception");
}
System.out.println("b is alive:"+obj1.t.isAlive());
System.out.println("c is alive:"+obj2.t.isAlive());
}
}

Example: Write a java program that creates three threads. First thread
displays"Good Morning" every one second , the second thread displays "Hello:
every two seconds and the third thread displays "Welcome" every three seconds.

import java.lang.*;
class Mythread1 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(1000);
System.out.println("Good Morning");
}
catch(Exception e){}
}
}
}
class Mythread2 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{

RAKESH.C.M Page 150


Thread.sleep(2000);
System.out.println("Hello");
}
catch(Exception e){}
}
}
}
class Mythread3 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(3000);
System.out.println("Welcome");
}
catch(Exception e){}
}
}
}
class Threaddemo
{
public static void main(String args[])
{
Mythread1 m1=new Mythread1();
Mythread2 m2=new Mythread2();
Mythread3 m3=new Mythread3();
m1.start();
m2.start();
m3.start();
}
}

Thread Priorities

Every thread in Java is assigned a priority value, when more than one thread is
computing for CPU time. Generally highest priority thread is running before the
lowest priority thread. It is also possible to set priority to each thread by the user
using setPriority( ) method. System defined thread priorities are

Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread.NORM_PRIORITY 5

The default priority is Thread.NORM_PRIORITY

RAKESH.C.M Page 151


Example:

class Demo extends Thread


{
public void run()
{
for(int i=1;i<=3;i++)
System.out.println(getName()+" "+i);
}
}
class ThprDemo
{
public static void main(String[] args)
{
Demo obj=new Demo();
Demo obj1=new Demo();
Demo obj2=new Demo();
obj.setPriority(Thread.MAX_PRIORITY);
obj1.setPriority(Thread.MIN_PRIORITY);
obj2.setPriority(Thread.NORM_PRIORITY);
obj.start();
obj1.start();
obj2.start();
}
}

O/P: Thread-1 1
Thread-1 2
Thread-1 3
Thread-3 1
Thread-3 2
Thread-3 3
Thread-2 1
Thread-2 2
Thread-2 3

Synchronization

When two or more threads need access to a shared resource, they need
someway to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called Synchronization. Java uses the concept of
monitor (also called Semaphore) for Synchronization.
A monitor is an object that is used as a mutually exclusive lock, or mutex.
The monitor allows one thread at a time to execute a Synchronized method on the
object.

RAKESH.C.M Page 152


Example: Write a java program that correctly implements procuder
consumer problem using the concept of inter thread communication

class Q
{
int n;
boolean valueset=false;
synchronized void get()
{
while(!valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("got"+n);
valueset=false;
notify();
}
synchronized void put(int n)
{
while(valueset)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
this.n=n;
valueset=true;
System.out.println("put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;

RAKESH.C.M Page 153


while(true)
{
q.put(i++);
}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}

class ITC
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("press ^- to exit");
}
}

***

RAKESH.C.M Page 154


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-VI: Event Handling: 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 – layout manager types – boarder, grid, flow, card
and grid bag.

EVENT HANDLING

Events

An event is an object that describes a state change in a source. Even driven is


a consequence interaction of the user with the GUI. Some of the common interactions
are moving the mouse, clicking the mouse, clicking a button, typing in a textfield etc.,

Event Sources

A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one type
of event.

Delegation Event Model

In java1.0 the action() method is used to perform any actions that are provided
with the controls. But the action() method is now deprecated. The new technique in
java1.1 and java2 is the Event Delegation Model.
This method defines a consistent mechanism to generate and process the
events. The process is: a source generates an event and sends it to one or more
listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns.

Event Listeners

A listener is an object that is notified when an event occurs. It has two


requirements.
1. It must have been registered with one or more sources to receive
notifications about the specific type of events.
2. It must implement methods to receive and process the notifications
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event package.

RAKESH.C.M Page 155


Commonly used Event Listener Interfaces are

ActionListener, AdjustmentListener, ComponentListener, ContainerListener,


FocusListener, ItemListener, KeyListener, MouseListener, MouseMotionListener,
MouseWheelListener, TextListener, WindowFocusListener, WindowListener.

Event Classes

Event classes are used to handle Java event handling mechanism. At the root
of the java event class hierarchy is EventObject , which is in java.util package. It is
the superclass for all events. It provides a constructor as:

EventObject(Object x)

Methods provided by the class are:

1. Object getSource(): returns the source of the event


2. Stirng toString() : returns the string equivalent of the event

The class AWTEvent, defined with in the java.awt package, is subclass of


EventObject. It is the superclass of all AWT-based events used by the delegation
model.

Commonly used Event classes are:

ActionEvent, AdjustmentEvent, ComponentEvent, ContainerEvent, FocusEvent,


InputEvent, ItemEvent, KeyEvent, MouseEvent, MouseWheelEvent, TextEvent,
WindowEvent.

MouseEvent Class:

The MouseEvent class defines eight types of mouse events. It defines the
following integer constants that can be used to identify them:

MOUSE_CLICKED : The user clicked the mouse


MOUSE_DRAGGED : The user dragged the mouse
MOUSE_ENTERED : The mouse entered a component
MOUSE_EXITED : The mouse exited from a component
MOUSE_MOVED : The mouse moved
MOUSE_PRESSED : The mouse was pressed
MOUSE_RELEASED: The mouse was released
MOUSE_WHEEL : The mouse wheel was moved

RAKESH.C.M Page 156


MouseEvent is a subclass of InputEvent

Hierarchy: java.lang.Object

java.util.EventObject

java.awt.AWTEvent

java.awt.event.ComponetEvent

java.awt.event.InputEvent

java.awt.event.MouseEvent

Methods:

1. int getX(): returns the X coordinate of the mouse when an event occurred
2. int getY():returns the Y coordinate of the mouse when an event occurred
3. Point getPoint(): returns the coordinates of the mouse

MouseListener Interface: This interface defines five methods.

1. void mouseClicket(MouseEvent me): it invokes if the mouse is pressed


and released at the same point
2. void mouseEntered(MouseEvent me): it invokes when the mouse enters
a component
3. void mouseExited(MouseEvent me): it invokes when the mouse leaves
the component
4. void mousePressed(MouseEvent me): it invokes when the mouse is
pressed
5. void mouseReleased(MouseEvent me): it invokes when the mouse is
released

MouseMotionListener Interface: This interface defines two methods

1. void mouseDragged(MouseEvent me): it invokes when multiple times


as the mouse is dragged
2. vid mouseMoves(MouseEvent me): it invokes when multiple times as
the mouse is moved

RAKESH.C.M Page 157


Handling MouseEvents:

// Example program to draw rectangles with mouse clicking

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/* <applet code="Lab15.class" width=400 height=350>


</Applet> */

public class Lab15 extends Applet implements MouseListener,MouseMotionListener

{
String msg=" ";
int x=0,y=0,w=0,h=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
x=me.getX();
y=me.getY();
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
public void mouseExited(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
public void mouseReleased(MouseEvent me)
{
w=me.getX();

RAKESH.C.M Page 158


h=me.getY();
repaint();
}
public void mouseDragged(MouseEvent me)
{
w=me.getX();
h=me.getY();
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Mouse Operation");
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(x,y,w,h);
}
}

Example: Write a java program for handling mouse events

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="Nmouse" width=300 height=300>


</applet>*/

public class Nmouse extends Applet implements


MouseListener,MouseMotionListener
{
String msg=" ";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent e)
{
setForeground(Color.red);
msg="Mouse is entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
setForeground(Color.blue);
msg="Mouse is exited";
repaint();
}

RAKESH.C.M Page 159


public void mousePressed(MouseEvent e)
{
setForeground(Color.gray);
msg="Mouse is pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
setForeground(Color.yellow);
msg="Mouse is released";
repaint();
}
public void mouseDragged(MouseEvent e)
{
setForeground(Color.pink);
msg="Mouse is dragged";
repaint();
}
public void mouseMoved(MouseEvent e)
{
setForeground(Color.orange);
msg="Mouse is moved";
repaint();
}
public void mouseClicked(MouseEvent e)
{
setForeground(Color.red);
msg="Mouse is clicked";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

KeyEvent Class:

A KeyEvent is generated when keyboard input occurs. There are three types
of key events, which are identified by these integer constants:
KEY_PRESSED
KEY_RELEASED
KEY_TYPED
The first two events are generated when any key is pressed or released. The last event
occurs when a character is generated.

Methods:
1. char getKeyChar(): returns the character that was entered
2. int getKeyCode(): returns the character code

RAKESH.C.M Page 160


KeyListener Interface: The interface defines three methods.

1. void keyPressed(KeyEvent me): it invokes when a key is pressed


2. void keyReleased(KeyEvent me): it invokes when a key is released
3. void keyTyped(KeyEvent me): it invokes when a key is typed

Handling KeyEvents:

//Example program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Keydemo.class" width=400 height=350>
</Applet> */

public class Keydemo extends Applet implements KeyListener


{
String msg=" ";
int x=50,y=50;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent me)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent me)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent me)
{
showStatus("Key Typed");
msg=msg+me.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString(msg,x,y);
}
}

RAKESH.C.M Page 161


ADAPTER CLASSES
An adapter class provides an empty implementation of all methods in an event
listener interface. Adapter classes are useful when we want to receive and process
only some of the events that are handled by a particular event listener interface. For
this, we can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested.
Consider, the MouseMotionAdapter class has two methods,
mouseDragged() and mouseMoved(). If we are interested in only muse drag events,
then we extend mouseMotionAdapter and implement mouseDragged(). The empty
implementation of mouseMoved() would handle the mouse motion events.
Adapter classes are provided by java.awt.event package. Some of the
Adapter classes are
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

// Example program
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Adapterdemo.class" width=400 height=350>
</Applet> */

public class Adapterdemo extends Applet


{
public void init()
{
addMouseListener(new my(this));
addMouseMotionListener(new myadd(this));
}
}
class my extends MouseAdapter
{
Adapterdemo a;
public my(Adapterdemo p)
{
this.a=p;
}
public void mouseClicked(MouseEvent me)
{
a.showStatus("Mouse Clicked");
}
}

RAKESH.C.M Page 162


class myadd extends MouseMotionAdapter
{
Adapterdemo a;
public myadd(Adapterdemo p)
{
this.a=p;
}
public void mouseDragged(MouseEvent me)
{
a.showStatus("Mouse Dragged");
}
}

INNERCLASSES

The most important type of nested class is the inner class. An inner
class is a non-static nested class. It has access to all of the variables and
methods of its outer class and may refer to them directly in the same way that
other non-static members of the outer class.

// EXAMPLE PROGRAM FOR INNER CLASS

import java.applet.*;
import java.awt.event.*;

/* <applet code="Inner" width=200 height=100>


</applet>
*/

public class Inner extends Applet


{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent M)
{
showStatus("Mouse Pressed");
}
}
}

RAKESH.C.M Page 163


Anonymous Inner Classes:

An anonymous inner class is one that is not assigned a name.

// EXAMPLE PROGRAM FOR ANONYMOUS INNER CLASS

import java.applet.*;
import java.awt.event.*;

/* <applet code="AnInner" width=200 height=100>


</applet>
*/

public class AnInner extends Applet


{
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent M)
{
showStatus("Mouse Pressed");
}
}
);
}
}

RAKESH.C.M Page 164


AWT CLASSES

The Abstract Window Toolkit (AWT) contains several classes which are
placed in the java.awt package. It is one of Java’s largest packages. The following
table shows a list of classes.

Class Description

AWTEvent Encapsulates AWT Events.


AWTEventMultiCaster Dispatches events to multiple listeners
BorderLayout The border layout manager. Border layouts use five
components: North, South, East, West and Center
Button Creates a push button control
Canvas A blank, semantics-free window
CardLayout The card layout manager. Card layouts emulate index cards.
Only the one on top is showing
Checkbox Creates a check box control
CheckboxGroup Creates a group of checkbox controls
CheckboxMenuItem Creates an on/off menu item
Choice Creates a pop-up list
Color Mangaes colors in a portable, platform dependent

Window Fundamentals

The AWT defines windows according to a class hierarchy that adds


functionality and specificity with each lever. The most two common windows are:
Panel, which is used by applets
Frame, which creates a standard window.

The class hierarchy for Panel and Frame is as follows:

Component

Container

Window Panel

Frame

RAKESH.C.M Page 165


Component: Top of the AWT hierarchy is the Componet class. All user
interface elements that are displayed on the screen and that interact with the user are
subclasses of Component. It defines different methods for managing events, such as
mouse and keyboard input, positioning and sizing the window, and repainting.

Container: The Container is a subclass of Component. It has additional


mehods that allow other Component objects tobe nested within it.

Panel: The Panel class is a concrete subclass of Container. It doesn’t


add any new methods; it simply implements Container.
Panel is the superclass for Applet. When screen output is directed to an
applet, it is drawn on the surface of a Panel object. Thus, a Panel is a window that
does not contain a title bar, menu bar, or border.

Window: The Window class creates a top-leve window. Generally, we


won’t create Window objects. Instead, we use a subclass of Window called Frame.

Frame: Frame is a subclass of Window and has a title bar, menu bar,
borders, and resizing corners.

Frame

Frame class provides two constructors as:

Frame()
Frame(String title)

The first form creates a standard window that does not contain a title.
The second form creates a window with the title specified by title.

Setting Window’s Dimensions

The setSize() method is used to set the dimensions of the window.

Syntax: void setSize(int newWidth, int newHeight)


void setSize(Dimension newSize)

The getSize() method is used to obtain the current size of a window.

Syntax: Dimension getSize()

RAKESH.C.M Page 166


Hiding and Showing a Window

After a frame window has been created, it will not be visible until to call
setVisible().

Syntax: void setVisible(boolean visibleFlag)

The component is visible if the argument to this method is tue. Otherwise, it


is hidden.

Setting a Window’s Title

We can change the title in a frame window using setTitle() method.

Syntax: void setTitle(String newTitle)

Closing a Frame Window

When using a frame window, the program must remove that window from the
screen when it is closed, by calling setVisible(false).

// EXAMPLE PROGRAM WITH FRAME WINDOW

import java.awt.*;

class Dframe extends Frame


{
Dframe()
{
setTitle("Demo Program");
setSize(250,450);
setVisible(true);
}
}

public class Demo


{
public static void main(String args[])
{
Dframe obj=new Dframe();
}
}

RAKESH.C.M Page 167


Working with Graphics

The AWT supports all of graphic methods. All graphics are drawn
relative to a window.This can be the main window of an applet,a child window
of an applet,or a stand-alone application window.The origin of each window is
at the top-left corner and is 0,0. Cooridinates are specified in pixels.All output
to a window takes place through a graphics context.A graphics context is
encapsulated by the Graphics class and is obtained in two ways:

 It is passed to an applet when one of its various methods, such as


paint( ) or update( ) ,is called.
 It is returned by the getGraphics( ) method of component.

The Graphics class defined a number of drawing functions.Each shape can be


drawn edge-only or filled.Objects are drawn and filled in the currently selected
graphics color, which is black by default.

1. Drawing Lines:

Lines are drawn by using drawLine( ) method. The method is as:

void drawLine(int startX, int startY, int endX, int endY)

drawLine( ) displays a line in the current drawing color that begins at


startX,startY and ends at endX,endY.

// EXAMPLE PROGAM TO DRAW A LINE

import java.awt.*;
import java.applet.*;

/* <applet code="Lines" width=300 height=200>


</applet> */

public class Lines extends Applet


{
public void paint(Graphics g)
{
g.drawLine(40,25,250,180);
}
}

RAKESH.C.M Page 168


2. Drawing Rectangles:

The drawRect() and fillRect() methods are used to draw and fill rectangles.
The methods are as:

void drawRect(int top, int left, int width, int height)


void fillRect(int top, int left, int width, int height)

The upper-left cornor of the rectangle is at top,left.


The dimensions of the rectangle are specified by width and height.

The draw a rounded rectangle, use drawRoundRect() and fillRoundRect()


methods as:

void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)

A rounded rectangle has rounded corners.


The upper-left cornor of the rectangle is at top,left.
The dimensions of the rectangle are specified by width and height.
The diameter of the rounding are along X axis is specified by xDiam.
The diameter of the rounding are along Y axis is specified by yDiam.

// EXAMPLE PROGRAM FOR RECTANGLES

import java.awt.*;
import java.applet.*;

/* <applet code="Rectangle1" width=300 height=200>


</applet> */

public class Rectangle1 extends Applet


{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,10,60,50);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70,90,140,100,30,40);
}
}

3. Drawing Elllipses and Circles:

To draw an ellipse, use drawOval(). To fill and ellipse, use fillOval(). These
methods are:

void drawOval(int top, int left, int width, int height)


void fillOval(int top, int left, int width, int height)

RAKESH.C.M Page 169


The ellipse is drawn within a bunding rectangle whose upper-left corner is
specified by top, left and whose width and height are specified by width and height.

To draw a cirle, specify a square as the bounding rectangle.

// EXAMPLE PROGRAM TO DRAW ELLIPSE

import java.awt.*;
import java.applet.*;

/* <applet code="Ellipses" width=300 height=200>


</applet> */

public class Ellipses extends Applet


{
public void paint(Graphics g)
{
g.drawOval(10,10,50,50);
g.fillOval(100,10,75,50);
}
}

Example: Write a Java program that allows the user to draw lines,
rectangles and ovals.

import java.awt.*;
import java.applet.*;

/* <applet code="Lab12b" width=500 height=500>


</applet> */

public class Lab12b extends Applet


{
public void paint(Graphics g)
{
g.drawLine(300,0,300,300);
g.drawRect(10,10,60,50);
g.fillRect(100,10,60,50);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70,90,140,100,30,40);
g.drawOval(250,250,50,90);
g.fillOval(350,200,75,50);
}
}

RAKESH.C.M Page 170


4. Drawing Arcs:

Arcs can be drawn with drawArc() and fillArc() methods.

void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)

The arc is bounded by the rectangle whose upper-left corner is specified by


top, left and whose width and height are specified by width and height. The arc is
drawn from startAngle through the angual distance spsecified by sweepAngle.
Angles are specified in degrees.
Zero degress is on the horizontal, at the three 0’ clock position. The arc is
drawn counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is
negative.

// EXAMPLE PROGRAM FOR ARCS

import java.awt.*;
import java.applet.*;

/* <applet code="Arcs" width=300 height=200>


</applet> */

public class Arcs extends Applet


{
public void paint(Graphics g)
{
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,100,70,80,0,270);
}
}

5. Drawing Polygons:

Polygons are drawn and filled using drawPolygon() and fillPolygon()


methods.

void drawPolygon(int x[], int y[], int numPoints)


void fillPolygon(int x[], int y[], int numPoints)

The polygon’s endpoints are specified by thej coordinate pairs contained


within the x and y arrays.
The number of points defined by x and y are specified by numPoints.

// EXAMPLE PROGRM TO DRAW A POLYGON

import java.awt.*;
import java.applet.*;

RAKESH.C.M Page 171


/* <applet code="Poly" width=300 height=200>
</applet> */

public class Poly extends Applet


{
public void paint(Graphics g)
{
int x[]={30,200,30,200,30};
int y[]={30,30,200,200,30};
int num=5;
g.drawPolygon(x,y,num);
}
}

6. Working with Color:

Java supports color in a portable, device-independent fashion. The AWT


color system allows us to specify any color we want.
Color is encapsulated by the Color class. Constructors for the class are:

Color(int red, int green, int blue)


Color(int rgbValue)
Color(float red, float green, float blue)

The first constructor takes three integers that specify the color as a mix of red,
green, and blue.

Ex: Color x = new Color(255, 100, 100);

The second color constructor takes a single integer that contains a mix of red,
gree, and blue packed into the integer. The integer is organized with red in bits 16 to
23, green in bits 8 to 15, and blue in bits 0 to 7.

Ex: int newRed = (0xff000000 | (0xc0 << 16) | (0x00<<8) | 0x00);


Color x = new Color(newRed);

The third constructor takes three float values between 0.0 and 1.0 that specify
the relative mix of red, green, and blue.

Ex: Color x = new Color(0.8, 0.4, 0.9);

RAKESH.C.M Page 172


Methods:

a) getRed(), getGreen(), getBlue():

These methods are used to obtain the red, green, and blue components
of a color independently.
int getRed()
int getGreen()
int getBlue()

b) getRGB():

To obtain packed RGB, we use getRGB() method.

int getRGB()

c) Setting current Graphics Color:

The color of the Graphics can be set by using setColor() method.

void setColor(Color newColor)

// EXAMPLE PROGRAM FOR COLOR DEMONSTRATION

import java.awt.*;
import java.applet.*;
import java.awt.Color;

/* <applet code="Lab12b" width=500 height=500>


</applet> */

public class Lab12b extends Applet


{
public void paint(Graphics g)
{
Color c1=new Color(255,100,100);
Color c2=new Color(100,255,100);
g.fillRect(100,10,60,50);
g.setColor(Color.red);
g.drawRoundRect(190,10,60,50,15,15);
g.setColor(c1);
g.fillRoundRect(70,90,140,100,30,40);
g.setColor(c2);
g.drawOval(250,250,50,90);
g.fillOval(350,200,75,50);
}
}

RAKESH.C.M Page 173


7. Working with Fonts:

The AWT supports multiple type fonts. To select a new font, we construct a
Font object. It has a constructor as:

Font(String fontName, int fontStyle, int pointSize)

fontName specifies the name of the desired font.


fontStyle specifies the style of the font. It may consist of one or more of these
three constants: Font.PLAIN, Font.BOLD, and Font.ITALIC.
pointSize specifies the size of the font.

Methods:

Font class provides different methods. Some of the important methods are:

int getSize()
String getName()
int getStyle()
String getFamily()
boolean isBold()
boolean isItalic()
boolean isPlain() etc.,

// EXAMPLE PROGRAM FOR FONT STYLES

import java.awt.*;
import java.applet.*;
import java.awt.Color;

/* <applet code="Ft" width=500 height=500>


</applet> */

public class Ft extends Applet


{
public void paint(Graphics g)
{
Font f=g.getFont();
int f1=f.getSize();
int f2=f.getStyle();
g.drawString("SIZE:"+f1,20,20);
g.drawString("STYLE:"+f2,100,100);
}
}

RAKESH.C.M Page 174


AWT CONTROLS

Controls are components that allow a user to interact with our application in
various ways. A layout manager automatically positions components with in a
container. The appearance of window is determined by a combination of the controls
that it contains and the layout manger used to position them. The Layout managers
manage manual positions of placing the components.
The AWT supports the following types of controls:

Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text editing

Adding Controls: First created an instance of the desired control and then add it to a
window by calling add( ) method, which is defined by Container.

Syntax: Component add(Component obj)

obj is an instance of the control that we want to add. It returns the object of
the control. Once, the control is added, it will automatically be visible whenever its
parent window is displayed.

Removing Controls: We want to remove a control from a window when the control
is no longer needed, call the method remove( ). This method is also defined by
Container.

Syntax: void remove(Component obj)


obj is a reference to the control that we want to remove.

To remove all the controls from the window used the following syntax as

Syntax: void removeAll( )

Labels: Label is a text information that display on the GUI as a stirng. These are
passive controls that do not support any interaction with the user. Label defines the
following constructors:
Label( )
Label(String str)
Label(String str, int how)

The first form creates a blank label


The second form creates a label that contains the string specified by str. The
string is left-justified

RAKESH.C.M Page 175


The third version crates a label that contains the string specified by str using
the alignment specified by how. The value of how must be one of these three
constants: Label.LEFT, Label.RIGHT or Label.CENTER.

Methods:
1. void setText(String str): To change the text specified by the str
argument
2. String getText( ): It returns the text from the label
3. void setAlignment(int how): To set the position of the label specified
by the how constant
4. int getAlignment( ): It returns the alignment

// Example program to create two Labels

import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(250,450); One Two
setVisible(true);
setLayout(new FlowLayout());
Label L1=new Label("One");
Label L2=new Label("Two");
add(L1);
add(L2);
}
}
class Labeldemo
{
public static void main(String[] args)
{
Frame1 f=new Frame1();

}
}

Buttons: A push button is a component that contains a label and that generates an
event when it is pressed. Push buttons are objects of type Button. Button defines
these two constructors:
Button( )
Button(String str)

The first form creates an empty button


The second form creates a button that contains str as a label

RAKESH.C.M Page 176


Methods:

1. void setLabel(String str): To set a label on the push button


2. String getLabel( ): It returns the label of the push button as String

Handling Buttons:

ActionEvent Class: An ActionEvent is generated when a button is pressed, a list


item is double-clicked, or menu item is selected.

Hierachy: java.lang.Object

java.util.EventObject

java.awt.AWTEvent

java.awt.event.ActionEvent

Methods:

1. Object getSource(): It returns the object on which event initially


occurred
2. String getActionCommand(): It returns the command string associated
with this action

ActionListener Interface: Each time a button is pressed, an action event is


generated. This is sent to any listeners. Each listener implements the ActionListener
interface. That interface defines the actionPerformed() metho, which called when an
event occurs. An ActionEvent object is supplied as the argument to this method.

Method: void actionPerformed(ActionEvent obj)

Example: Develop an applet that receives an integer in one text field, and
computes its factorial value and returns it in another text field, when the button
named “Compute” is clicked.

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Lab6b" width=400 height=350> </Applet> */

public class Lab6b extends Applet implements ActionListener


{
TextField t1,t2;
Button b1;
Label L1,L2;

RAKESH.C.M Page 177


public void init()
{
L1=new Label("Enter the Number:");
add(L1);
t1=new TextField(15);
add(t1);
L2=new Label("Factorial Value:");
add(L2);
t2=new TextField(15);
add(t2);
b1=new Button("COMPUTE");
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{

if(e.getSource()==b1)
{
int x=Integer.parseInt(t1.getText());
int i,f=1;
for(i=1;i<=x;i++)
f=f*i;
t2.setText(" "+f);
}
repaint();
}
}

Example: Write a java program that creates a user interface to perform


integer divisions. The user enters two numbers in the text fields ,num1, and
num2. The division of num1, and num2 is displayed in the result field when the
divide button is clicked. If num1 and num2 were not integers, the program
would throw a NumberFormatException.If num2 was zero, the program would
throw an ArithmeticException.Display the exception in a message dialog box.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Divide" width=300 height=300>
</applet>*/
public class Divide extends Applet implements ActionListener,TextListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
int x,y,res=0;
Button b1;

RAKESH.C.M Page 178


public void init()
{
l1=new Label("num1");
l2=new Label("num2");
t1=new TextField(10);
t2=new TextField(10);
l3=new Label("Result");
t3=new TextField(10);
t3.setEditable(false);
b1=new Button("Divide");
b1.setEnabled(false);
b1.addActionListener(this);
t1.addTextListener(this);
t2.addTextListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
try
{
x=Integer.parseInt(t1.getText());
y=Integer.parseInt(t2.getText());
if(e.getSource()==b1)
res=x/y;
}
catch(NumberFormatException nfe)
{
System.out.println("Enter proper integer value");
}
catch(ArithmeticException ae)
{
System.out.println("Enter non zero denominator");
}
t3.setText(String.valueOf(res));
}
public void textValueChanged(TextEvent te)
{
if((!t1.getText().equals(" "))&&(!t2.getText().equals(" ")))
b1.setEnabled(true);
else
b1.setEnabled(false);
}
}

RAKESH.C.M Page 179


Check Boxes: A Check box is a control that is used to turn an option on or off. It
consists of a small box that can either contain mark or not. There is a label associated
with each check box that describes the option that box represents. We can change the
state of the check box by clicking it. Check boxes can be used individually or as a
part of a group. Check boxes are objects of the Checkbox class. Checkbox supports
these constructors:

Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cb)

The first form creates a check box with empty label and the state is unchecked
The second form creates a check box with the label str and the state is unchecked
The third form creates a check box with the label str and the state is checked () when
the boolean argument on is true
The fourth form creates a check box with the label str and the state is checked ()
when the boolean argument on is true whose group is specified by cb.

Methods:

1. boolean getState( ): Determines whether this check box is in the "on" or


"off" state.
2. void setState(boolean on): Sets the state of this check box to the
specified state
3. String getLabel( ): Gets the label of this check box
4. void setLabel( ): Sets this check box's label to be the string argument

// Example program to create different check boxes with individual group

import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
Checkbox c1=new Checkbox();
Checkbox c2=new Checkbox("DOS");
Checkbox c3=new Checkbox("Window",true);
add(c1);
add(c2);
add(c3);
}
}

RAKESH.C.M Page 180


class Cboxdemo
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}

Handling Checkboxes:

ItemEvent Class: An ItemEvent is generated when a checkbox or a list item is


clicked or when a checkable menu item is selected or deselected.

Hierarchy: java.lang.Object

java.util.EventObject

java.awt.AWTEvent

java.awt.event.ItemEvent

Methods:

1. Object getItem(): returns the item effected by the event


2. int getStateChange(): returns the type of state change

ItemListener Interface: Each time a Checkbox is selected or deselected, an item


event is generated. This is sent to any listeners. Each listener implements the
ItemListener interface. That interface defines the itemStateChanged() method. An
ItemEvent object is supplied as the argument to this method.

Method: void itemStateChanged (ActionEvent obj)

Example: Write a java program that simulates a traffic light. The program
lets the user select one of the three lights , red,yellow, or green. When a radio
button is selected , the light is turned on, and only one light can be on at a time.
No light is on when the program starts.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Color;

/*<applet code="Traffic" width=300 height=300>


</applet>*/

RAKESH.C.M Page 181


public class Traffic extends Applet implements ItemListener
{
CheckboxGroup cbg;
Checkbox a,b,c;
public void init()
{
cbg=new CheckboxGroup();
a=new Checkbox("Red",cbg,false);
b=new Checkbox("Green",cbg,false);
c=new Checkbox("Yellow",cbg,false);
add(a);
add(b);
add(c);
a.addItemListener(this);
b.addItemListener(this);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
if(cbg.getSelectedCheckbox()==a)
{
g.setColor(Color.red);
g.fillOval(150,120,50,50);
}
if(cbg.getSelectedCheckbox()==b)
{
g.setColor(Color.green);
g.fillOval(150,120,50,50);
}
if(cbg.getSelectedCheckbox()==c)
{
g.setColor(Color.yellow);
g.fillOval(150,120,50,50);
}
}
}

CheckboxGroup: Collection of check boxes is placed under one group is


considered as CheckboxGroup. These Checkboxes are often called radio buttons,
since one choice is selected at any one time. To create a set of mutually exclusive
check boxes, first define the group to which they will belong and then specify that
group when we construct the check boxes. Check box groups are objects of type
CheckboxGroup.

RAKESH.C.M Page 182


// Example program for Check boxes

import java.awt.*;
class Frame1 extends Frame
{
Checkbox c1,c2,c3;
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
CheckboxGroup cbg=new CheckboxGroup();
c1=new Checkbox("DOS",cbg,true);
c2=new Checkbox("Windows",cbg,false);
c3=new Checkbox("UNIX",cbg,false);
add(c1);
add(c2);
add(c3);
}
}
class Chgroup
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}

Handling CheckboxGroups:

// Example program to change the background color of the applet window by


selecting different colors placed in checkbox group

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class Checkboxdemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
CheckboxGroup cg;
public void init()
{
cg=new CheckboxGroup();
c1=new Checkbox("RED",cg,false);
c2=new Checkbox("GREEN",cg,false);

RAKESH.C.M Page 183


c3=new Checkbox("BLUE",cg,false);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg=cg.getSelectedCheckbox().getLabel();
if(msg.equals("RED"))
setBackground(Color.red);
else if(msg.equals("GREEN"))
setBackground(Color.green);
else if(msg.equals("BLUE"))
setBackground(Color.blue);
showStatus("Selected Color:"+msg);
}

}
/* <applet code="Checkboxdemo.class" width=400 height=350></Applet>*/

Choice Control: The Choice class is used to create a pop-up list of items from
which the user may choose. A Choice control is a form of menu. Choice only defines
the default constructor, which defines an empty list.

Choice( )

Methods:

1. void add(String name): To add a selection of the list specified by the


name argument
2. String getSelectedItem( ): Returns the string containing the name of the
item
3. int getSelectedIndex( ): Returns the index of the selected item. The first
item is at index 0.
4. int getItemCount( ): Returns the number of items in the list
5. void select(int index): To select the item in the choice depending upon
the index value
6. void select(String name): To select the item in the choice depending upon
the name argument
7. String getItem(int index): Returns the name of the item that contain the
value of index

RAKESH.C.M Page 184


// Example program to create a Choice list

import java.awt.*;
class Frame1 extends Frame
{
Frame1()
{
setTitle("Demo");
setSize(350,200);
setVisible(true);
setLayout(new FlowLayout());
Choice c=new Choice();
add(c);
c.add("Red");
c.add("Green");
c.add("Blue");
}
}

class Choicedemo
{
public static void main(String[] args)
{
Frame1 f=new Frame1();
}
}

Handling ChoiceLists:

// Example program to change the background color of the applet window by


selecting different colors from choice control

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

/*<applet code="Choicedemo.class" width=400 height=350> </Applet> */

public class Choicedemo extends Applet implements ItemListener


{
String msg=" ";
Choice ch;
public void init()
{
ch=new Choice();
ch.add("RED");
ch.add("GREEN");

RAKESH.C.M Page 185


ch.add("BLUE");
add(ch);
ch.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg=ch.getSelectedItem();
if(msg.equals("RED"))
setBackground(Color.red);
else if(msg.equals("GREEN"))
setBackground(Color.green);
else if(msg.equals("BLUE"))
setBackground(Color.blue);
g.drawString("Selection:"+msg,50,200);
showStatus("List Action Performance");
}
}

Lists: The List class provides a compact, multiple-choice, scrolling section list. The
list object can be constructed to show any number of choices in the visible window. It
can also be created to allow multiple selections. List provides these constructors.

List()
List(int nrows)
List(int nrows, boolean select)

The first form creates a List control that allows one item to be selected at any
one time.
In the second form, the value of nrows specifies the number of entries in the
list that will always visible.
In the third form, if select is true, then the user may select two or more items
at a time. If its is false, then only one item may be selected.

To add a selection to the list, call add() method

Syntax: void add(String name)


Void add(String name,int in)

Here, name is the item that is added to the list. It adds the items at the end of
the list.
The second form adds the item at the index specified by the in argument.
Indexing starts at zero. Specify –1 to add the item to the end of the list.

RAKESH.C.M Page 186


Methods:

1. String getSelectedItem(): returns the currently selected item as string.


If more than one item is selected, it returns null
2. int getSelectedIndex(): returns the index value of the currently selected
item. If more than one item is selected, it returns -1
3. String[] getSelectedItems(): returns the multiple selection of items as
string array
4. int[] getSelectedIndexes(): returns an array containing the indexes of
the currently selected items
5. int getItemCount(): returns the number of items in the list
6. void select(int in): set the item as selection specified by the in index
argument
7. String getItem(int in): returns the name associated with item by calling
its index with in argument

Handling Lists:

// Example program to select different items by creating a list box

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Listdemo.class" width=400 height=350> </Applet> */

public class Listdemo extends Applet implements ActionListener


{
String msg=" ";
List ch,browser;
public void init()
{
ch=new List(3,true);
browser=new List(4);
ch.add("DOS");
ch.add("WINDOWS");
ch.add("UNIX");
browser.add("Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
add(ch);
add(browser);
ch.addActionListener(this);
browser.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
repaint();
}

RAKESH.C.M Page 187


public void paint(Graphics g)
{

msg="Selected OS:";
int id[];
id=ch.getSelectedIndexes();
for(int i=0;i<id.length;i++)
msg=msg+ch.getItem(id[i])+ " ";
g.drawString(msg,50,100);
msg="Current:";
msg+=browser.getSelectedItem();
g.drawString(msg,50,150);
showStatus("List Action Performance");
}
}

Scroll Bars: Scroll bars are used to select continuous values between a specified
minimum and maximum. Scroll bars may be oriented horizontally or vertically. A
scroll bar is actually a composite of several individual parts. Each end has an arrow
that you can click to move the current value of the scroll bar one unit in the direction
of the arrow. The current value of the scroll bar relative to its minimum and
maximum values is indicated by the slider box for the scroll bar. The user can drag
the slider box to a new position. The scroll bar will then reflect this value.
Scrollbar defines the following constructors:

Scrollbar()
Scrollbar(int style)
Scrollbar(int style, int ivalue,int ssize, int min,int max)

The first form creates a vertical scroll bar


The second form and third form allow to specify the style of the scrollbar. If
style is Scrollbar.VERTICAL, a vertical scrollbar is created. If style is
Scrollbar.HORIZONTAL, the scrollbar is horizontal
In the third from the initial value is specified by ivalue, the number of units are
specified by ssize and minimum, maximum values for the scrollbar are specified by
min, max arguments.

Methods:

1. void setValues(int ivalue, int ssize, int min, int max): Used to set the parameters
2. int getValue(): returns the current setting value of the scrollbar
3. void setValue(int newvalue): Set with the newvalue
4. int getMinimum(): returns the minimum value of the scrollbar
5. int getMaximum(): return the maximum value of the scrollbar

RAKESH.C.M Page 188


TextField: The TextField class implements a single-line text entry area, usually
called an edit control. Text fields are used to enter stings to edit the information.
TextField is a subclass of TextComponent. TextField defines the following
constructors:
TextField()
TextField(int num)
TextField(String str)
TextField(String str, int num)

The first form creates a default text field.


The second form creates a text field that is num characters wide
The third form creates a text field with the string specified by str
The fourth form initializes a text field and sets its width

Methods:

1. Sting getText(): returns the information currently contained in the text


field as string
2. void setText(String str): sets the string information into the text field
3. String getSelectedText(): returns the currently selected text
4. void selected(int sindex, int eindex): selects the characters beginning at
sindex and ending at eindex-1
5. boolean isEditable(): return true if the text may be changed and false if
not
6. void setEditable(boolean b): if b is true, the text may be changed,
otherwise, the text cannot be altered
7. void getEchoChar(char ch): it disable the echoing characters on the
screen and display the characters as specified by the ch argument
8. boolean echoCharIsSet(): returns true, if echochar is set otherwise,
returns false
9. char getEchoChar(): returns the echo character

Handling TextFields:

//Example program to create an Applet to enter the data in Textfields and


display sum of the two numbers

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Tdemo.class" width=400 height=350> </Applet> */

public class Tdemo extends Applet implements ActionListener


{
TextField t1,t2,t3;
Label L1,L2,L3;
public void init()
{
L1=new Label("Enter the first Number:");
add(L1);

RAKESH.C.M Page 189


t1=new TextField(15);
add(t1);
L2=new Label("Enter the second Number:");
add(L2);
t2=new TextField(15);
add(t2);
t1.addActionListener(this);
t2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}

public void paint(Graphics g)


{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int sum=x+y;
g.drawString("Total="+sum,100,100);
}
}

TextArea: TextField is useful to enter only one line of information. If we want to


enter more than one line of data it is not possible with the TextField. To handle these
situaltions, the AWT includes a simple multiline editor called TextArea.
Constructors of the TextArea are:

TextArea()
TextArea(int nlines, int nchars)
TextArea(String str)
TextArea(String str, int nlines, int nchars)
TextArea(String str, int nlines, int nchars, int sbars)

nlines specifies the height in lines, nchars specifies the width in charactes
str specifies the string filled with TextArea
sbars specifies the scroll bars that are associated with the TextArea. Sbars
must have one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORNIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY

It supports the getText(), setText(), getSelectedText(), select(), isEditable()


and stEditable() methods. In addition it also supports the following methods

1. void append(String str): it appends the string specified by str to the end
of current text

RAKESH.C.M Page 190


2. void insert(String str, int index): inserts the string specified by str at the
specified index
3. void replaceRange(String str, int sindex, int eindex): replaces the
characters with str from sindex to eindex-1

// Example Program:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="TextAreademo.class" width=400 height=350> </Applet> */

public class TextAreademo extends Applet


{
public void init()
{
String str="Java Language\n"+
"The Complete Reference\n"+
"Schildt\n"+
"TATA McGRAW HILL";
TextArea t=new TextArea(str,10,15);
add(t);
}
}

LAYOUT MANAGERS

Layout Manager is a technique used by the AWT to assign the locations of


components within a container. A layout manager is an instance of any class that
implements the LayoutManager interface. The layout manager is set by the
setLayoutt() method.
The general form of this method is:

void setLayout(LayoutManager obj)

If no call to setLayout() is made, then the default layout manager is used.


There are five standard types of layout managers:

1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout

RAKESH.C.M Page 191


1. FlowLayout:

FlowLayout implements a simple layout style, which is similar to words flow


in a text editor. The direction is by default, left-to-right, top-to-bottom and line
completed automatically moves to next line.
Constructors for FlowLayout are:

FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

The first form creates a default layout, with five pixels of space between each
component.
The second form specifies how each line is aligned. Valid values for how are
as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING

The third constructor allows to specify the horizontal and vertical space
between components in horz and vert, respectively.

// EXAMPLE PROGRAM FOR FLOW LAYOUT MANAGER

import java.awt.*;
import java.applet.*;

/* <applet code="Lay1" width=300 height=300>


</applet> */

public class Lay1 extends Applet


{
Checkbox ch;
public void init()
{
setLayout(new FlowLayout(FlowLayout.CENTER));
ch=new Checkbox("Windows XP",null,true);
add(ch);
}
}

RAKESH.C.M Page 192


2. BorderLayout:

BorderLayout has four narrow, fixed-width components at the edges and one
large area in the center. The four sides are referred to as north, south, east and west.
The middle area is called the center. Constructors for BorderLaout is:
BorderLayout()
BorderLayout(int horz, int vert)
The first form creates a default border layout.
The second form allows to specify the horizontal and vertical space between
components in horz and vert, respectively.
When adding components, we use add( ) method, defined by Container.
void add(Component obj, Object region)
The region specified with the constants:
BorderLayout.CENTER
BorderLayout.EAST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.WEST

// EXAMPLE PROGRAM FOR BORDER LAYOUT


import java.awt.*;
import java.applet.*;
import java.util.*;
/* <applet code="Lay2" width=300 height=300>
</applet> */
public class Lay2 extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button("TOP BUTTON"),BorderLayout.NORTH);
add(new Button("BOTTOM BUTTON"),BorderLayout.SOUTH);
add(new Button("RIGHT BUTTON"),BorderLayout.EAST);
add(new Button("LEFT BUTTON"),BorderLayout.WEST);
String msg="India"+"\nSrilanka"+"\nPakistan";
add(new TextArea(msg), BorderLayout.CENTER);
}
}

RAKESH.C.M Page 193


3. GridLayout:
GridLayout lays out components in a two-dimensional grid. Here, we
specifies number of rows and columns. The constructors are:
GridLayout()
GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int horz, int vert)
The first form creates a single-column grid layout.
The second form creates a grid layout with the specified number of rows and
columns.
The third form creates to specify the horizontal and vertical space between
components in horz and vert, respetively.

// EXAMPLE PROGRAM FOR GRID LAYOUT

import java.awt.*;
import java.applet.*;
import java.util.*;
/* <applet code="Lay3" width=300 height=300>
</applet> */

public class Lay3 extends Applet


{
static final int n=4;
public void init()
{
setLayout(new GridLayout(n,n));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int k=i*n+j;
if(k>0)
add(new Button(" "+k));
}
}
}
}

RAKESH.C.M Page 194


Example: Write a java program that works as a simple calculator. Use a grid
layout to arrange buttons for the digits and for the +,*,-,/ operations. Add a text
field to display the result.

import java.awt.*;
import java.awt.event.*;
import java.awt.Color;

class NFrame extends Frame implements ActionListener


{
int a,b,r;
String s;
char ch;
TextArea t;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
public NFrame()
{
setTitle("Calculator");
setSize(200,200);
t=new TextArea("",1,10,3);
b0=new Button("0");
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b10=new Button("+");
b11=new Button("-");
b12=new Button("*");
b13=new Button("/");
b14=new Button("%");
b15=new Button("=");
b16=new Button("clear");
b0.setForeground(Color.RED);
b1.setForeground(Color.RED);
b2.setForeground(Color.RED);
b3.setForeground(Color.RED);
b4.setForeground(Color.RED);
b5.setForeground(Color.RED);
b6.setForeground(Color.RED);
b7.setForeground(Color.RED);
b8.setForeground(Color.RED);
b9.setForeground(Color.RED);
b10.setForeground(Color.RED);
b11.setForeground(Color.RED);
b12.setForeground(Color.RED);

RAKESH.C.M Page 195


b13.setForeground(Color.RED);
b14.setForeground(Color.RED);
b15.setForeground(Color.RED);
b16.setForeground(Color.RED);
Panel p=new Panel();
p.setLayout(new GridLayout(4,4));
p.add(b0);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(b10);
p.add(b11);
p.add(b12);
p.add(b13);
p.add(b14);
p.add(b15);
p.add(b16);
add(p,BorderLayout.CENTER);
add(t,BorderLayout.NORTH);
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b16.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b0)
t.append("0");
if(e.getSource()==b1)
t.append("1");

RAKESH.C.M Page 196


if(e.getSource()==b2)
t.append("2");
if(e.getSource()==b3)
t.append("3");
if(e.getSource()==b4)
t.append("4");
if(e.getSource()==b5)
t.append("5");
if(e.getSource()==b6)
t.append("6");
if(e.getSource()==b7)
t.append("7");
if(e.getSource()==b8)
t.append("8");
if(e.getSource()==b9)
t.append("9");
if(e.getSource()==b10)
{
ch='+';
s=t.getText();
a=Integer.parseInt(s);
t.setText("");
}
if(e.getSource()==b11)
{
ch='-';
s=t.getText();
a=Integer.parseInt(s);
t.setText("");
}
if(e.getSource()==b12)
{
ch='*';
s=t.getText();
a=Integer.parseInt(s);
t.setText("");
}
if(e.getSource()==b13)
{
ch='/';
s=t.getText();
a=Integer.parseInt(s);
t.setText("");
}
if(e.getSource()==b14)
{
ch='%';
s=t.getText();
a=Integer.parseInt(s);
t.setText("");

RAKESH.C.M Page 197


}
if(e.getSource()==b15)
{
s=t.getText();
b=Integer.parseInt(s);
switch(ch)
{
case '+': r=a+b;
t.setText(String.valueOf(r));
break;
case '-': r=a-b;
t.setText(String.valueOf(r));
break;
case '*': r=a*b;
t.setText(String.valueOf(r));
break;

case '/': r=a/b;


t.setText(String.valueOf(r));
break;
case '%': r=a%b;
t.setText(String.valueOf(r));
break;
}
}
if(e.getSource()==b16)
t.setText(" ");
}
}
class Mcal
{
public static void main(String args[])
{
new NFrame();
}
}

4. CardLayout:

The CardLayout class is unique among the other layout managers in that it
stores several layouts. It provides constructors as:

CardLayout()
CardLayout(int horz, int vert)

The first form creates a default card layout.


The second form allows to specify the horizontal and vertical space between
components in horz and vert, respectively.

RAKESH.C.M Page 198


// EXAMPLE PROGRAM FOR CARD LAYOUT

import java.awt.*;
import java.applet.*;
import java.util.*;

/* <applet code="Lay4" width=300 height=300>


</applet> */

public class Lay4 extends Applet


{
CardLayout obj;
Panel x;
public void init()
{
obj=new CardLayout();
x=new Panel();
x.setLayout(obj);
}
}

5. GridBagLayout:

GridBagLayout manager allows the programmer to create a non uniform grid


of squares, and place components in various positions within each square. It provides
only one constructor as:

GridBagLayout()

// EXAMPLE PROGRAM FOR GRID BAG LAYOUT

import java.awt.*;
import java.applet.*;
import java.util.*;

/* <applet code="Lay5" width=300 height=300>


</applet> */

public class Lay5 extends Applet


{

public void init()


{
GridBagLayout obj=new GridBagLayout();
setLayout(obj);
}
}

***

RAKESH.C.M Page 199


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-VII: Applets: Concepts of Applets, differences between applets and


applications, life cycle of an applet, types of applets, creating applets, passing parameters to
applets.
Swing: 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.

APPLET

Java programs are generally classified into two ways as:


1. Applications programs
2. Applet programs

Application Programs: Applications programs are those programs normally created,


compiled and executed as similar to the other languages. Each Application program
contains one main() method. Programs are created in a local computer. Programs are
compiled with javac compiler and executed with java interpreter.

Applet Programs: Applet programs are small programs that are primarily used in
Internet programming. These programs are either developed in local systems or in
remote systems and are executed by either a java compatible “Web browser” or
“appletviewer”.
An applet developed locally and stored in a local system is known as a Local
Applet. When a Web page is trying to find a local applet, it does not need to use the
Internet and therefore the local system does not require the Internet connection. It
simply searches the directories in the local system and locates and loads the specified
applet.
An applet developed by someone else and stored on a remote computer is
known as Remote Applet. If our system is connected to the Internet, we download the
remote applet onto our system via the Internet and run it. In order to locate the remote
applet, we must know the applet’s address on the Web. This address is known as
Uniform Resource Locator (URL).

APPLET LIFE CYCLE

Every java applet inherits a set of default behaviors from the Applet class
defined in java.applet package. When an applet is loaded, it undergoes a series of
changes in its states. The important states of the Applet Life Cycle are:
Born or Initialization State
Running State
Idle State
Dead or Destroyed State

RAKESH.C.M Page 200


Initialization State: Applet enters the initialization state when it is first loaded. This
is achieved by calling the init() method of Applet class. The applet is born. The
initialization occurs only once in the applet’s life cycle. Generally all the
initialization variables are to be placed in the init() method.
Syntax: public void init()
{
....
. . . . (Action)
}

Running State: Applet enters the running state when the system calls the start()
method of Applet class. This occurs automatically after the applet is initialized.
Starting can also occurs if the applet is already in “Stopped State”. The start() method
may be called more than once.

Syntax: public void start()


{
....
. . . . (Action)
}

Idle or Stopped State: An applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the currently
running applet. This can also done by calling the stop() method explicitly.

Syntax: public void stop()


{
....
. . . . (Action)
}

Dead State: An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when we quit the browser.
Destroying stage occurs only once in the applet life cycle.

Syntax: public void destroy()


{
....
. . . . (Action)
}

Display State: Display state is useful to display the information on the output screen.
This happens immediately after the applet enters into the running state. The paint() is
called to accomplish this task. Almost every applet will have a paint() method.

Syntax: public void paint(Graphics g)


{
....
. . . . (Display Statements)
}

RAKESH.C.M Page 201


Begin Born Initialization
(Load Applet)

start()

stop()

paint() Running Idle Stopped

start()

destroy()

Destroyed
Dead
End

Exit of Browser

Note:
1. All the methods are automatically to called when any applet begin
execution.
2. The applet execution follows the above order.
3. In every applet it doesn’t need to place all the methods.
4. class hierarchy of the applet is

java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Panel

java.applet.Applet

The steps involved in developing and testing an applet are:


1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Create HTML page with the <APPLET> tag
4. Testing the Applet code with appletviewer

RAKESH.C.M Page 202


Applet Tag: The <APPLET> tag supplies the name of the applet to be loaded and
tells the browser how much space the applet requires. The Applet tag is specified as

<applet code=”filename.class” width=400 height=300>


</Applet>

Example: Write a program to create an Applet to display a simple Message.

Method 1:

import java.awt.*;
import java.applet.Applet;
public class Apdemo extends Applet
{
String msg=" ";
public void init()
{
msg=msg+"Init";
}
public void start()
{
msg=msg+"Start";
}
public void paint(Graphics g)
{
msg=msg+"Paint";
g.drawString(msg,50,100);
}
}

Save the file with Apdemo.java and compile as


C:> javac Apdemo.java

Create the html file as


<HTML>
<applet code="Apdemo.class" width=400 height=350>
</Applet>
</HTML>
Save the file with Ap.html and run the program as
C:> appletviewer Ap.html

Method 2:

import java.awt.*;
import java.applet.Applet;
/* <applet code="Apdemo1.class" width=400 height=350>
</Applet> */

RAKESH.C.M Page 203


public class Apdemo1 extends Applet
{
String msg=" ";
public void init()
{
msg=msg+"Init";
}
public void start()
{
msg=msg+"Start";
}
public void paint(Graphics g)
{
msg=msg+"Paint";
g.drawString(msg,50,100);
}
}

Save the file with Apdemo1.java compile and run the program as
C:> javac Apdemo1.java
C:> appletviewer Apdemo1.java

Status Window: Apart to display the information in its window, applet also produce
an applet status window of the browser on which it is running. It can be changed by
calling showStatus() method specified by passing the string as an argument.

repaint(): If the programmer needs to call the paint(), a call is made to the
Component class repaint() method. Method repaint request a call to the component
class update() method. As soon as possible to clear the components background of
any previous status then update calls paints directly. The repaint() method is
frequently called by the programmer to force paint() operation.
Syntax: public void repaint()
public void update(Graphics g)

update() method takes a Graphics object as an argument which is supplied


automatically by the system when update() is called.

PASSING PARAMETERS TO APPLETS

It is also possible to supply user-defined parameters to an applet using


<PARAM> tags. Each <PARAM> tag has a name attribute and value attribute.
Inside the applet code, the applet can refer to that parameter by name to find its value.
To retrieve the parameter, use the getParameter() method. It returns the value of the
specified parameter in the form of a String object.

RAKESH.C.M Page 204


Example program:

import java.awt.*;
import java.applet.Applet;
/* <applet code="paramdemo.class" width=400 height=350>
<param name=first value=50>
<param name=second value=160>
</Applet> */

public class paramdemo extends Applet


{
String first,second;
int x,y,sum;
public void paint(Graphics g)
{
x=Integer.parseInt(getParameter("first"));
y=Integer.parseInt(getParameter("second"));
sum=x+y;
g.drawString("Total value="+sum,100,100);
}
}

SWINGS

GUI represents a pictorial interface to a program. GUI environment provides


a distinctive appearance the user to interact with the program. GUI’s are built from
GUI components.
Swing is a set of classes that provides more powerful and flexible functionality
than in possible with the standard AWT components. The classes that are used to
create the GUI components are part of the swing GUI components from package
javax.swing. These are the newest GUI components of the Java2 platform. Swing
components are written, manipulated and displayed completely in Java, so called pure
Java components.
The outset that Swing is built upon the foundation of the AWT. So, that
Swing provides all the facilities that are supported by the AWT in addition that it also
provides some additional components such as tabbed panes, scroll panes, trees and
tables.
Main difference between AWT and Swing components are in AWT, a Java
program executing on different Java platform provides different appearance and some
times even different interactions on each platform. AWT components are tied to the
local platform are corresponding called heavy weight components. Whereas,
Swing component programs are gave same look in any Java platform even we change
the environment. So, that the program running with Swing components are often
referred as lightweight components. These are platform independent.

RAKESH.C.M Page 205


The Swing related classes are contained in javax.swing package. Some of the
classes are

AbstractButton : Abstract superclass for swing buttons


ButtonGroup : Encapsulates a mutually exclusive set of Buttons
ImageIcon : Encapsulates an icon
Japplet : The Swing version of Applet
Jbutton : The Swing version of push button
JcheckBox : The Swing check box class
JcomboBox : Encapsulates a combo box
Jlabel : The Swing version of a label
JradioButton : The Swing version of a radio button
JscrollPane : Encapsulates a scrollable window
JtabbedPane : Encapsulates a tabbed window
JtextField : The Swing version of a text field
Jtree : Encapsulates a tree-based control

JApplet: Fundamental to Swing is the JApplet class, which extends Applet. JApplet
supports various “Panes” such as the content pane, the glass pane, and the root pane.
When adding a component to an instance of JApplet, call add() method of the
applet. Instead, we need to call add() on the content pane of the JApplet object. The
content pane can be obtained via the method:
Container getContentPane()
The add() method of the Container was then used to add a component to the content
pane.
Ex: Container c=getContentPane();
c.add(comp);

Note: add(), remove() and setLayout() are directly available in JApplet.

JFrame: JFrame extends the AWT class Frame. It contains additional features that
enable it to support Swing components.

JComponent: Jcomponent class extends the AWT Component and Container classes.
It is the top-level class for all swing components.

Icons: Icons are encapsulated by the ImageIcon class, which paints an icon from an
image. ImageIcon class provides a constructor as:

ImageIcon(String filename)

ImageIcon class implements the Icon interface and provides the methods as:
1. int getIconHeight(): returns the height of the icon in pixels
2. int getIconWidth(): returns the width of the icon in pixels

RAKESH.C.M Page 206


JLabel

Swing labels are instances of the JLabel class, which extends Jcomponent. It
displays text and/or an icon. Constructors provided by the JLabel class are:

JLabel(Icon I)
JLabel(String S)
JLabel(String S, Icon I, int Align)

S and I are text and icon used for the label. Align argument is LEFT, RIGHT,
CENTER, LEADING or TRAILING

Methods:

1. Icon getIcon()
2. Sting getText()
3. void setIcon(Icon I)
4. void setText(String s)

// Example program
import javax.swing.*;
import java.awt.*;
/* <applet code="Jl.class" width=200 height=150>
</Applet> */

public class Jl extends JApplet


{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
ImageIcon i=new ImageIcon("HLPstep1.gif");
JLabel j=new JLabel("Hello",i,JLabel.CENTER);
c.add(j);
}
}

JTextField

The Swing text field is encapsulated by the JTextComponent class, which


extends Jcomponent. It provides functionality that is common to Swing text
components. One of its subclasses is JTextField, which allows to edit one line of text.
JTextField class provides the constructors as:

JTextField()
JTextField(int col)
JTextField(String s, int col)
JTextField(String s)

RAKESH.C.M Page 207


// Example program

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/* <applet code="Jt.class" width=300 height=250>


</Applet> */

public class Jt extends JApplet implements ActionListener


{
JTextField t1;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
t1=new JTextField(15);
c.add(t1);
t1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
showStatus(t1.getText());
}
}

JButton

Swing buttons are subclasses of the AbstractButton class, which extends


Jcomponent. AbstractButton contains many methods to allow control the behavior
of buttons, check boxes, and radio buttons. Some of the methods to handle these
things are:

1. void setDisabledIcon(Icon d)
2. void setPressedIcon(Icon d)
3. void setSelectedIcon(Icon d)
4. void setRolloverIcon(Icon d)
5. String getText()
6. void setText(String s)

JButton class provides the functionality of the push buttons. Constructors


provided by the JButton class are:

JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)

RAKESH.C.M Page 208


// Example Program

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/* <applet code="JB.class" width=300 height=250>
</Applet> */

public class JB extends JApplet implements ActionListener


{
JButton b1,b2;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.CENTER));
b1=new JButton("yes");
c.add(b1);
b1.addActionListener(this);
b2=new JButton("no");
c.add(b2);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
showStatus(e.getActionCommand());
}
}

Check Boxes

The JCheckBox class provides the functionality of a check box. JCheckBox


defines a constructor as:

JCheckBox(String str)

When the user selects or deselects a check box, an ItemEvent is generated.


We can objtain a reference to the JCheckBox that generated the event by calling
getItem() on the ItemEvent passed to the itemStateChanged() method defined by
ItemListener.

// DEMONSTRATE JCheckBox

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/* <applet code="Demo" width=300 height=300>


</applet> */

RAKESH.C.M Page 209


public class Demo extends JApplet implements ItemListener
{
JLabel jl;
public void init()
{
setLayout(new FlowLayout());
JCheckBox c1=new JCheckBox("C");
c1.addItemListener(this);
add(c1);
c1=new JCheckBox("C++");
c1.addItemListener(this);
add(c1);
jl=new JLabel("Select");
add(jl);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox c1=(JCheckBox)ie.getItem();
if(c1.isSelected())
jl.setText(c1.getText()+ " is selected");
else
jl.setText(c1.getText()+ " is selected");
}
}

Radio Buttons

Radio buttons are a group of mutually exclusive buttons, in which only one
button can be selected at any one time. JRadioButton constructor is as:

JRadioButton(String str)

JRadioButton operations implemtn the ActionListener interface and uses


actionPerformed() method.

// EXAMPLE PROGRAM TO DEMONSTRATE RADIO BUTTONS

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/* <applet code="Demo" width=300 height=300>


</applet> */

public class Demo extends JApplet implements ActionListener


{
JLabel jl;

RAKESH.C.M Page 210


public void init()
{
setLayout(new FlowLayout());
JRadioButton c1=new JRadioButton("C");
c1.addActionListener(this);
add(c1);
JRadioButton c2=new JRadioButton("C++");
c2.addActionListener(this);
add(c2);
jl=new JLabel("Select");
add(jl);
ButtonGroup bg=new ButtonGroup();
bg.add(c1);
bg.add(c2);
}
public void actionPerformed(ActionEvent ie)
{
jl.setText("Selection "+ie.getActionCommand());
}
}

JComboBox

Swing provides a combo box through the JComboBox class. A combo box
normally displays one entry, but it will also display a drop-down list that allows a user
to select a diffeent entry. The JComboBox class constructor is:

JComboBox(Object [] items)

Here,
items is an array that initialize the combo box.

Methods:

void addItem(Object obj)


Object getSelectedItem()

// EXAMPLE PROGRAM TO CREATE JCOMBO BOX

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/* <applet code="Demo" width=300 height=300>


</applet> */

RAKESH.C.M Page 211


public class Demo extends JApplet
{
JComboBox jcb;
String flags[]={"France","Germany","Italy"};
public void init()
{
setLayout(new FlowLayout());
jcb=new JComboBox(flags);
add(jcb);
}
}

JScrollPane

JScrollPane is a lightweight container that automatically handles the scrolling


of another component. The component being scrolled can either be an individual
component such as a table, or a group of components contained within another
lightweight container, such as JPanel. JScrollPane Constructor is:

JScrollPane(Component comp)

Steps follow to use a scroll pane:

1. Create the component to be scrolled.


2. Create an instance of JScrollPane, passing ot it the objet to
scsroll.
3. Add the scroll pane to the content pane.

// EXAMPLE PROGRAM FOR JSCROLL PANE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/* <applet code="Demo" width=300 height=300>


</applet> */

public class Demo extends JApplet


{

public void init()


{
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(20,20));
int b=0;
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{

RAKESH.C.M Page 212


jp.add(new JButton("B "+b));
++b;
}
}
JScrollPane jsp=new JScrollPane(jp);
add(jsp,BorderLayout.CENTER);
}
}

JTabbedPane

A tabbed pane is a component that appears as a group of folders in a file


cabinet. Each folder has a title. When a user selects a folder, its contents become
visible. Only one folder may be selected at a time.
Tabbed panes are encapsulated by the JTabbedPane class, which extends
JComponent. Constructor provided by the class is: JTabbedPane()
Tabs are added to the TabbedPane by calling addTab() method as:

void addTab(String str, Component com)

str is the title of the tab


com is the component that should be added to the tab

Steps to follow in JTabbed Pane are:

1. Create an instance of JTabbedPane.


2. Add each tab by calling addTab().
3. Add the tabbed pane to the content pane.

// EXAMPLE PROGRAM FOR JTABBED PANE

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/* <applet code="JTab.class" width=300 height=250>
</Applet> */

public class JTab extends JApplet


{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT));
JTabbedPane jb=new JTabbedPane();
jb.addTab("cities",new City());
jb.addTab("color",new Colors());
c.add(jb);
}
}

RAKESH.C.M Page 213


class City extends JPanel
{
public City()
{
JButton b1=new JButton("BOmbay");
add(b1);
JButton b2=new JButton("Chennai");
add(b2);
}
}
class Colors extends JPanel
{
public Colors()
{
JButton b1=new JButton("Red");
add(b1);
JButton b2=new JButton("Green");
add(b2);
}
}

Trees

A tree is a component that presents a hierarchical view of data. The user has
the ability to expand or collapse individual subtrees in this display. Trees are
implemented in Swing by JTree class. Constructors are:

JTree (Object obj[])


JTree (Vector v)
JTree (TreeNode tn)

In the first form, the tree is constructed from the elements in the array obj.
In the second form, the tree form the elements of vector v.
In the third form, the tree whose root nodej is specified by tn specifies the tree.

Steps to follow to use a tree:

1. Create an instance of JTree.


2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.

// EXAMPLE PROGRAM TO CREATE TREE STRUCTURE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

RAKESH.C.M Page 214


/* <applet code="Demo" width=300 height=300>
</applet> */

public class Demo extends JApplet


{
JTree jt;
public void init()
{
DefaultMutableTreeNode top=new DefaultMutableTreeNode("ROOT");

DefaultMutableTreeNode a=new DefaultMutableTreeNode("A1");


top.add(a);
DefaultMutableTreeNode b=new DefaultMutableTreeNode("A2");
top.add(b);
DefaultMutableTreeNode c=new DefaultMutableTreeNode("A3");
top.add(c);

jt=new JTree(top);

JScrollPane jsp=new JScrollPane(jt);


add(jsp);
}
}

JTable

JTable is a component that displays rows and columns of data. We can drag
the cursor position on column boundaries to resize columns. Constructor used for
JTable class is:
JTable(Object data[][], Object col[[])
Here,
data is a two-dimensional array of the information to be presented.
col is a one-dimensional array with the colum headings.

Steps to follow to set up a simple JTable:

1. Create an instance of JTable.


2. Create a JScrollPane object, specifying the table as the objetct to
scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

// EXAMPLE PROGRAM FOR JTABLE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

RAKESH.C.M Page 215


/* <applet code="Demo" width=300 height=300>
</applet> */

public class Demo extends JApplet


{

public void init()


{
String col[]={"Language","Year"};
Object data[][]={ {"C","1972"},{"C++","1979"},{"JAVA","1995"}};
JTable jt=new JTable(data,col);
JScrollPane jsp=new JScrollPane(jt);
add(jsp);
}
}

Example: Suppose that a table named Table.txt is stored in a text file. The
first line in the file is the header, and the remaining lines correspond to rows in
the table. The elements are operated by commas. Write a java program to
display the table using JTable component.

import java.awt.*;
import java.applet.*;
import java.io.*;
import javax.swing.*;
import java.util.*;

/*<applet code="Tabledemo" width=300 height=300>


</applet>*/

public class Tabledemo extends JApplet


{
public void init()
{
try
{
FileReader f=new FileReader("table.txt");
BufferedReader br=new BufferedReader(f);
String data[][]=new String[3][3];
String col[]=new String[3];
String s=br.readLine();
StringTokenizer st=new StringTokenizer(s,",");
for(int i=0;i<3;i++)
{
col[i]=st.nextToken();
}

RAKESH.C.M Page 216


for(int i=0;i<3;i++)
{
String s1=br.readLine();
StringTokenizer st1=new StringTokenizer(s1,",");
for(int j=0;j<3;j++)
data[i][j]=st1.nextToken();
}
Container c=getContentPane();
JTable t=new JTable(data,col);
JScrollPane js=new JScrollPane(t);
c.add(js);
}
catch(Exception e)
{
}
}
}

***

RAKESH.C.M Page 217


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY
II YEAR B.Tech. CSE – II SEM

OBJECT ORIENTED PROGRAMMING

UNIT-VIII: Networking: Basics of network programming, addresses, ports, sockets,


simple client server program, multiple clients, java.net package, Enumerations, autoboxing,
annotations, generics.

NETWORKING

Network: More than one computer systems are connected to sent and receive the
information with each other is considered as a Network. Due to the networking there
is a communication between the systems. So, that they are shared data as well as
resources.

Internet: An interconnection of networks is considered as a Internet or Intranet. It is


the name for vast of worldwide systems, which consists of different types of computer
systems, different types of networks or different servers. The Computers that are
connected to the Internet is considered as a Host.

Socket Overview: Networks sockets are used for networking the systems. A
Network Socket is like an electrical socket at which various plugs around the network
has a standard way of delivering their payload. For transmission the data, the sockets
are used some protocols.

“Protocol” is a standard set of rules, which is used to transfer the data from
one system to another. Protocols ae classified into two types as:

1. Connection-oriented Protocols: Ex: TCP/IP Protocols


2. Connection-less Protocols: Ex: UDP Protocols

Internet Protocol (IP) is a low-level routing protocol that breaks data into small
packets and sends them to an address across the network. It is not guarantee to
deliver the packets to destination.

Transmission Protocol (TCP) is a higher-level protocol that manages to robustly


string together these packets, sorting and retransmitting them as necessary to reliably
transmit the data.

User Datagram Protocol (UDP) used directly to support fast, connectionless,


unreliable transfer of packets.

Client/Server: A Server is anything that has some resource that can be shared. It is
permanently available resource. Different types of servers are
Compute servers : which provides computing server
Print Servers : which manages a collection of printers
Disk Servers : which provides a networked disk space
Web servers : which store web pages
RAKESH.C.M Page 218
A Client is an entity that wants to gain access to a particular server.

The notion of a socket allows a single computer to server many different


clients at once, as well as serves different types of information. This is managed by a
port, which is a numbered socket on a particular machine.
Server process is said to be “listen” to a port until a client connects to it. A
server is allowed to accept multiple clients connected to the same port number,
although each session is unique. To manage multiple client connections, process
must be multithreaded.
When multiple Hosts are connected to the user, unique systems are identified
by an address called IPAddress as 192.168.1.146. Unique IPAddresses for each host
are provided by InterNIC (Inter Network Information Center).

TCP/IP reserves the lower 1024 ports for specific protocols. Some of the
reserved protocols are:
21 - FTP
23 - Telnet
25 - e-mail
43 - whois
79 - finger
80 - HTTP
119 - netnews

Every computer on the Internet has an address. An Internet address is a


number that uniquely identifies each computer on the Net. All Internet addresses
consisted of 32-bit values organized as four 8-bit values. This address type was
specified by Ipv4 (Internet Protocol, version 4). New versions addressing scheme
called Ipv6 (Internet Protocol version 6). Ipv4 is compatible with Ipv6.
For example, http://192.9.9.1/, the number is called Domain Naming Service
(DNS). The numbers of an IP address describe the network hierarchy, the name of an
Internet address, called its domain name, describes a machine’s location in a name
space.

Java and the Net

Java supports TCP/IP both by extending the already establish stream I/O
interfaces and by adding the features required to build I/O objects across the network.
Java supports both the TCP and UDP protocols families. TCP is used for reliable
stream-based I/O across the network. UDP supports a faster, point-to-point datagram-
oriented model.
All the network classes are supported by java.net package. Some of the
classes are
InetAddress, DatagramPacket, DaragramSocket etc.,

InetAddress Class: When we form a connection across the Internet, addresses are the
fundamental notations. InetAddress is a class that is used to encapsulate both the
numerical IPAddress and domain name for that address.

RAKESH.C.M Page 219


The InetAddress class has no visible constructors. To create an InetAddress
Object, use the factory methods of the class. Factory methods are static methods in a
class return all instance of that class. The commonly used InetAddress factory
methods are:

1. static InetAddress getLocalHost(): returns the InetAddress object


that represents the local host
2. static InetAddress getByName(String hostname): returns an
InetAddress for a host name passed to it
3. static InetAddress getAllByName(String hostname): In web servers,
a single name is used to represent several machines. This method
returns an array of InetAddresses that represent all the addresses that a
particular name resolves in it.

All the methods are possible to throw an UnknownHostException.

// Example program to print the InetAddress of the local system.

import java.net.*;
class netdemo
{
public static void main(String[] args) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
System.out.println("IPAddress:"+ia);
}
}

//O/P: IPAddress:pbrvits210/192.168.1.210

Instance Methods: The InetAddress class also has several other methods, which
can be used on the objects returned by the methods.

1. boolean equals(Object oth): returns true if this object has the same
internet address as other
2. byte[] getAddress(): returns a byte array that represents the object’s
Internet address in network byte order
3. String getHostAddress(): returns a string that represents the host
address associated with the InetAddress object
4. String getHostName(): returns a string that represents the host name
associated with the InetAddress object
5. String toString(): returns a string that lists the host name and the IP
address for convenience

RAKESH.C.M Page 220


// Example program

import java.net.*;
class netdemo1
{
public static void main(String[] args) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
String str=ia.getHostName();
System.out.println("Host Name :"+str);
}
}

// O/P: Host Name : pbrvits210

TCP/IP SOCKETS

TCP/IP Sockets are used to implement reliable, bi-directional, persistent,


point-to-point stream-based connections between hosts on the Internet. A socket can
be used to connect Java’s I/O system to other system programs that may reside either
on the local machine or on any other machine on the Internet. There are two types of
TCP/IP sockets are available in Java. They are:
1. ServerSocket (for Server)
2. Socket (for Client)

Socket: The Socket class is designed to connect to server sockets and initiate
protocol exchanges. The creation of socket object implicitly establishes a connection
between the client and server. Two constructors to create client sockets are:
Socket(String hostname, int port): Creates a socket, connecting the
local host to the name host and port; can throw an UnknownHostException or an
IOException
Socket(InetAddress ia, int port): Creates a socket using a preexisting
Inetaddress object and a port; can throw an IOException.

Methods:

1. InetAddress getInetAddress(): returns the InetAddress associated


with the Socket Object
2. int getPort(): returns the remote port to which the invoking socket
object is connected
3. int getLocalPort(): returns the local port to which the invoking Socket
object is connected

Once the Socket object has been created, it is possible to access the input and output
streams associated with it. For this the following methods are use. They are:

RAKESH.C.M Page 221


1. InputStream getInputStream(): returns the InputStream associated
with the invoking socket
2. OutputStream getOutputStream(): returns the OutputStream
associated with the invoking socket.

ServerSocket: The ServerSocket class is used to create servers that listen for either
local or remote client programs to connect to them on published ports. When we
create a ServerSocket, it will register itself with the system as having an interest in
client connections. The constructors for ServerSocket reflect the port number that
we wish to accept connections. Constructors provided by the ServerSocket class are:

1. ServerSocket(int port): creates a server socket on the specified port


with a queue length of 50
2. ServerSocket(int port, int max): creates a server socket on the specified
port with a maximum queue length of max
3. ServerSocket(int port, int max, InetAddress ia): creates a server
socket on the specified port with a maximum queue length of max. On a
multihomed host, ia specifies the IP Address to which this socket binds
ServerSocket has a method called accept(), which is a blocking call that will wait for
a client to initiate communications, and then return with a normal Socket that is then
used for communication with the client.

Example: Write a java program that implements a simple client/server application.


The client sends data to a server. The server receives data ,uses it to produce a result,
and then sends the result back to the client. The client displays the result on the console.
For example the data sent from the client is the radius of a circle, and the result
produced by the server is the area of the circle (use java.net).

import java.net.*;
import java.io.*;
import java.util.*;
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(8080);
Socket s=ss.accept();
Scanner c=new Scanner(s.getInputStream());
double r=c.nextDouble();
double a=Math.PI*r*r;
PrintStream p=new PrintStream(s.getOutputStream());
p.println(a);
s.close();
p.close();
}
}

RAKESH.C.M Page 222


import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",8080);
Scanner c=new Scanner(System.in);
System.out.println("Enter radius of a circle");
double r=c.nextDouble();
PrintStream p=new PrintStream(s.getOutputStream());
p.println(r);
c=new Scanner(s.getInputStream());
double area=c.nextDouble();
DecimalFormat df=new DecimalFormat("0.00");
System.out.println("Area of a circle="+df.format(area));
s.close();
p.close();
}
}

Address Identifiers

When the data is required to transmit or received over the network, first the
server is required to identify the address of the client. More clients have common
system names, but addresses are different. Two types of classes called URI
(Uniform Resource Identifier) and URL (Uniform Resource Locator) identify system
unique addresses.

URL:

URL provides a powerful mechanism to identify the uniquely address systems


over the web. Java provides URL Class to provide the facilities provided by the
URL. Example for URL format is as follows: URL specification is based on four
components.
http://www.osborne.com/
http://www.osborne.com:80/index.html

first component is the protocol, rest of the locator are separated by colon.
Commonly used protocols are http, ftp, gopher and file etc.,
second component is the hostname or IPAddress of the host, this delimited on
the left by double slashes (//)
third component is the port number, default port number of http protocol is 80
fourth component is the file path

RAKESH.C.M Page 223


Java’s URL class has several constructors. Most commonly used constructor
is:
URL(Stirng str)

// Example program

import java.net.*;
class url
{
public static void main(String[] args) throws Exception
{
URL obj=new URL("http://www.google.co.in/download");
System.out.println(obj.getProtocol());
System.out.println(obj.getHost());
System.out.println(obj.getFile());
System.out.println(obj.getPort());
System.out.println(obj.toExternalForm());
}
}

//O/P: http
www.google.co.in
/download
-1
http://www.google.co.in/download

URLConnection:

URLConnection is a general purpose class for accessing the attributes of a


remote resources. We want to access the actual bits or content information of URL,
we create a URLConnection object from it, using its openConnection() method as
url.openConnetion();

URLConnection class defines several methods as:

1. int getContentLength(): returns the size of the content associated with


the resource. If the length is unavailable, -1 is returned
2. long getDate(): returns time and date of the response represented in
terms of milliseconds
3. long getExpiration(): returns the expiration time and date of the
resource represented in terms of milliseconds
4. long getLastModified(): returns the time and date represented in terms
of milliseconds of the last modification of the resource

RAKESH.C.M Page 224


// Example program

import java.net.*;
import java.util.Date;
class urlconnection
{
public static void main(String[] args) throws Exception
{
URL obj=new URL("http://www.google.co.in/download");
URLConnection uc=obj.openConnection();
System.out.println("Type:"+uc.getContentLength());
long d=uc.getDate();
if(d==0)
System.out.println("Not available");
else
System.out.println("Time:"+new Date(d));
}
}

DATAGRAMS

When the data is passed to TCP/IP style of networking, it provides serialized,


predictable, reliable stream of packet data. But TCP includes many complicated
algorithms for dealing with congestion control over networks, about the loss of data.
This leads to transport data. To avoid it another alternative is Datagrams.
Datagrams are bundles of information passed between machines. Collection
of data is considered as a Datagram. It is a hard process. Once the datagram has been
released to the target, there is no assurance whether the datagram is reached to the
target or not. When the datagram, is received, there is no assurance that it hasn’t
damaged in transmission.
UDP Protocols are used the way of transmission the data in terms of
datagrams. For this the provided classes are:

DatagramPacket and DatagramSocket.

DatagramPacket objet is the data container, while the DatagramSocket is


the mechanism to send or receive the DatagramPackets.

DatagramSocket defines four public constructors. They are:

DatagramSocket() throws SocketException


DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ip) throws SocketException
DatagramSocket(SocketAddress ad) throws SocketException

Methods:
1. void send(DatagramPacket pc) throws IOException
2. void receive(DatagramPacket pc) throws IOException

RAKESH.C.M Page 225


DatagramPacket class is used to create datagram packets of given data. It defines
the following constructors:

DatagramPacket(byte data[], int size)


DatagramPacket(byte data[], int offset, int size)
DatagramPacket(byte data[], int size, InetAddress ia, int port)
DatagramPacket(byte data[], int offset, int size, InetAddress ia, int port)

The first constructor specifies a buffer that will receive data, and the size of the packet
The second form allows to specify an offset into the buffer at which data will be
stored
The third form specifies a target address and port to which packets of data will be sent
The fourth form transmits packets beginning at the specified offset into the data

Methods:

1. InetAddress getAddress(): returns the InetAddress, typically used


when sending
2. int getPort(): returns the port number
3. byte[] getData(): returns the byte array of data contained in the
datagram
4. int getLength(): returns the length of the valid data contained by the
byte array.

// EXAMPLE PROGRAM FOR DATA GRAMS

UDP CLIENT

import java.net.*;
import java.io.*;
import java.util.*;
class udpclient
{
public static void main(String args[])
{
try
{
DatagramPacket dp;
String strline,text;
InetAddress ia=InetAddress.getLocalHost();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the string:");
strline=dis.readLine();
byte[] data=new byte[strline.length()];
strline.getBytes(0,strline.length(),data,0);
dp=new DatagramPacket(data,data.length,ia,100);
DatagramSocket ds=new DatagramSocket(101);
ds.send(dp);
System.out.println("data sent");

RAKESH.C.M Page 226


data=new byte[1024];
dp=new DatagramPacket(data,data.length);
ds.receive(dp);
text=new String(dp.getData(),0,0,dp.getLength());
System.out.println(text);
}
catch(UnknownHostException e)
{
System.out.println(e);
}
catch(SocketException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

UDP SERVER

import java.net.*;
import java.io.*;
class udpserver
{
public static byte[] msg=new byte[1024];
public static void main(String args[])
{
String str;
try
{
InetAddress ia=InetAddress.getLocalHost();
DatagramPacket dp=new DatagramPacket(msg,msg.length);
DatagramSocket ds=new DatagramSocket(100);
ds.receive(dp);
str=new String(dp.getData(),0,0,dp.getLength());
System.out.println(str);
byte[] data=new byte[str.length()];
str.getBytes(0,str.length(),data,0);
dp=new DatagramPacket(data,data.length,ia,101);
ds.send(dp);
}
catch(SocketException e)
{
System.out.println(e);
}

RAKESH.C.M Page 227


catch(IOException ie)
{
System.out.println(ie);
}
}
}

ENUMERATIONS

Enumeration refers to a list of named constants. In JDK5, enumerations were


added to the Java language. Java enumerations appear similar to enumerations in
other language.
In C++, enumerations are simply a list of name constants. In Java, an
enumeration defines a class type. i.e., an enumeration can have constructors, methods
and instance variables.
An enumeration is created by the enum keyword.

Syntax: enum Tag


{
Member1, Member2, …. , Membern;
}
Here,
Member1, … , Membern are called enumeration constants. Each is implicitly
declared as a public, static final members.

Example: enum Apple


{
Jonathan, GoldenDel, RedDel, WineSap;
}

After defining an enumeration, we are able to create a variable of enum type.


For this, use the syntax as:

Syntax: Tag Variable;


Example: Apple Ap;

Ap is of the Apple. So, that Ap values can be assigned only with those are
defined by the enumeration.

Ex: Ap = Apple.RedDel;

Note:

1. Two enumeration constants can be compared for equality using the


= = relational operator.
2. An enumeration value can also be used to control a swithch statement.

RAKESH.C.M Page 228


// EXAMPLE PROGRAM FOR ENUMERATION

enum Days
{
MON, TUE, WED, THU, FRI, SAT, SUN;
}

class EnumDemo
{
public static void main(String[] args)
{
Days d;
d=Days.WED;
System.out.println("Value of d="+d);

d=Days.FRI;
if(d==Days.FRI)
System.out.println("EQUAL");

switch(d)
{
case MON:System.out.println("DAY 1");
break;
case TUE:System.out.println("DAY 2");
break;
case WED:System.out.println("DAY 3");
break;
case THU:System.out.println("DAY 4");
break;
case FRI:System.out.println("DAY 5");
break;
case SAT:System.out.println("DAY 6");
break;
case SUN:System.out.println("DAY 7");
break;
}

}
}

RAKESH.C.M Page 229


AUTOBOXING

In JDK5, Java added two important features:

Autoboxing
Auto-unboxing

Autoboxing is the process by which a primitive type is automatically


encapsulated (boxed) into its equivalent type wrapper whenever an object of that type
is needed. There is no need to explicit construct an object.

Auto-unboxing is the process by which the value of a boxed object is


automatically extracted (unboxed) from a type wrapper when its value is needed.
There is no need to call a method such as intValue() or doubleValue().

// Demonstarte autoboxing / unboxing

class AutoBox
{
public static void main(String args[])
{
Integer x = 100; // autobox an int
int i = x; // auto-unbox
System.out.println(x+” “+i);
}
}

In addition to the simple case of assignments, autoboxing / unboxing might


occur when an argument is passed to a method, or when a value is returned by a
method.

// Example

class AutoBox2
{
static int m(Integer v)
{
return v; // auto-unbox to int
}
public static void main(String[] args)
{
Integer iob=m(100); // autobox into Integer
System.out.println(" "+iob);
}
}

RAKESH.C.M Page 230


ANNOTATIONS

In JDK5, a new facility was added to Java that enables us to embed


supplemental information into a source file. This information is called an annotation,
which does not change the actions of the program.
The term metadata is also used to refer this feature, but most commly used
term is annotation.
An annotation is created through a mechanism based on the interface.

Example: @interface MyAnno


{
String str();
int val();
}

For creating annotations, @ precedes the keyword interface. It contains only


method declarations. These methods are implemented by the Java classes whose used
this interface.

GENERICS

Generics means parameterized types. Parameterized types are enable us to


create classes, interfaces, and methods in which the type of data upon which they
operate is specifed as a parameter. A class, interface, or method that operates on a
parameterized type is called generic, as in generic class or generic method.

The general form of creating a generic class is:

Syntax: class classname <typelist>


{
--
--
}

The Syntax for declaring a reference to a generic class is:

Syntax: classname <typelist> varname = new classname<typelist>(arglist);

// Example program for creating a generic class

class Two<T,V>
{
T ob1;
V ob2;
Two(T x,V y)
{
ob1=x;
ob2=y;
}

RAKESH.C.M Page 231


void showTypes()
{
System.out.println("Type of T is:"+ob1.getClass().getName());
System.out.println("Type of V is:"+ob2.getClass().getName());
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
class Simple
{
public static void main(String[] args)
{
Two<Integer,String> t=new Two<Integer,String>(88,"GENERICS");

t.showTypes();

int p=t.getob1();
System.out.println("Value 1:"+p);
String q=t.getob2();
System.out.println("Value 2:"+q);
}
}

// O/P:

Type of T is: java.lang.Integer


Type of V is: java.lang.String
Value 1: 88
Value 2: GENERICS

// Example program for creating generic methods

class MethDemo
{
static <T,V extends T>boolean isIn(T x,V[] y)
{
for(int i=0;i<y.length;i++)
if(x.equals(y[i]))
return true;
return false;
}
public static void main(String[] args)
{
Integer nums[]={1,2,3};
if(isIn(2,nums))
System.out.println("EXIST");

RAKESH.C.M Page 232


else
System.out.println("NOT EXIST");
}
}

// Example proram for generic constructors

class GenDemo
{
private double val;
<T extends Number>GenDemo(T arg)
{
val=arg.doubleValue();
}
void showVal()
{
System.out.println("Value:"+val);
}
}
class GenCons
{
public static void main(String[] args)
{
GenDemo gd1=new GenDemo(100);
GenDemo gd2=new GenDemo(123.5F);
gd1.showVal();
gd2.showVal();
}
}

THE END

RAKESH.C.M Page 233

You might also like