Sunteți pe pagina 1din 272

UNIT-1

1. Introduction to OOP:
 OOP Stands for Object Oriented Programming.
 The main aim of OOPs is to design the object oriented programming languages (OOPL).
 If any language supports all the OOPs principles is known as object oriented programming languages.
Examples: C++, JAVA, PHP, .NET, Python, Android, Selenium, Hadoop. Etc.
 The main objective of OOP is to store the client input data in the form of “Objects” instead of
functions and procedures.
 In OOPs, every object has data and behavior (methods), identify by a unique name, which achieves
through class and happened at object creation.
 OOP is focuses mainly on classes and objects.
 OOPs mainly used to develop System Softwares like driver softwares, operating system, compiler
softwares, interpreter softwares etc.

1.1 Advantages of OOP:


 Code Reusability:
1) In object-oriented programming, one class can easily move to another application if we want to use
its properties.
2) For example, a client already having account in Facebook and now he want to register in LinkedIn
application. By using his Facebook credentials, he can register in LinkedIn application, instead of a
separate registration. Therefore, write once and use anywhere leads to re-usability.
 Easily identify the bug:
1) When we are programing with procedural programming language takes a lot of time to identify
errors and resolve it.
2) But in object Oriented Programming due to modularity of classes we can easily identify the errors.

2. Procedural Programming Language Vs Object Oriented Language:


2.1 Procedure oriented programming:
 It uses a set of procedures or functions to perform a task.
 When the programmer wants to write a program, he will first divide the task into separate sub tasks,
each of which is expressed as functions.
 If we require any extension to the function then we need to recreate the entire program.
 In C language, the problem is divided in to sub-problems or sub-procedures. These sub-problems are
again divided continuously until the sub-problem is simple enough to be solved and controlled from a
main( ) function. For example: factorial program.

Page 1
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
2.2 Object Oriented Programming:
 Object oriented programming language like C++ and Java uses classes and objects in the programs.
 A class is a module that which contains collection of methods (functions) and data (variables) to
perform a specific task.
 The main task is divided in to several modules and these are represented as classes.
 The method of class that contains the logic to perform operations and variable is used to handle the
client data.
 The Object is a memory holds the end users data as part of main memory.
 The goal of this methodology is to achieve reliability, reusability and extensibility.
 It is easy to modify and extend the features of application, which is possible with Inheritance principle
and no need any recreation.

2.3 Comparison:

Procedure Oriented Programming (POP) Object Oriented Programing (OOP)


1) A program is divided in to sub problems 1) A Program is divided in to parts or modules
called as functions. called as objects.
2) It follows Top Down approach 2) It follows Bottom Up Approach
3) In POP, the operations are carried out 3) In OOP, the operations are carried out
through functions. through data rather than functions.
4) It has access specifiers names as public,
4) It does not have access specifiers.
private, etc.
5) Adding new functions leads to recreation
5) It is easy to add new data and methods.
and not easy also.
6) In POP, Data can move freely from 6) In OOP, objects can move and communicate
function to function in the system by usingwith each other through access specifiers
global data sharing. otherwise, it is not possible.
7) In OOP, Overloading is possible in the form
7) In POP, Overloading is not possible.
of function and operator overloading.
8) In POP, it does not have any feature to 8) In OOP, Data Abstraction / Hiding provides
hide the data. It is less secured. more securable.
9) Examples: C, FORTAN, COBOL, etc. 9) Examples: C++, JAVA, .NET, Python, etc.

Page 2
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3. OOPS Principles (Features):
 Object Oriented Programming Structure (OOPS) is a concept with collection of principles named as
follows:
1) Class/Object
2) Encapsulation
3) Data Abstraction
4) Inheritance
5) Polymorphism

3.1 Class/Object:

3.1.1 Object:

 Object is a memory that holds the end users data as a part of main memory (RAM).
 Every object has properties and can perform certain actions.
 The properties can be represented by variables in our programming.
For example: String name; int age; char sex;
 The actions of object are performed by methods. For example, ‘Ravi’ is an object and he can perform
some actions like talking( ), walking( ), eating( ). etc.
 So an object contains both variables and methods.

Advantages of storing the data in the form of object:

1. Security: It provides to the data from un-authenticated users.

2. Data can be identified and accessed very easily.

3.1.2 Class:

 Class is a container with collection of variables and methods.


 Variables are used to handle the clients input data.
 Method can contain the logic to perform operations for specific task.
 A class is created by using the keyword ‘class’.
 A class describes the properties and actions performed by its objects.
 A java program can have many numbers of classes and every class should be identified with a unique
class name.

Page 3
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 It is mandatory to write every java program in the form of class then only JVM allows us to store the
end users data in the form of objects.

Syntax of class:

class classname
{
// List of variables
// List of Methods
}
Example of class:

class Person
{
String name;
int age;
char sex;

void talk( )
{
------
------
}
void eat( )
{
------
------
}
void walk( )
{
------
------
}
}

 In the above example, a person class has 3 variables and 3 methods. This class code stored in JVM’s
method area. When we want to use this class, we should create an object to the class as follows:

3.1.3 Object creation Syntax:


 In the real time, memory is not allocated for properties (variables and methods) of class at the time
writing of the program and compilation of the program.
 The memory is allocated at run time based on the object creation syntax.
 JAVA supports “new” keyword to create a new object for a given class in two ways.

Syntax 1: classname reference = new classname( ); // referenced object

Syntax 2: new classname( ); // unreferenced object

 The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
 The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before
executing the next time. So that it is highly recommended to access a single method of the class at a
time.
Page 4
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
 ‘Referenced’ and ‘unreferenced’ object is created by JVM in main memory based on its syntax.
 In the above syntax 2, JVM will create a new object for the properties of the given class.
 In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.

Examples of object creation:

1) Person raju = new Person( ); // object creation of syntax 1.

2) new Person( ); // object creation of syntax 2.

Examples of object calling:

1) raju.walk( );
2) raju.talk( );
3) new Person( ).walk( );

 In the above figure, multiple users are sending the request to the Banking application and the data will
be stored in the main memory in the form of objects and later it will be stored in the secondary
memory (Database).
 Note: Without storing the data in the temporary memory, it will never be stored in the permanent
memory.

Page 5
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3.2 Encapsulation:

 Encapsulation is a mechanism of combining the state and behavior in a single unit.


 The state represents the data and behavior represents the operation.
 In JAVA, encapsulation can be achieved by using “class” keyword.
 The variables and methods of a class are known as “members” or “properties” of the class.
 Generally, the variables in the class are declared by using a keyword ‘private’. This means the
variables are not directly available to any other classes.
 The methods of a class are declared as ‘public’. This means the methods can be called and used from
anywhere outside the other classes.
 To use the variables from outside, we should take the help of methods. There is no other way of
interacting with the variables.
 This means outsiders do not know what variables declared in the class and what code is written in that
method. Since encapsulation provides a protective mechanism for the members of the class.

Example: Write a java class that the variables of the class are not available to any other program.

class Person
{
//variable declarations
private String name = “Vignan”;
private int age = 2002;
//Method
public void talk( )
{
System.out.println(“ Hello, I am” +name);
System.out.println(“ My year of establishment is:” +age);
}
}

3.3 Data Abstraction:


 A class contains lots of data and the user does not need the entire data.
 The user requires only some part of the available data. In this case, data abstraction is used to hide the
un-necessary data from the user and un-hide the necessary data to the user.
 This concept called as “Data Abstraction”.
 In JAVA, Data Abstraction can be achieved by using ‘class’ keyword.
 The advantage of abstraction is that every user will view their data according to own requirements.

Example: Write a java class to describe data abstraction.

class Customer
{
String name;
int accno;
float bal;
int mobno;
String email_id;
String addr;

Page 6
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void fundsTransfer( )
{
---------------
---------------
}

void updateContactDetails( )
{
---------------
---------------
}
}

 In the above program, the variables ‘accno’ and ‘bal’ are necessary for fundsTransfer( ) method and
the remaining variables are not necessary (hidden).
 The variables ‘mobno’, ‘email_id’ and ‘addr’ are necessary for updateContactDetails( ) method and
the remaining variables are not necessary.

3.4 Inheritance:

 Creating or deriving a new class from the existing class is known as “Inheritance”.
 So a new class can acquires the properties of the existing class and its own properties also.
 In JAVA, Inheritance can be achieved by using “extends” keyword.
 The class which is giving the properties is known as “parent/base/super” class.
 The class which is acquiring the properties is known as “child/sub/derived” class.

 The advantages of using inheritance are Code Re-usability, Re-Implementation and Extensibility.

Example: Write a java class to describe nature of Inheritance.

class A
{
int a;
int b;
void method1( )
{
// method body
}
}

class B extends A
{
int c;

Page 7
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void method2( )
{
// method body
}
}

3.5 Polymorphism:
 In java point of view, if the same method name is existed multiple times with different implementation
(logic) is known as “polymorphism”.
 It can be categorized into two types: Static Polymorphism and Dynamic Polymorphism.
3.5.1 Static Polymorphism:
 Whatever the method is verified at compile time and the same method is executed at runtime by
following polymorphism principle is known as “static polymorphism/compile time
polymorphism/static binding”.
 In JAVA, static polymorphism can be achieved by using overloading.
Example: A java class on method overloading
class A
{
void f1(int x)
{
---------
---------
}
void f1(float y)
{
---------
---------
}
}
3.5.2 Dynamic Polymorphism:
 Verifying super class method at compile time and executing derived class method at runtime by
following polymorphism principle is known as “Dynamic polymorphism or Runtime
polymorphism or late binding”.
 In JAVA, Dynamic polymorphism can be achieved by using overriding.
Example: A java class on method overriding
class A
{
void f1(int x)
{
---------
---------
}
}
class B extends A
{
void f1(int x)
{
---------
---------
}
}

Page 8
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4. Introduction to Software:
Def of software:
 Software is a collection of programs. A program is a collection of instructions used to perform an
operation.
 Either programs or softwares can be designed by using programming languages.
 Examples: C, C++, JAVA, VC++, .NET etc.
Types of softwares:
 Software is divided in to two categories. 1) System Software 2) Application Software
4.1 System Softwares:
 These are the softwares can be designed for physical hardware devices (embedded systems).
 In real time, these softwares are mostly designed by using C/C++.
 Examples: operating system, compilers, system drivers. Etc.
4.2Application Softwares:
 These are the softwares can be designed for end users and these are again categorized into two types
named as:
a) Standalone (or) Desktop applications
b) Distributed (or) Internet based applications.
 In real time, these softwares are mostly designed by using JAVA.
4.2.1 Standalone (or) Desktop applications:
 These applications runs in a single computer and whose results are not sharable in multiple other
computers.
 In real time mostly these are designed by using ‘.NET’ language.
 Examples: Media player, M.S. office, calculator applications, etc.
4.2.2 Distributed (or) Internet based applications:
 This is an application runs in a single computer but whose results can be shared in multiple other
computers.
 These distributed applications are again divided in to two: Web applications and Enterprise
applications.
 Web Application: This is an internet based application designed commonly for every end user in the
world. Examples: Facebook, YouTube, google, etc.
 Enterprise application: This is an internet based application designed for specific organizations,
which means only limited end users can access these applications. Examples: Banking applications,
income tax applications, company mailing applications, etc.

Page 9
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 So finally java is a universal programming language can be used to design any of above softwares. But
it is very famous to design internet based applications.

5. History of JAVA:

 JAVA is a programming language used to design the softwares; the main purpose of software is to
perform business-oriented operations in very less time.
 Examples: Operating bank operations through online, searching a job through online, purchasing a
product through online etc.
 Java was originally initiated in the year 1991 and it is designed by “Mr. James Gosling” and his team
members ‘Mr. Bill Joy’, ‘Mr. Mike Sheradin’, ‘Mr. Patrick’. N in the year 1995 at “SUN MICRO
SYSTEMS” named as JAVA 1.0.
 The initial name was Oak but it was renamed to Java in 1995.
 Right now SUN MICRO SYSTEMS was taken over by “ORACLE CORPORATION”.
JAVA 1.0:
 In 23rd Jan 1996, Java Development Kit (JDK) 1.0 was released for free by the SUN
MICROSYSTEMS and named as OAK. It includes predefined 8 packages and 212 classes.
 MICRSOFT and other companies licensed JAVA.
JAVA 1.1:
 In 19th Feb 1997, JDK 1.1 was released with predefined 23 packages and 504 classes. It includes the
features of inner classes, event handling, improved JVM, AWT, JDBC, JAVA Bean Classes etc.
 Microsoft developed its own 1.1 compatible JVM for internet explorer.
JAVA 1.2 (J2SE):
 In 8th Dec 1998 JDK 1.2 was released with predefined 59 packages and 1520 classes.
 It includes the features of Swings for improved graphics, JIT Compiler and Multithread methods like
suspend( ), resume( ) and stop( ) of Thread class.
 JAVA API includes collection frameworks such as list, sets and hash map.

JAVA 1.3:
 In 8th May 2000 JDK 1.3 was released with predefined 76 packages and 142 classes.
 It includes the features of JAVA Sound (input and output of sound media), Java Naming and Directory
Interface (JNDI) and Java Platform Debugger Architecture (JPDA), etc.
JAVA 1.4:
 In 6thFeb 2002 JDK 1.4 was released with predefined 135 packages and 2991 classes.
 It includes the features of XML support, ‘assert’ keyword, Regular Expressions, Exception Handling,
Reading and writing image files etc.
JAVA SE 5 (Java 1.5):
 In 30thSep 2004, JSE5 was released with predefined 165 packages and 3000 classes.
 It includes the features of Generics, Annotations, Metadata, Auto boxing, Un-boxing, improved
collection framework, formatted I/O, for-each loop, Concurrency utilities etc.
JAVA SE6:
 In 11thDec 2006, Java SE6 was released with features of scripting language support, JDBC 4.0
support, JVM improvements including Synchronization and compiler performance optimizations,
Garbage collection algorithms, etc.

Page 10
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
JAVA SE 7:
 In 28thJul 2011, Java SE7 was released with features of JVM support for dynamic language, new
library for parallel computing on multi core, compressed 64 bit pointers, Automatic resource
management, Multi-catch Exception, underscore in numeric literals etc.
JAVA SE 8:
 In 18thMar 2014, Java SE8 was released with features are lambda expressions, Enhanced security,
JDBC-ODBC bridge has been released etc.
5.1 Parts of JAVA:
 SUN Micro Systems has divided java into 3 parts named as Java SE, Java EE and Java ME.
Java SE:
 It is known as “Java Standard Edition”. It is used to develop basic java classes, standalone
applications, simple network based applications, standard APPLETS.
Java EE:
 It is known as “Java Enterprise Edition”. It is used to develop Internet based applications on
providing business solutions.
Java ME:
 It is known as “Java Micro Edition”. It is used to develop portable applications such as PDA or
Mobile devices. Code on these devices needs to be small in size and should take less memory.

5.2 Key Points:


 Up to 8 versions, java EE contains more than 35 modules and these are used to design very efficient
and secured internet based applications.
 From Java 2.0 onwards java becomes the “technology” and from java 5.0 onwards it becomes
“Framework”.
 The main difference between programming language, technology and framework is all are almost
same but difference can found in its library size.
 Programming language supports max 10% of library, Technology supports min 40% of library and
Framework supports min 80% of library sizes.

6. JAVA Features:
 Java is very famous in the market even multiple other programming languages are available because of
following features.
1) Simple
2) Object Oriented
3) Platform Independent
4) Architectural Neutral
5) Robust
6) Multi-Threaded
7) High Performance
8) Dynamic
9) Distributed
10) Secured

6.1 Simple:
 Java is easy to learn and its syntax is quite simple, clean and easy to understand.
 The ambiguous concept of C++ has been re-implemented in java in a clear way.
 Java is simple programming language because of following reasons:-

Page 11
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) It supports very huge API (Application Program Interface) also known as java library. So that
application development becomes very easy and burden on the developer is reduced.
2) Java is free from pointers. It means java makes the developer free from writing of pointer code.
Therefore, the burden on the developer and code complexity is reduced.
 Note: Java supports pointers and it will be handled internally / implicitly by the JVM.
 Every java program can be written in simple English language. So that it is easy to understand by
developers.

6.2 Object Oriented:


 Java is object oriented language which means java programs uses objects and classes. An object which
contains data and behavior.
 Java can be easily extended as it is based on ‘Object’ model.

6.3 Platform Independent:


 Generally platform means “Operating System” (O.S).
 Java is a platform independent language, which means java program can be executed in any
operating system even that program was developed and compiled in other O.S.
 Java follows “Write Once and Run anywhere” slogan.
 After compilation, java program is converted in to ‘byte code’. This bytecode is platform
independent and can be run on any machine with secured manner.
 Any machine, which is having “Java Runtime Environment” (JRE), can run java programs.

6.4 Architectural Neutral:


 Java is a processor independent language that means java program can be executed by any processor
even that program was developed and compiled in other processor.

Page 12
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
6.5 Robust:
 Java is very strong because of exception handling mechanism.
 If any error is generated at that time of compilation of program is known as “Compile time error /
Syntax error”. These errors are raised because of violating the syntax rules given by programming
languages. Example: Semicolon missing, writing keyword in uppercase, etc.
 If any error is generated at run time is known as “Run time error / Exception”. Generally these are
raised because of providing invalid inputs by the end user.

 Whenever exception is raised system defined / generated error message will be given to the end user, it
is unable to understandable. So that this message must be converted into user friendly message.
 Exception Handling is a mechanism used to convert system defined error message into user friendly
error message.
 In java it can be achieved by using “try-catch”.

6.6 Multi-Threaded
 Java is a multi-threaded programming language. It means if the same program of same application
running simultaneously is known as “Multi-Threading”.
 In the end user point of view, thread is a request.
 In java point of view, thread is a “flow of execution”.
 The main advantage with multi-threading is end users waiting time is reduced while performing
business oriented operations.

6.7 High Performance


 Java is very high performance language because of following reasons:
1) By using Multi-threading, end users waiting time is reduced so that performance will be increased.
2) By using “Garbage Collector”, wastage of memory space is reduced so that performance is
increased.

Page 13
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Garbage Collector: It is a predefined method in Java, runs automatically in the background of every
java program and deallocates un-used memory spaces.

6.8 Dynamic
 Java is dynamic because of supporting “Runtime memory allocations”.
 If the memory is allocated for input data at the time of compilation of program is known as “compile
time memory / static memory”.
 If the memory is allocated for input data at the time of running of the program is known as “Dynamic
memory”.
 Java strictly supports only “Dynamic Memory”.

6.9 Distributed:
 Java is distributed. It means it supports to design distributed applications / network based applications
and it supports distributed architecture.
 Based on the distance between the computer networks are categorized into LAN, MAN, WAN and
Internet.
 Java supports to design all network categories based on two architectures.
1) Client-Server architecture
2) Distributed architecture.
Client-server Architecture:
 In this architecture, multiple client machines depend on single server machine.
 Client always sends the request to the server whereas server always gives the response to the client.

 If any problem is occurred at server machine that will reflected on every client machine. This problem
is leads to “server down”.

Distributed Architecture:
 In this architecture, multiple client machines depend on multiple server machines.
 The main advantage is even if the problem is occurred at one server machine that won’t be reflected on
any client machine.
 All client requests are shared to multiple server machines based on its distance.
 Java supports to develop internet based applications. This architecture is mostly used in real time.

Page 14
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
6.10 Secured:
 Java is more secured programming language among all other languages because of following reasons.
 It is virus free programming language, which means if any application is designed by using java
language that does not allows virus in to the computer.
 Java provides security to the applications in two ways. 1) Internal security 2) External security.
 Internal Security: A security is provided by the data within the application is known as Internal
security. It can be achieved by OOPS.
 External Security: Whenever security is provided to data by the outside applications is known as
external security. It can be achieved by Encryption and Decryption.
 Encryption: Converting plain text into cypher text is known as encryption.
 Decryption: Converting cypher text in to plain text is known as decryption.
 Java supports all encryption and decryption techniques so that it provides high level external security
for the data.

7. Java Virtual Machine (JVM) Architecture:

 JVM is a software available as a part of JDK software and it is a heart of entire Java program
execution process.
 JVM is a platform dependent software mainly used to perform following operations:
1) Allocates sufficient memory space for the properties of class in main memory (RAM).
2) It takes the ‘.class’ file as an input and converting each byte code instruction in to the machine
language instruction that can be executed by the processor.

Page 15
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 First ‘javac’ converts the source code instructions in to ‘byte code’ and after successful compilation a
new ‘.class’ file will be created.
 Now the ‘.class’ file is given to the JVM as an input and it converts in to machine level instructions.
 The architecture of JVM is as follows:

7.1 Class Loader Sub System:

 In JVM, there is a module called “class loader sub system”, which performs the following functions:
1) First, it loads the “.class” file into main memory for all the properties of the class.
2) Then it verifies whether all byte code instructions are proper or not. If it finds any instruction
suspicious, the execution is rejected immediately.
3) If the byte code instructions are proper, then it allocates necessary memory to execute the program.

7.2 Method area:


 Method area is the method block, in which memory is allocated for the code of the variables and
methods in the java program.

7.3 Heap:
 This is the area where objects are created. In this area, memory is allocated for the ‘Instance Variables’
in the form of objects.

7.4 PC (Program Counter) registers:


 These are the registers, which contains memory address of the instructions of the methods.

Page 16
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
7.5 Java Stacks:
 Java stacks are memory area where Java methods are executed.
 It also allocates the memory for ‘local variables’ and ‘object references’.
 JVM uses a separate thread to execute each method.

7.6 Native Method area:


 In which memory is allocated for the native methods.
 These methods contain other than java language code like c, C++, .Net. Etc.
 To execute native method, generally native method libraries are required. These header files are
located and connected by the JVM by using ‘Native method interface’.

7.7 Execution Engine:


 It contains two components named as Just in Time (JIT) Compiler and Interpreter.
 These components are responsible for converting the byte instructions into machine code so that the
processor will execute them.
 Most of the cases JVM use both JIT compiler and interpreter simultaneously to convert the byte code.
This technique is called “Adaptive Optimizer”.
 Interpreter is responsible to convert one by one ‘byte code’ instructions into ‘machine level
instructions’ and it always comes into the picture while sending the first request to java program.
 JIT Compiler always appears from the second request onwards; it will collect all the ‘machine level’
instructions that are already converted by the interpreter and gives to processor.
 The main advantage with JIT compiler is it will increase the execution speed of the program.

8. Difference between C++ and JAVA

C++ JAVA
1) C++ is platform dependent. 1) JAVA is platform independent.
2) It is mainly used to develop system 2) It is mainly used to develop application
softwares. softwares.
3) It is not a purely object oriented
3) It is a purely object oriented programming
programming language, since it is possible to
language, since it is not possible to write a
write C++ programs without using class or
java program without using class or object.
object.
4) Pointers are available in C++. 4) Java is free of pointers creation.
5) Allocation and deallocating memory is the 5) Allocation and deallocating memory will
responsibility of the programmer. be taken care of JVM.
6) C++ has goto statement. 6) C++ doesn’t have goto statement.
7) In some cases, implicit casting is available.
7) Automatic casting is available in C++. But it is advisable to the programmer should
use casting wherever required.
8) Multiple Inheritance feature is available in 8) Java doesn’t support Multiple Inheritance
C++. in class level. It can be achieved by interfaces.
9) Operator overloading is available in C++. 9) It is not available in java.
10) #define, typedef and header files are
10) These are not available in java.
available in C++.
11) C++ uses compiler only. 11) Java uses compiler and interpreter both.
12) C++ supports constructors and destructors. 12) Java supports constructors only.

Page 17
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
9. Structure of Java Program
9.1 Comments:
 Writing comments is compulsory in any program. In java, there are three types of comments named as
single line, multi line and Java documentation.
1) Single line comments: These comments are used for marking a single line as a comment. These
comments starts with double slash symbol // until the end of the line.
Example: //Hello java programmer.
2) Multi line comments: These comments are used for representing several lines as comments. These
comments starts with /* and end with */.
Example: /* this multi line comment.
Hello java */
3) Java documentation comments: These comments starts with /** and ends with */. These are used
to provide description for every feature in a java program in JAVA API document.
Example: /** Description about a class */.

9.2 Java API (Application Programming Interface):


 Java API document is an ‘.html’ file that contains description of all the features of a technology and it
is helpful for the developer to understand how uses the technology.
 The sample pics of Java API accessing is as follows:

Page 18
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
9.3 example of java program structure

import packagename;
class ClassName1
{
List of variables;
List of methods;
}
class ClassName2
{
List of variables;
List of methods;
}
class MainClass
{
Public static void main(String args[])
{
-------
-------
}

9.4 Import statement:


 It is used to import the predefined Java API properties in the current java program by using the
‘import’ keyword.
 Java API is a collection of Packages.
 Package: A package is kind of directory which contains all the predefined classes and interfaces. A
class is collection of variables (to handle the input data) and methods ( to write the logics).

 A package is a container in which all related classes are available.


 Every java program must be written in the form of ‘classes’ only.
 One java program can have any number of classes but every class must be identified with a unique
name called “class name”.
 ‘#include’ directive makes the compiler go to the C/C++ standard library and copy the code form the
header files in to the program. But ‘import’ statement makes JVM go to the Java standard library,

Page 19
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
execute the code there, and substitute the result into the program. It increases the speed of the
processors time, no waste of memory and no code is copied.

9.5 Main method:


 A class code starts with a ‘{’ and ends with a ‘}’. We can create any number of variables and methods
inside the class.
 Main method is a predefined method can be used to test the java programs in ‘core java’ level.
 ‘main( )’ is the starting point for JVM to start execution of a Java program.
 If any class contains main( ) method is known as “Main class”.
 Every java program must be saved with “mainclass.java”.
 A method which accepts input data from outside and also returns the results. Likewise In main( )
method we having “String args[ ]” to accept groups of strings. It is also called as string type array.

10. Naming conventions in Java:

 “SUN MICRO SYSTEMS” given the following name conventions that must be followed while
writing java programs.

1) Package name must be in ‘LOWER CASE’ letters.


Syntax: a) package packagename; // Used to create a new package
b) import packagename; //Used to import the existing packages.
2) First letter of every word of class name must be in ‘UPPER CASE’ letters.
Example: class StudentDetails
{
----
----
}
3) Constant:
It must be in ‘UPPER CASE’ letters, if it is containing more than one word that must be separated
with UNDERSCORE.
Example: final String COLLEGE_NAME = “VIGNAN”;
-If any variable is preceded with ‘final’ keyword then it becomes ‘constant’. It means whose value
can’t be changed at runtime.
4) Naming of variables is same as that for the method. Except first letter of first word, from the next
word onwards the first letter must be in UPPERCASE for variables, methods and object references.
Example: class StudentDetails
{
int rno;
String studentName;
void insertStudentDetails( )
{
----
----
}
}
5) All keywords should be written in LOWERCASE letters. Example: public, void, static. etc.

 In the above naming conventions are mandatory while accessing predefined properties of Java API
but it is optional while creating user defined properties.
Page 20
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
11. Compilation of Java program:
 Every java program is executed by JVM, but JVM can understand only “Byte Code” instructions.
 ‘Java compiler’ (javac) is responsible to convert the ‘source code’ instructions into ‘byte code’
instructions and also it will identify the ‘syntactical errors’ in the java program.
 ‘Byte code’ instructions represented in the form of “.CLASS” file whereas source code instructions
are represented in the form of ‘.java’ file.
 Syntax to compile a program:
 javac filename.java;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘Java compiler’
to compile the program.
 Syntax to run a program:
After compilation of java program ‘JVM’ will execute the program and gives the result.
 java filename;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘JVM’ to
execute the java program.

Example Programs
Program 1: Write a program to display the message

import java.lang.*;
class Sample1
{
public static void main(String args[])
{
System.out.println(“Welcome to Java Programming”);
}
}
OUTPUT:
 javac Sample1.java
 java Sample1
Welcome to Java Programming

- In the above program 1, it is just to display a string on the monitor.


- ‘System’ is the class name and ‘out’ is a static object in the System class.

Program 2: Write a program to find sum of two numbers


import java.lang.*;
class Sum
{
public static void main(String args[ ])
{
int x,y; //variables declaration
x=10, y=20; //store values in to variables
int z = x+y;
System.out.println(z);
}
}

Page 21
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
 javac Sum.java
 java Sum
30
- In the above program x+y performs the sum operation and the result is stored into z.
- ‘System’ is a class in ‘java.lang’ package and ‘System.out’ creates the PrintStream object which
represents the standard output device.
- System.out.println(z) is used to displays the value on the monitor.

Program 3: Sum of two numbers with formatting the output


class Sum1
{
public static void main(String args[])
{
int x=10, y=20;
int z=x+y;
System.out.println(“sum of two numbers=” +z);
System.out.println(“sum of two numbers=” +x+y);
System.out.println(“sum of two numbers=” +(x+y));

}
}
OUTPUT:
 javac Sum1.java
 java Sum1
sum of two numbers=30
sum of two numbers=1020
sum of two numbers=30

- In the first display statement, “+” is used to join the string “sum of two numbers=” and the numeric
variable ‘z’. It is acting like a concatenation operation.
- In the second display statement, we are having sum of two numbers=” +x+y. Since left one is a string
and the next value of x is also converted in to a string; thus the value of x, i.e. 10 will be treated as
separate characters as 1 and 0 and are joined to string and also for the next variable y is 25. Thus we
get result as 1025.
- In the third display statement, we are having sum of two numbers=” +(x+y). The execution will start
from the inner braces. At left we got ‘x’ and right we got ‘y’, both are numbers and addition will be
done by the + operator, thus giving a result 35.

Page 22
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 4: Examples on System.out.println( ) statements:

Statement Output
1) System.out.println(“Hello”); Hello
2) System.out.println(“ “Hello” ”); Invalid
3) System.out.println(“ ‘Hello’ ”); ‘Hello’
4) System.out.println(“ \”Hello\” ”); “Hello”
5) System.out.println(“ \’Hello\’ ”); ‘Hello’
6) System.out.println(“ Hello \t friends ”); Hello friends
7) int x=10, y=40;
System.out.println(“ x ”); x
System.out.println(x); 10
System.out.println(“ x+y”); x+y
System.out.println(x+y); 50
System.out.println(“10” + “20”); 1020
System.out.println(“x=” +x); x=10
System.out.println(“y=” +y); y=40
System.out.println( x + “ ” +y); 10 20
System.out.println( x +y + “ ”); 30
System.out.println( “ ” +x +y); 1020
8) int rno=1; roll number is: 1
String name = “java”; name of the lab: java
System.out.println(“roll number is:” +rno);
System.out.println(“name of the lab:” +name);
9) System.out.println(“hello”); hello
System.out.println(“friends”); friends
System.out.println(“How are you”); How are you
10) System.out.print(“hello”); hellofriendsHowareyou
System.out.print(“friends”);
System.out.print(“How are you”);

 Double quotations with in double quotations and single quotations with in single are not allowed in
java. But single with in double and double within single are allowed in Java.
 Java supports escape sequences or backslash code to perform special operations:

Backslash code Meaning


\n Next Line
\t Horizontal tab space
\r Enter key
\b Backspace
\f Form feed
\\ Displays \
\” Displays ”
\’ Displays ’

Page 23
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
12. Variables in Java:
 Variable is a container which holds the value while the java program is executed.
 A variable is assigned with the data type.
 A variable is used to identify the data either by the program or developer. So variable is a name of
memory location.
 There are three types of variables in Java. They are:
1) Local variable
2) Static variable
3) Instance / Non-static variable
12.1 Local Variable:

 If a variable defined or declared inside the method is known as “local variable” and also inside the
“formal parameters”.
 Example on Local Variable
void method1( )
{
int x = 10; //local variable
}
 Local variable must be initialized, why because JVM does not assign any default value for the local
variables.
 Example on Formal Parameter
void method1( int x) // formal parameter
{
x = 10;
}
 For local variables memory is allocated at that time of calling the method and memory is deallocated
once the control comes outside the method.
 Local variables can be accessed only with in the same method.
 In real time, it is recommended to define the local variable whenever that variable wants to be used
with in the single method at a time.
12.2 Instance / Non-static Variable:
 If any variable defined outside the method and inside the class without ‘static’ keyword is known as
“Non-static variable” or “Instance Variable”.
 For instance variables memory is allocated whenever a new object is created and memory is
deallocated once object is destroyed.
 Instance variable can be accessed in any method of the same class.
Example:
class A
{
int x; //instance variable
void f1( )
{
x=20;
}
void f2( )
{
x=30;
}
}
Page 24
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In real time, it is highly recommended to define the non-static variable whenever we want to maintain
a separate memory copy for that variable for every new object.

12.3 Static Variable:


 If any variable is defined outside the method and inside the class with ‘static’ keyword is known as
‘static variable’.
 For static variable memory is allocated only once at that time of loading of class and memory is
deallocated once class is un-loaded from the main memory. Probably it is possible when we shut
down the server.
 Static variable can be accessed in any method of the same class.
 Example:
class A
{
static int x; //static variable
void f1( )
{
x=20;
}
Void f2( )
{
x=30;
}
}
 In real time, it is highly recommended to define the static variable whenever we want to maintain a
single memory copy for any object of same class.
 Note: Separate memory copy is required to handle the dynamic input values and common memory
required to handle common data.

12.4 Comparison on life time and scope of variable:

Variable Name Life Scope


1) Local variable Within the same method Within the same method
2) Instance variable Until object is available Anywhere within the same class
Until class is unloaded from
3) Static variable Anywhere within the same class
the main memory

 Whenever variable is declared by default JVM keeps following default values.


Syntax: datatype var_name;
Datatype Default Value
1) byte, short, int, long 0
2) float, double 0.0
3) char Blank space
4) Boolean False
5) String NULL

12.5 Example Program


class Student
{
int rno;
String name;
float marks;
static clgName= “Vignan”;

Page 25
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void insert( )
{
------
------
}
}

13. Data Types in Java:


13.1 Types of inputs:
 End user will provide one or more inputs but these are categorized into following 4 types.

 If any character (alphabet/numeric/special symbol) is enclosed in ‘single quotation’ is known as


“Single character” constant.
 If the set of characters are enclosed in “double quotations” is known as “String type constant”.

13.2 Data Types:

 Def: It is a keyword in java which is used to represent the type of the data and it will tell to the JVM
how much memory should be allocated for the data.
 Data types are categorized in to two types:
1) Primitive data types
2) Reference data types
 Note: Every data type is keyword but not every keyword is a datatype.

Page 26
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
13.2.1 Primitive Data Types:
 These are the data types whose variable can handle maximum one value at a time, these are
categorized into following 4 types:
1) Integer datatype
2) Floating point datatype
3) Character datatype
4) Boolean datatype

 Integer Data Type: It is used to handle integer type of values without any fraction or decimal parts and
these are categorized into following types:

Data Type Size (in Bytes) Range of the data type


1) byte 1 (8 bits) -27to +27- 1
2) short 2 (16 bits) -215 to +215 - 1
3) int 4 (32 bits) -231 to +231 – 1
4) long 8 (64 bits) -263 to +263 – 1

Example: byte rno=10; in this statement we declared a variable of type ‘byte’ for the variable ‘rno’
with the value 10.
 Floating point Data Type: It is used to handle real type of values with fraction or decimal parts and
these are categorized into following types:

Data Type Size (in Bytes) Range of the data type


1) float 4 (32 bits) -231 to +231 – 1
2) double 8 (64 bits) -263 to +263 – 1

Example 1: float pi = 3.142f; in this statement the variable ‘pi’ which contains the value ‘3.142’. If ‘f’
is not written in the end, the JVM would have allocates 8 bytes of memory. The reason which is Java
takes default as ‘double’.
Example 2: Consider double distance = 1.96e8; this deceleration represents the scientific notation. It
means 1.96e8 means 1.96X108.
 Character Data Type:
1) This is used to handle single character values at a time.
2) In java language, it can be represented with ‘char’ keyword.
3) In C-language, char data type occupies 1 byte of memory because of ASCII system. It means it
supports only international langua1ge characters English (256 characters).
4) In java language, char data type occupies 2 bytes of memory because of UNICODE system. It
means character data type in java allows 18 international languages. To store these characters 2
bytes of memory is required.
5) Range of char in java language: -215 to +215 – 1.
 Boolean Data Type:
1) This is used to handle ‘boolean’ values like TRUE or FALSE.
2) It can be represented by using ‘boolean’ keyword.
3) True value always can be stored in the form of ‘1’and false can be stored in the form of ‘0’.
4) So 1-bit of memory is sufficient for boolean type.
5) Example: boolean response = true;

13.2.2 Referenced Data Types:


 It is a data type whose variable can handle more than one value in the form of object.

Page 27
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
13.2.3 String data Type:
 It is used to handle the string type of data in java language and it will be treated as special data type
because of following reasons:
1) There is no fixed size for string data type. Example: “ABC”, “Vignan”… Etc.
2) Based on requirement it may acts a primitive data type or reference data type.
3) String not a keyword in java, it acts as a ‘predefined class’.
4) String is a collection of characters that must be enclosed in “double quotation”.

 Note: The main purpose of maintaining sub data types is for handling efficient memory management.
That means based on the size of input values data type should be changed.

14. Identifiers:

 Identifiers are name of the variable, method, classes, packages and interfaces.
 For example: main, String, args and println( ) are identifiers in java program.
 Identifiers are composed of letters, numbers, underscore, and the dollar ($) sign.
 An identifier name must begin with the letter, underscore and dollar sign.
Example: age =20;
_age=20;
25age = 20; // Illegal
 After the first character, an identifier can have any combination of characters.
 Identifier always should exist in the left hand side of assignment operator.
Example: age = 30;
45 = age; // Illegal
 No keyword should be assigned as an identifier.
Example: break = 15; // Illegal
 In java, the maximum length of the identifier in java should be 32 characters.
 No Spaces are allowed in the identifier declaration;
 Example: my age = 20; // Illegal
 Except underscore ( _ ) no special symbols are allowed in the middle of the identifier name.
Example: my_age = 20;
my@age = 20; //Illegal
my$age = 20; //Illegal

Program 5: A java program to create referenced and un-referenced objects

class Student
{
int rno;
String name;
float marks;

void setData( )
{
rno=1;
name=”james”;
marks=95.6f;
}
Page 28
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void display( )
{
System.out.println(rno);
System.out.println(name);
System.out.println(marks);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student( );
s1.display( )
s1.setData( );
s1.display( );
System.out.println(“………………….”);
System.out.println(“Hello Java”);
s1.display( );
System.out.println(“………………….”);
new Student( ).display( );
System.out.println(“………………….”);
new Student( ).setData( );
new Student( ).display( );
System.out.println(“………………….”);
s1.display( );
s1=null;
s1.display( );
}
}

 OUTPUT: Run this program in your PC for better understanding.

15. Literals in Java:


 A literal represents a value that is stored into a variable in a program.
 Example: boolean result = false;
char gender = ‘M’;
int i = 156;
 In the above examples, the right hand side (RHS) values are called “Literals” because these values are
being stored into the variables shown in the left hand side (LHS).
 As the data type changes then the type of the literal also changes.
 Literals are categorized into various types are as follows:
1) Integer Literals
2) Float Literals
3) Character Literals
4) String Literals
5) Boolean Literals

Page 29
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
15.1 Integer Literals:
 Integer literals represent the fixed integer values like 100, -53, 1235, etc.
 All these numbers belonging to the decimal number system, which use (0 - 9) to represent any number.
Examples:
int dec = 26;
15.2 Float Literals:
 Float literals represents fractional numbers. These are the numbers with decimal points like 2.1, -3.4,
etc, which should be used with float and double type variables.
 Examples:
float f1 = 12.3f;
double x = 123.4;
15.3 Character Literals:
 Character literals includes general characters like A, b, etc., special characters like @, ?, etc, escape
sequences like \n, \t etc.
 These are enclosed in single quotations. But the escaping sequences can also be treated as string
literals.
15.4 String Literals:
 String literals represent objects of “String” class. For example: “Hello”, “Never say die” etc. will
come under string literals, which can be stored directly in the string object.
 These are enclosed in double quotations.
 Example:
String a = “Hello java world”;
15.5 Boolean Literals:
 It represents only two values namely: TRUE and FALSE. It means we can store either true or false
into boolean type variable.

16. Operators in Java:


 An operator is a symbol that performs basic logical operations like arithmetic, relational, increment
operations etc.
 For example: a + b; Here a, b are operands and ‘+’ is an addition operator.
 If an operator acts on a single variable is called as unary operator. If it acts on two variables is called
as binary operator. If it acts on three variables is called as Ternary operator.
 There are many operators that are supported by Java as follows:
1) Unary operator
2) Arithmetic operator
3) Shift operator
4) Relational operator
5) Bitwise operator
6) Logical operator
7) Ternary operator
8) Assignment operator

16.1 Unary operator:


 The java unary operator acts on only one operand.
 These are used to perform increment / decrement a value, negating an expression and inverting the
value of a boolean.

Page 30
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example 1 on unary + + and - -
class Sample
{
public static void main(String args[])
{
int x=10;
System.out.println(-x);
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
OUTPUT:
-10
10
12
12
10
 Example 2 on unary + + and - -
class Sample2
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);
}
}
OUTPUT:
22
21
 Example 3 on !
class Sample3
{
public static void main(String args[])
{
boolean c=true;
boolean d=false;
System.out.println(!c);
System.out.println(!d);
}
}
OUTPUT:
false
true

Page 31
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
16.2 Arithmetic operator:
 These are the operators used to perform fundamental arithmetic operations like addition, subtraction,
multiplication, etc.
 It acts on the two operands at a time, called as binary operators.
 While working with arithmetic operators the result type is depends on the following priorities of
datatypes.
Datatype Priority (High to Low)
1) double 1
2) float 2
3) long 3
4) int 4
5) short 5
6) byte 6
 Examples:
- int + float -> float
- float / double -> double
- byte - short -> short
- long * double -> double
- float % int -> int // remainder should be in integer
- int % int -> int
- float % float -> int
- long % int -> long // long has highest priority
 Example 1: Program on Arithmetic operators
class AirthmeticOperators
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}
}
OUTPUT:
15
5
50
2
0
 Example 2: Program on Arithmetic operators
class SampleArithmetic
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);

Page 32
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
21

16.3 Left Shift operator:


 The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
 Example Program on Left Shift Operator:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
OUTPUT:
40
80
80
240
16.4 Right Shift operator:
 The Java right shift operator >> is used to move left operands value to right by the number of bits
specified by the right operand.
 Example Program on Right Shift Operator:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
OUTPUT:
2
5
2

Page 33
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
16.5 Relational operator:
 These are used to check the conditions, it always returns either TRUE or FALSE.
 The relational operators are of 6 types:
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

 Example Program on Relational Operator:


public class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;

System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
OUTPUT:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

16.6 Logical AND, Bitwise & operator:

 The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.
 The bitwise & operator always checks both conditions whether first condition is true or false.
 Java AND Operator Example 1: Logical && and Bitwise &
class OperatorExample
{
public static void main(String args[ ])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
Page 34
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(a<b&a<c);//false & true = false
}
}
OUTPUT:
false
false
 Java AND Operator Example 2: Logical && vs Bitwise &
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
OUTPUT:
false
10
false
11

16.7 Logical || and Bitwise | operator:


 The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
 The bitwise | operator always checks both conditions whether first condition is true or false.
 Java OR Operator Example: Logical || and Bitwise |
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Page 35
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
true
true
true
10
true
11
16.8 Ternary Operator:
 This operator is can be used on 3 variables, it is also known as ‘conditional operator’;
 Syntax: Expr1? Expr2 : Expr3;
 In the above syntax, expr1 should be a condition, if it is TRUE then expr2 will be executed otherwise
expr3 will be executed.
 Java Ternary Operator Example:
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
OUTPUT:
2
16.9 Assignment Operator:
 Java assignment operator is one of the most common operator.
 It is used to assign the value on its right to the operand on its left.
 Java Assignment Operator Example 1:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
OUTPUT:
14
16

Page 36
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Java Assignment Operator Example 2:
class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}
}
OUTPUT:
13
9
18
9

17. Primitive Type Conversion and Casting


 Assigning a value of one type to a variable of another type is known as ‘Type Casting’.
 In real time, the main purpose of using type casing is to change the client data in to database
understandable format and database data into client understandable format.
 Type casting is categorized in to two: Widening and Narrowing conversion.
 Widening Implicit Conversion:
- If the data types are compatible, then Java will perform the conversion automatically known as
automatic Type Conversion (or) Widening.
- Widening conversion takes place when two data types are automatically converted. This happens
when:
1) The two data types are compatible.
2) When we assign value of a smaller data type to a bigger data type.
 For Example: In java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Page 37
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example Program on Widening Conversion
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
OUTPUT:
Int value 100
Long value 100
Float value 100.0

 Narrowing or Explicit Conversion:

- If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
- This is useful for incompatible data types where automatic conversion cannot be done.
- Here, target-type specifies the desired type to convert the specified value to.

 Example Program on Narrowing Conversion


class Test
{
public static void main(String[] args)
{
double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i);
}
}

Page 38
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
Double value 100.04
Long value 100
Int value 100

18. Control Structures in Java


 Control Structures are used to control the execution flow of logic, in other words it can be used to
achieve random execution.
 These are categorized into following:

18.1 Conditional statements:


 These are used to execute one or more logical instructions based on the condition, these statements are
executed only once.

18.1.1 If Statement:-
 The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
 if statement
 if-else statement
 else-if ladder
 nested if statement
Simple If statement:
 It can be used by performing any operation by checking each and every condition. It executes the logic
if the condition is true.
Syntax:
if(condition)
{
//code to be executed
}
Page 39
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program:
class IfExample
{
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
OUTPUT:
Age is greater than 18

If else statement:
 The Java if-else statement also tests the condition. It executes the code if condition is true otherwise
else block is executed.
 In real time it can be used whenever we want to execute one logic among two logics.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example Program:
class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
OUTPUT:
odd number

Page 40
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
else-if statement:
 In real time it can be used to execute only one logic among multiple logics.

Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}

Example Program:
class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)

Page 41
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

OUTPUT:
c grade

Nested-if statement:
 In real time, if one ‘if-statement’ is existing inside another ‘if-statement’ is known as Nested-if
statement.
 It can be used to improve the efficiency of simple if statement, if-else statement and else-if statement.

Syntax:
if(condtion1)
{
// executes when the condtion1 is true
ifcondtion2)
{
// executes when the condtion2 is true
}
}
Example Program:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
OUTPUT:
X = 30 and Y = 10

Page 42
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
18.1.2 Switch Statement:
 It is same as ‘else-if statement’ used to executes only one logic among multiple logics.
 The only difference between switch and ‘else-if’ is in performance. Switch is better than else-if
statement.
 In ‘else-if’ statement every condition should be verified even to execute last block of statements, it
leads to increase the time consuming process and this problem can overcome using ‘switch’ statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
//code to be executed if all cases are not matched;
}
 ‘Java compiler’ will memorize all the case label name values and it will help to JVM to identify the
case blocks at runtime.
 If no label name is matching with input choice then default block will be executed, default bloack can
exist anywhere in the switch statement.

Example Program 1:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20
Example Program 2:
public class SwitchExample2
{
public static void main(String[] args)
{
int number=20;

Page 43
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
switch(number){
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20
30
Not in 10, 20 or 30
Note: All conditional statements are executed only once.

18.2 Looping statements


 In programming languages, loops are used to execute a set of instructions/functions repeatedly when
some conditions become true. There are three types of loops in java.

 for loop
 while loop
 do-while loop

18.2.1for loop:
 These are used to execute repeatedly based on given range, it can be achieved using for loop.
 The Java for loop is used to iterate a part of the program several times. If the number of iteration is
fixed then it is recommended to use for loop.
 There are three types of for loops in java.
 Simple For Loop
 Nested For Loop
 For-each or Enhanced For Loop
 Labeled For Loop
Simple for Loop:
 The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr)
{
//code to be executed
}
Example Program on for loop:
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
System.out.println(i);
}
}}

Page 44
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
2
3
4
5
6
7
8
9
10

Nested loop:
 If the ‘for loop’ is existed within another ‘for’ loop are called as Nested for-loops.

Syntax:
for(initialization;condition;incr/decr)
{
for(initialization;condition;incr/decr)
{
//code to be inner for loop
}
//code to be outer for loop
}

Example Program on nested for loop:


class NestedForLoop
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; ++i)
{
System.out.println("Outer loop iteration " + i);
for (int j = 1; j <=2; ++j)
{
System.out.println("i = " + i + "; j = " + j);
}
}
}
}
OUTPUT:
Outer loop iteration 1
i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3

Page 45
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

for-each loop:
 The for-each loop is used to traverse array or group of elements in java.
 It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
 It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:
for(Datatype var:array)
{
//code to be executed
}

Example Program on ‘for-each’ loop:


public class ForEachExample
{
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}
OUTPUT:
12
23
44
56
78

Java Labeled For Loop:


 We can have name of each for loop. To do, we use label before the for-loop.
 It is useful if we have nested for loop so that we can break/continue specific for loop.
 Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr)
{
//code to be executed
}
Page 46
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program 1 on labeled for loop:
public class LabeledForExample
{
public static void main(String[] args)
{
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21
Example Program 2 on labeled for loop:
public class LabeledForExample2
{
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21
31
32
33

Page 47
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example Program 3 on infinite for loop:
 If you use two semicolons “;;” in the for loop, it will be infinitive for loop.
Syntax:
for(;;)
{
//code to be executed
}
Program:
public class ForExample
{
public static void main(String[] args)
{
for(;;)
{
System.out.println("infinitive loop");
}
}
}
OUTPUT:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c (To exit out of the program)

18.2.2 While loop:


 These are used to execute one or more logical instructions based on the condition if the range is not
known, these can be achieved by while and do-while loop.
 While loop is an entry controlled loop that means condition is verified before performing operation
only.
Syntax:
while(condition)
{
//code to be executed
}
Example Program 1 on while loop:
public class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=5){
System.out.println(i);
i++;
}
}
}

Page 48
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
2
3
4
5
Example Program 2 on infinite while loop:
 If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true)
{
//code to be executed
}
Program:
public class WhileExample2
{
public static void main(String[] args)
{
while(true){
System.out.println("infinitive while loop");
}
}
}
OUTPUT:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c (To exit out of the program)

18.2.3 do-while loop:


 The Java do-while loop is used to iterate a part of the program several times.
 If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
 The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do
{
//code to be executed
}while(condition);

Example Program 1 on do-while loop:


public class DoWhileExample
{
public static void main(String[ ] args)
{
int i=1;

Page 49
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
OUTPUT:
1
2
3
4
5

Example Program 2 on infinite do-while loop:


 If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Program:
public class DoWhileExample2
{
public static void main(String[] args)
{
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
OUTPUT:
infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c (to exit out of the program)

18.3 Un-Conditional statements

18.3.1 Break Statement:


 When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
 The Java break is used to break loop or switch statement.
 It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.

Syntax:
jump-statement;
break;

Page 50
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Example program 1 on break statement:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4

Example program 2 on break statement:


 It breaks inner loop only if you use break statement inside the inner loop.
Program:
public class BreakExample2
{
public static void main(String[] args)
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21
31
32
33

Page 51
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
18.3.2 Continue Statement:
 The continue statement is used in loop control structure when you need to immediately jump to the
next iteration of the loop. It can be used with for loop or while loop.
 The Java continue statement is used to continue loop. It continues the current flow of the program and
skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement;
continue;
Example program on continue statement:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4
6
7
8
9
10

Page 52
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
19. JAVA Expressions:
 Expressions are made up of variables, operators, literals and method calls that evaluates to a single
value according to the syntax of the language.
 Operators may be used in building expressions, which compute values; expressions are the core
components of statements; statements may be grouped into blocks.
 Example 1:
int abc;
abc = 100;
Here, abc = 100, is an expression that returns an int because the assignment operator returns a value of
the same data type as its LHS operand.
 Example 2:
int a=10, b=30;
int c;
c = a + b;
Here, c = a + b, is an expression that returns an int.
 Example 3:
If (number1 = = number2)
{
Sytem.out.println(“Hello java world”);
}
Here, number1 = = number2 is an expression that returns Boolean value and “Hello java world” is an
string expression.

19.1 Compound expressions:


 The Java programming language allows you to construct compound expressions from various smaller
expressions as long as the data type required by one part of the expression matches the data type of the
other.
 Example of a compound expression is: 1 * 2 * 3;
 Here the above example, the order in which the expression is evaluated is unimportant because the
result of multiplication is independent of order; the outcome is always the same, no matter in which
order you apply the multiplications.
 However, this is not true of all expressions. For example, the following example 1 expression gives
different results, depending on whether you perform the addition or the division operation first:
 Example 1:
x + y / 100; // ambiguous
 To overcome this, an expression will be evaluated using balanced parenthesis: ( and ). For example, to
make the previous expression unambiguous, you could write the following example 2:
 Example 2:
(x + y) / 100; // unambiguous, recommended

19.2 Java Blocks:


 A block is a group of statements (zero or more) that is enclosed in curly braces { }.
 Example:
class AssignmentOperator
{
public static void main(String[] args)
{

Page 53
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
String band = "Beatles";
if (band == "Beatles")
{ // start of block
System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}
 There are two statements System.out.print("Hey "); and System.out.print("Jude!"); inside the
mentioned block above.

20. Java operator precedence and associativity rules


 In Java, when an expression is evaluated, there may be more than one operators involved in an
expression.
 When more than one operator has to be evaluated in an expression, Java interpreter has to decide
which operator should be evaluated first.
 Java has well-defined rules for specifying the order in which the operators in an expression are
evaluated when the expression has several operators.
 For example: multiplication and division have a higher precedence than addition and subtraction.
 Java makes this decision on the basis of the precedence and the associativity of the operators.

20.1 Precedence order:


 Precedence is the priority order of an operator, if there are two or more operators in an expression
then the operator of highest priority will be executed first.
 For example: In expression 1 + 2 * 5, multiplication (*) operator will be processed first and then
addition. It's because multiplication has higher priority or precedence than addition.

20.2 Associativity:
 When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity.
 Associativity tells the direction of execution of operators that can be either left to right or right to left.
 For example, in expression a = b = c = 8 the assignment operator is executed from right to left that
means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You
can parenthesize this expression as (a = (b = (c = 8))).
 Note that, you can change the priority of a Java operator by enclosing the lower order priority operator
in parentheses but not the associativity.
 For example, in expression (1 + 2) * 3 addition will be done first because parentheses has higher
priority than multiplication operator.

Page 54
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
20.3 Precedence and associativity of Java operators:
The table below shows all Java operators from highest to lowest precedence, along with their
associativity.

Precedence Operator Description Associativity


[] array index
1 () method call Left -> Right
. member access
++ pre or postfix increment
-- pre or postfix decrement
2 +- unary plus, minus Right -> Left
~ bitwise NOT
! logical NOT
3 new Object creation Right -> Left
* multiplication
4 / division Left -> Right
% modulus (remainder)
+,- Addition, Subtraction
5 Left -> Right
+ Concatenation
< less than
<= less than or equal to
6 Left -> Right
> greater than
>= greater than or equal to
== Equal to
7 Left -> Right
!= Not equal to
& bitwise AND
^ bitwise XOR
8 | bitwise OR Left -> Right
&& Logical AND
|| Logical OR
9 ?: Ternary (conditional) Right -> Left
=
+=
-=
10 Assignment operators Right -> Left
*=
/=
%=

Page 55
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT - 2
21. Abstract Data Type:

 Abstract Data Type (ADT) is a type (or class) for objects whose behavior is defined by a set of value
and a set of operations.
 The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented.
 It does not specify how data will be organized in memory and what algorithms will be used for
implementing the operations.
 So it is called “abstract” because it gives an implementation independent view.
 The process of providing only the essentials and hiding the details is known as abstraction.
 In java, there are 3 ADTs namely List ADT, Stack ADT, Queue ADT.

21.1 List ADT:


 A list contains elements of same type arranged in sequential order and following operations can be
performed on the list.
i) get( ) – Return an element from the list at any given position.
ii) insert( ) – Insert an element at any position of the list.
iii) remove( ) – Remove the first occurrence of any element from a non-empty list.
iv) removeAt( ) – Remove the element at a specified location from a non-empty list.
v) replace( ) – Replace an element at any position by another element.
vi) size( ) – Return the number of elements in the list.
vii) isEmpty( ) – Return true if the list is empty, otherwise return false.
viii) isFull( ) – Return true if the list is full, otherwise return false.

21.2 Stack ADT:


 A Stack contains elements of same type arranged in sequential order. All operations takes place at a
single end that is top of the stack and following operations can be performed:
a) push( ) – Insert an element at one end of the stack called top.
b) pop( ) – Remove and return the element at the top of the stack, if it is not empty.
c) peek( ) – Return the element at the top of the stack without removing it, if the stack is not empty.
d) size( ) – Return the number of elements in the stack.
e) isEmpty( ) – Return true if the stack is empty, otherwise return false.
f) isFull( ) – Return true if the stack is full, otherwise return false.

21.3 Queue ADT:


 A Queue contains elements of same type arranged in sequential order. Operations takes place at both
ends, insertion is done at end and deletion is done at front. Following operations can be performed:
a) enqueue( ) – Insert an element at the end of the queue.
b) dequeue( ) – Remove and return the first element of queue, if the queue is not empty.
c) peek( ) – Return the element of the queue without removing it, if the queue is not empty.
d) size( ) – Return the number of elements in the queue.
e) isEmpty( ) – Return true if the queue is empty, otherwise return false.
f) isFull( ) – Return true if the queue is full, otherwise return false.

Page 56
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
22. Classes and objects
 In object-oriented programming every program is developed by using objects and classes.
 Object is the physical as well as logical entity whereas class is the logical entity only.

22.1 Objects in Java:

 An entity that has state and behavior is known as an object.


 An object has three characteristics:
1) State: represents data (value) of an object.
2) Behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
3) Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
 For example, ‘student’ is an object. His name, student id, branch, etc. represents the state. He used to
renewal books in library, knowing his current academic percentage, etc. represents the behavior.
 So object is called as instance of class.

22.2 Class in Java:

 A class is a group of objects which have common properties. It is a logical entity. It can't be physical.
 A class in Java can contain:
1. variable
2. methods
3. constructors
4. blocks
5. nested class and interface

Syntax to declare a class:


class <class_name>
{
field;
method;
}

Variable in Java:

 A variable which is created inside the class but outside the method is known as instance variable.
 Instance variable doesn't get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.

Method in Java:
 In java, a method is like function i.e. used to expose behavior of an object.
 Advantages of method are: Code Reusability and Code Optimization.

‘new’ keyword in Java:


 The new keyword is used to allocate memory at run time. All objects get memory in Heap memory
area.
 There are two types we can create object in java:
Syntax 1:classname reference = new classname( ); // referenced object

Syntax 2:new classname( ); // unreferenced object

Page 57
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
 The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before
executing the next time. So that it is highly recommended to access a single method of the class at a
time.
 In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
 ‘Referenced object’ and ‘unreferenced object’ is created by JVM in main memory based on its syntax.
 In the above syntax 2, JVM will create a new object for the properties of the given class.
 In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.

Examples of object creation:

1) Person raju = new Person( ); // object creation of syntax 1.

2)new Person( ); // object creation of syntax 2.

Program 6: A java program to create an object within the class


class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student( );//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}}
OUTPUT:
0
null

Program 7: A java program to create a main outside the class


class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student( );
System.out.println(s1.id);
System.out.println(s1.name);
} }
OUTPUT:
0
null
Page 58
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
22.3 Object creation and Initialization:
 There are 3 ways to initialize object in java.
a) By reference variable
b) By method
c) By constructor

Program 8: A java program to Initialization through reference


 Initializing object simply means storing data into object.
 The below example program shows how to initialize object through reference variable.

class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student( );
s1.id=101;
s1.name="Abc";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
OUTPUT:
101 Abc

Program 9: A java program to create multiple objects through reference variable

class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
//Creating objects
Student s1=new Student( );
Student s2=new Student( );
//Initializing objects
s1.id=101;
s1.name="Abc";
s2.id=102;
s2.name="Xyz";
System.out.println(s1.id+" "+s1.name);

Page 59
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(s2.id+" "+s2.name);
}
}
OUTPUT:
101 Abc
102 Xyz

Program 10: A java program to Initialization through method


class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation( )
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student( );
Student s2=new Student( );
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation( );
s2.displayInformation( );
}
}
OUTPUT:
111 Karan
222 Aryan

Page 60
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 11: A java program to Initialization through constructor
class Student4
{
int id;
String name;

Student4(int i,String n)
{
id = i;
name = n;
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display( );
s2.display( );
}
}
OUTPUT:
111 Karan
222 Aryan

Program 12: A java program to store employee records


class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display( ){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee
{
public static void main(String[] args)
{
Employee e1=new Employee( );
Employee e2=new Employee( );
Employee e3=new Employee( );
e1.insert(101,"ajeet",45000);

Page 61
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display( );
e2.display( );
e3.display( );
}
}
OUTPUT:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

22.4 Anonymous (or) un-reference object:


 Anonymous simply means nameless. An object which has no reference is known as anonymous
object.
 It can be used at the time of object creation only.
 For example: new Calculation( );//anonymous object

Syntax for calling method through anonymous object:

 new Classname( ).methodName( );

Example Program:
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[])
{
new Calculation( ).fact(5);//calling method with anonymous object
}
}
OUTPUT:
Factorial is 120

Page 62
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 13: A java program to store Bank details of customers
class Account
{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println("Insufficient Balance");
}
else
{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
void checkBalance( )
{
System.out.println("Balance is: "+amount);
}
void display( )
{
System.out.println(acc_no+" "+name+" "+amount);
}
}
class TestAccount
{
public static void main(String[] args)
{
Account a1=new Account( );
a1.insert(832345,"Ankit",1000);
a1.display( );
a1.checkBalance( );
a1.deposit(40000);
a1.checkBalance( );

Page 63
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
a1.withdraw(15000);
a1.checkBalance( );
}
}
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

23. Access Specifiers:


 An access specifier is a keyword that specifies how to access the members of class or a class itself.
 We can use access specifiers before a class and its members.
 There are 4 access specifiers mainly available in java are as follows.

23.1 Private: ‘private’ members of a class are not accessible anywhere outside the class. They are accessible
only within the methods of the same class.

23.2 Public: ‘public’ members of a class are accessible everywhere outside the class. So any other program
can read them and use them.

23.3 Protected: ‘protected’ members of a class are accessible outside the class, but generally within the same
directory.

23.4 default: If no access specifier is written by the programmer, then the java compiler uses a ‘default’
access specifier. ‘default’ members are accessible outside the class but within the same directory.

Note:
 In real time, we generally use ‘private’ for instance variables and ‘public’ for methods.
 In java, classes cannot be declared by using ‘private’.

24. Access Modifier:


 These are the keywords in java language used to change the current behavior of methods (or)
variables.
 Every access modifier is a ‘keyword’ but every keyword is not an access modifier.
 In java language there are 4 types of access specifiers:
1) default
2) private
3) protected
4) public
 Following access modifiers represents accessibility of variables and methods.

Page 64
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Within the derived Anywhere in same
Access Within the Within the
class of other and outside the
Modifier same class same package
package package
1) private YES NO NO NO
2) default YES YES NO NO
3) protected YES YES YES NO
4) pubic YES YES YES YES

 If any variable or method is not preceded by “private/protected/public” then that properties are treated
as ‘default’ properties.

24.1 private access modifier:


 The private access modifier is accessible only within class.
 In the below program 14, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so there
is compile time error.

Program 14: A java program for private access modifier


class A
{
private int data=40;
private void msg( ){System.out.println("Hello java");}
}

public class Simple


{
public static void main(String args[])
{
A obj=new A( );
System.out.println(obj.data);//Compile Time Error
obj.msg( );//Compile Time Error
}
}
OUTPUT:
Compile time error

24.2 default access modifier:


 If you don't use any modifier, it is treated as ‘default’ by default. The default modifier is accessible
only within package.
 In the below program 15, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

Page 65
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 15: A java program for default access modifier
//save by A.java
package pack;
class A
{
void msg( )
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );//Compile Time Error
obj.msg( );//Compile Time Error
}
}
OUTPUT:
Compile time error

24.3 protected access modifier:


 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
 In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

Program 16: A java program for protected access modifier


//save by A.java
package pack;
public class A
{
protected void msg( )
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A

Page 66
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
public static void main(String args[])
{
B obj = new B( );
obj.msg( );
}
}
OUTPUT:
Hello

24.4 public access modifier:


 The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Program 17: A java program for public access modifier

//save by A.java
package pack;
public class A
{
public void msg( )
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );
obj.msg( );
}
}

OUTPUT:
Hello

Page 67
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
25. Methods in Java:
 Def: A method represents a group of statements that performs a task. A task represents a calculation or
processing of data or generating a report etc.
 A method has two parts:
1) Method header or Method prototype
2) Method body
 The method header contains method return datatype, method name, method parameter.
 The method body contains business logic.

Method Syntax:
returntype methodName (parameter 1, parameter 2, …)
{
// method body
}
 In the above syntax, ‘methodname’ can be any user defined name and the main business logic must
be written inside the method body.

Parameters:
 The ‘parameters’ represents the “input”, it can be any of following 3 types:
1) No parameter (empty):Method performs an operation without accepting any input.
2) Primitive datatype: Method performs an operation by accepting single input value.
3) Reference datatype: Method performs an operation by accepting multiple input values in the form
of “object”.

Returntype:
 ‘returntype’ represents “output”, it can be any of following 3 types:
1) No return type (void):Method does not return the output to other method from where it is calling.
2) Primitive datatype: Method returns a single output value to the other method.
3) Reference data type: Method returns multiple output values in the form of ‘object’ to the other
method.
 Primitive data type: This is a data type whose variable can handle maximum one value at a time. For
example: byte, short, int, long, float, double, char and Boolean
 Reference data type: It is a data type whose variable can handle more than one value in the form of
‘object’.
 Note: If the result (output) of one method wants to be used inside the other method then the return
type of the first method should be either ‘primitive’ (or) ‘reference’ data type.

25.1 Types of method:


1. Non-static/ Instance method
2. Static method
25.1.1 Instance Method:
 If any method is not preceded by ‘static’ keyword is known as ‘Non-static’ or ‘Instance’ method.
 Syntax:
returntype methodname( )
{
-----
-----
}
Page 68
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In real time, it is highly recommended to define instance methods onlyif any method wants to perform
an operation only on ‘Instance variables’.
 Non-static method should be accessed with ‘object’.
 For non-static method memory is allocated only once at that time of object calling.

25.1.2 Static Method:


 If any method is preceded by ‘static’ method known as static method.
Syntax:
static returntype methodname( )
{
-----
-----
}
 In real time, it is highly recommended to define the static methods to perform an operation only on
static variables.
 Static methods should be accessed with ‘class name’.
 For static method, memory is allocated only once at that time of loading of class.

 If any method definition is preceded by ‘static’ keyword is known as “static method”, it must be
accessed with ‘classname’.
 If any method definition is not preceded by ‘static’ keyword is known as “non-static method” or
“instance method”, it must be accessed with ‘object’.

Syntax No 1:
void methodname( )
{
-----
-----
}
- In the above syntax 1, it is use to perform an operation without accepting any input values and
does not returns any output to the other method
- Syntax to call a non-static method:
object.methodname( );

Page 69
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
- Syntax to call a static method:
classname.methodname( );

Syntax No 2:
void methodname( primitivedatatype variable)
{
-----
-----
}
- In the above syntax 2, it is use to perform an operation by accepting single input value and does
not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( value);
- Syntax to call a static method:
classname.methodname( value);

Syntax No 3:
void methodname( Referencedatatype variable)
{
-----
-----
}
- In the above syntax 3, it is use to perform an operation by accepting multiple input values in the
form of object and does not returns any output to the other method.
- Syntax to call a non-static method:
object.methodname( object);
- Syntax to call a static method:
classname.methodname(object);

Syntax No 4:
primitivedatatype methodname( )
{
-----
-----
return value;
}
- In the above syntax 4, it is use to perform an operation without accepting any input values and
returns a single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename = object.methodname( );
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( );

Page 70
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Syntax No 5:
primitivedatatype methodname( primitivedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 5, it is use to perform an operation by accepting single input value and returns
single output value to the other method.
- Syntax to call a non-static method:
primitivedatatype variablename= object.methodname( value);
- Syntax to call a static method:
primitivedatatype variablename = classname.methodname( value);

Syntax No 6:
primitivedatatype methodname( referencedatatype variable)
{
-----
-----
return value;
}
- In the above syntax 6, it is use to perform an operation by accepting multiple input values in the
form of object and returns single output value to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( object);
- Syntax to call a static method:
Classname objectreference = classname.methodname(object);

Syntax No 7:
Referencedatatype methodname( )
{
-----
-----
return object;
}
- In the above syntax 7, it is use to perform an operation without accepting any input values and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname( );
- Syntax to call a static method:
Classname objectreference = classname.methodname( );

Page 71
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Syntax No 8:
Referencedatatype methodname(primitivedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 8, it is use to perform an operation by accepting single input value and returns
multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(value);
- Syntax to call a static method:
Classname objectreference = classname.methodname( value);

Syntax No 9:
Referencedatatype methodname(Referencedatatype variable )
{
-----
-----
return object;
}
- In the above syntax 9, it is use to perform an operation by accepting multiple input value and
returns multiple output values in the form of object to the other method.
- Syntax to call a non-static method:
Classname objectreference = object.methodname(object);
- Syntax to call a static method:
Classname objectreference = classname.methodname( object);

 Following table shows how to access both static and non-static properties within the non-static and
static methods of same class or other class:

Within the non- Within the Within the non- Within the static
Type of
static method of static method static method of method of other
Property
same class of same class other class class
1. Non-static Can be used Can be accessed Can be accessed Can be accessed
method/variable directly by using object by using object by using object
Can be accessed Can be accessed Can be accessed Can be accessed
2. Static
directly / using directly / using by using class by using class
method/variable
class name class name name name

25.2 Rules to be followed while working with methods:


1. Method must be defined inside the class only.
2. One class can have many numbers of methods.
3. No method will be executed without calling.
4. One method should be called inside another method, that maybe main method or user defined method.
5. Method contains only logic to perform an operation.

Page 72
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 18: A java program for method concept
class A
{
int x=10, y=20, z;
void add( )
{
z= x + y;
System.out.println(z);
}
}
class B
{
void show( )
{
new A( ).add( );
System.out.println(“In class B”);
}
}
class C
{
void f1( )
{
new B( ).show( );
System.out.println(“In class C”);
}
}
class TestDemo
{
public static void main(String args[])
{
new C( ).f1( );
System.out.println(“In class C”);
}
}
OUTPUT:
30
In class B
In class C

Page 73
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 19: A java program to work with all types of variables and methods
Class A
{
int y=8;
static int z = 3;
void f1( )
{
int x=5; //local variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
void f2( )
{
System.out.println(x); //local variable cannot be accessed outside the method
System.out.println(y);
System.out.println(z);
System.out.println(A.z);
f1( );
}
static void f3( )
{
A oa = new A( );
System.out.println(oa.y);
oa.f1( );
System.out.println(z);
}
}
class B
{
void f4( ) //non-static method
{
new A( ).f1( );
A.f3( );
}
static void f5( )
{
new A( ).f1( );
A.f3( );
}
}
class MethodDemo
{
public static method(String args[ ])
{
A.f3( );
new B( ).f4( );
B.f5( );

Page 74
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
B.f4( );//Not possible because f4( ) is a non-static method so we cannot call by class
//name. If requires we can access the f4( ) by creating an object.
}
}

Program 20: A java program to work with methods


class A
{
void f1( )
{
System.out.println(“In f1( ) of class A”);
}
int f2( )
{
return (5);
}
static void f3(String s)
{
System.out.println(“In f3( ) of class A”);
}
}
class Main
{
public static void main(String a[ ])
{
A oa = new A( );
oa.f1( );
int x = oa.f2( );
System.out.println(x);
float y = oa.f2( );//Invalid, because f2( ) is returning integer value but here we are assigning to
float
oa.f2( );
A.f3(Hello);//Invalid, f3( ) is expecting string type value.
A.f3(“Java”);
}
}

Program 21: A java program to work with methods


class Student
{
int rno;
String name;
void display( )
{
System.out.println(rno);
System.out.println(name);
}
}

Page 75
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class A
{
void f1(Student s)
{
System.out.println(“In class A”);
}
static int f2( )
{
return (5);
}
}
class Demo
{
public static void main(String a[ ])
{
new Student( ).display( );
Student s = new Student( );
new A( ).f1(s);
int i = A.f2( );
}
}

Program 22: A java program for a method without parameters and without return type
class Sample
{
private double, num1, num2;
void sum( )
{
double res = num1 + num2;
System.out.println(“Sum=” +res);
}
}
class Methods
{
public static void main(String a[ ])
{
Sampe s = new Sample( );
s.sum( );
}
}

Page 76
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 23: A java program for a method without parameters and with return type
class Sample
{
private double num1, num2;
double sum( )
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum( );
System.out.println(“Sum=” +x);
}
}

Program 24: A java program for a method with two parameters and with return type
class Sample
{
double sum(int num1, double num2)
{
double res = num1 + num2;
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample( );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}

Page 77
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 25: A java program for a static method that accepts data and return the result
class Sample
{
static double sum(double num1, double num2)
{
double res = num1 + num2;
return res;
}
class Methods
{
public static void main(String a[ ])
{
double x = Sample.sum(10, 22.5);
System.out.println(“Sum=” +x);
}
}
Program 26: A java program to test whether a static method can access the instance variable or not
class Test
{
int x;
static void access( )
{
System.out.println(“x =”+x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}
Program 27: A java program to test whether a static method can access the static variable or not
class Test
{
static int x = 55;
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test.access( );
}
}

Page 78
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 28: A java program by taking an instance variable x in the Test class
class Test
{
int x = 10;
void display( )
{
System.out.println(x);
}
}
class InstanceDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );
}
}
OUTPUT:
X in obj1: 11
X in obj2: 10

Program 29: A java program by taking a static variable x in the Test class
class Test
{
static int x = 10;
static void display( )
{
System.out.println(x);
}
}
class StaticDemo
{
public static void main(String args[ ])
{
Test obj1, obj2;
obj1= new Test( );
obj2= new Test( );
++obj1.x;
System.out.println(“X in obj1: “);
obj1.display( );
System.out.println(“X in obj2: “);
obj2.display( );

Page 79
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
X in obj1: 11
X in obj2: 11

26. Method Overloading:


 If the same name is existing multiple times with in a class with different number of parameters,
different type of parameters and different order of parameters is known as “Method Overloading”.
 Advantage of method overloading is “readability of the program”.
 Different ways to overload the method:
1) By changing number of arguments.
2) By changing the data type.

26.1 Method Overloading: changing no. of arguments

 In the program 30, we have created two methods, first add( ) method performs addition of two
numbers and second add method performs addition of three numbers.
 In this example, we are creating static methods so that we don't need to create instance for calling
methods.

Program 30: A java program by changing no. of arguments

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
OUTPUT:
22
33

Page 80
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
26.2 Method Overloading: changing data type of arguments
 In program 31, we have created two methods that differ in data type. The first add method receives
two integer arguments and second add method receives two double arguments.

Program 31: A java program by changing data type of arguments


class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
OUTPUT:
22
24.9

 In method overloading, is not possible by changing the return type of the method only because of
ambiguity.
 Example program:
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static double add(int a,int b)
{
return a+b;
}
}
class TestOverloading3
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));//ambiguity
}

Page 81
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:
Compile Time Error: method add(int,int) is already defined in class Adder

26.3 Can we overload java main( ) method:


 Yes, it is possible by using method overloading.
 You can have any number of main methods in a class by method overloading. But JVM calls main( )
method which receives string array as arguments only.

Program 32: A java program on overloading main( ) method


class TestOverloading4
{
public static void main(String[] args)
{
System.out.println("main with String[]");
}
public static void main(String args)
{
System.out.println("main with String");
}
public static void main( )
{
System.out.println("main without args");
}
}
OUTPUT:
main with String[ ]

26.4 Method overloading with Type Promotion


 One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below.

Page 82
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can
be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or
double and so on.

program 33: A java program with type promotion:


class OverloadingCalculation1
{
void sum(int a, long b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
OverloadingCalculation1 obj=new OverloadingCalculation1( );
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
OUTPUT:
40
60

Program 34: A Java program with type promotion if matching found


 If there are matching type arguments in the method, type promotion is not required.
class OverloadingCalculation2
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
public static void main(String args[])
{
OverloadingCalculation2 obj=new OverloadingCalculation2( );
obj.sum(20,20);//now int arg sum( ) method gets invoked
}
}
OUTPUT:
int arg method invoked

Page 83
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
26.5 Method overloading with Type Promotion in case of ambiguity
 If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.

Program 35: A Java Program with Type Promotion in case of ambiguity in method overloading
class OverloadingCalculation3
{
void sum(int a, long b)
{
System.out.println("a method invoked");
}
void sum(long a, int b)
{
System.out.println("b method invoked");
}
public static void main(String args[])
{
OverloadingCalculation3 obj=new OverloadingCalculation3( );
obj.sum(20,20);//now ambiguity
}
}
OUTPUT:
Compile Time Error

26.6 Rules for Method overloading


1) Method name must be same.
2) Method signature must be different.
3) For overloading methods, ‘return type’ can be any type. There is no compulsion that return type must
be same.
4) Overloaded methods either can be static (or) non-static (or) can be a combination of static and non-
static.
 Example Program:
class A
{
static int f1( )
{
System.out.println(“F1 in class A”);
return (5);
}
static void f1(int x)
{
System.out.println(“F1 with parameter in class A”);
}
}
class MOverloadingDemo
{ A.f1( );
A.f1(5);
}

Page 84
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
27. Constructor in Java:
 In Java, constructor is a block of codes similar to method.
 It is called when an instance of object is created and memory is allocated for the object.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using ‘new’ keyword, at least one constructor is called. It is called a
default constructor.
 It is called constructor because it constructs the values at the time of object creation.
 It is not necessary to write a constructor for a class.
 It is because java compiler creates a default constructor if your class doesn't have any.
 Rules for creating java constructor:
1) Constructor name must be same as its class name.
2) Constructor must have no explicit return type
 Types of java constructors. There are two types of constructors in java:
1) Default constructor (no parameterized constructor)
2) Parameterized constructor

27.1 Parameterized Constructor:


 If any constructor contains list of parameters in its signature is known as ‘parameterized constructor’.
 Syntax:
classname (list of parameters)
{
//Initialization code
}
 Syntax to call the parametrized constructor:
- classname objreference = new classname(arguments); // constructor calling with referenced object
- new classname(arguments); //constructor calling without referenced object

Program 36: A java program on constructor


class Emp
{
int eid;
String ename;
float esal;
Emp(int id, String nm, float sl)
{
eid = id;
ename = nm;
esal = sl;
}
void display( )
{
System.out.println(“emp id:” +eid);
System.out.println(“emp name:” +ename);
System.out.println(“emp sal:” +esal);
}
}

Page 85
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class EmpDemo
{
public static void main(String args[ ])
{
Emp e1 = new Emp(1, “abc”, 75.6f);
e1.display( );
System.out.println(“……………..”);
Emp e2 = new Emp(2, “xyz”, 75.9f);
e1.display( );
System.out.println(“……………..”);
Emp e3 = new Emp(3, “lmn”, 83.7f);
e1.display( );
}
}
 One class can have many number of constructors with different signature, this is technically called as
“Constructor Overloading”.
 The main purpose of defining multiple constructors is to initialize the different objects with different
number of dynamic input values.

Program 37: A java program on multiple parameterized constructors


import java.util.Scanner;
class Emp
{
int eid;
String ename;
float esal;
Emp(int id, String nm, float sl)
{
eid = id;
ename = nm;
easl = sl;
}
Emp(int id, String nm)
{
eid = id;
ename = nm;
}
Emp(int id)
{
eid = id;
}
void display( )
{
System.out.println(“emp id:”,+eid);
System.out.println(“emp name:”,+ename);
System.out.println(“emp sal:”,+esal);
}
}

Page 86
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class EmpDemo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter number of inputs:”);
int ni = sn.nextInt( );
if(ni= = 3)
{
System.out.println(“Enter eid, ename, esal:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
float sl = sn.nextFloat( );
new Emp(id,nm,sl).display( );
}
else if(n= = 2)
{
System.out.println(“Enter eid, ename:”);
int id = sn.nextInt( );
String nm = sn.nextLine( );
new Emp(id,nm).display( );
}
else if(n= = 1)
{
System.out.println(“Enter eid:”);
int id = sn.nextInt( );
new Emp(id).display( );
}
}

27.2 Default (No-Parameterized) Constructor:


 If any constructor does not contain list of parameters in its signature is known as “No-Parameterized
Constructor”.
 ‘Java compiler’ creates no-parametrized constructor by default if that class does not contain
parameterized constructors.
 Syntax:
Classname( )
{
//constructor body
}
 Compiler doesn’t creates no-parameterized constructor if that class doesn’t contain atleast one
parameterized constructor.
 The logic is executed only once at that time of creation of object only.
 Syntax to call the no-parameterized constructor:
1) Classname ref = new Classname( );
2) new Classname( );

Page 87
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 38: A java program of default constructor
class Bike1
{
Bike1( )
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1( );
}
}
OUTPUT:
Bike is created

Program 39: A java program on default constructor that displays the default values
class Student3
{
int id;
String name;
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3( );
Student3 s2=new Student3( );
s1.display( );
s2.display( );
}
}
OUTPUT:
0 null
0 null

Program 40: A java program for a method with two parameters and with return type with constructor
class Sample
{
Private double num1, num2;
Sample(double x, double y)
{
num1 = x;
num2 = y;
}
double sum(int num1, double num2)
{
double res = num1 + num2;

Page 88
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
return res;
}
}
class Methods
{
public static void main(String a[ ])
{
Sample s = new Sample(10.9,23.6 );
double x = s.sum(10, 22.5);
System.out.println(“Sum =” +x);
}
}

OUTPUT:
Sum = 23.5

Program 41: A java program copying values without constructor


class Student7
{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7( )
{
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7( );
s2.id=s1.id;
s2.name=s1.name;
s1.display( );
s2.display( );
}
}
OUTPUT:
111 Karan
111 Karan

Page 89
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
28. Difference between Method and Constructor in java:

Method Constructor
1) Method is used to expose behavior of an 1) Constructor is used to initialize the state
object. of an object.
2) Method must have return type. 2) Constructor must not have return type.
3) Method is invoked explicitly. 3) Constructor is invoked implicitly.
4) The java compiler provides a default
4) Method is not provided by compiler in any
constructor if you don't have any
case.
constructor.
5) Method name may or may not be same as 5) Constructor name must be same as the
class name. class name.

29. Reading input values dynamically


 Java supports reading the input values dynamically in following 2 ways:
1) Using “Command Line Arguments”.
2) Using “Scanner” class.

29.1 Command Line Arguments:


 Generally argument means value and the java command-line argument is an argument i.e. passed at
the time of running the java program.
 If any input value is passed through command prompt or console at the time of running of java
program is known as “command line argument”.
 Syntax:
> javac filename.java
> java filename value1, value2, value3,…
 In the above syntax, value1, value2, value3 are known as command line arguments.
 Command line arguments should be separated with ‘spaces’, by default all these values are stored in
‘String’ array of main method.
 By default, every command line argument is ‘String’ type.
 The java command-line argument is an argument i.e. passed at the time of running the java program.

Program42: A Java program on command-line arguments


 In the below example program 42, we are receiving only one argument and printing it.
 To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
OUTPUT:
>javac CommandLineExample.java
> java CommandLineExample hellojava
Output: Your first argument is: hellojava

Page 90
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
29.2 Reading inputs using ‘Scanner’ class:
 ‘Scanner’ is a predefined class in “java.util” package used to read the input values from any input
component like ‘keyboard’, ‘file’, ‘client machine’ etc.
Syntax: Scanner sn = new Scanner(System.in);
 The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It
provides many methods to read and parse various primitive values.
 System.in represents standard input device and System.out represents standard output device.

29.3 Scanner class methods:


1) nextByte( ) - It used to read byte value.
2) nextShort( ) - It used to read short value.
3) nextInt( ) - It used to read int value.
4) nextLong( ) - It used to read long value.
5) nextFloat( ) - It used to read float value.
6) nextDouble( ) - It used to read double value.
7) nextBoolean( ) - It used to read boolean value.
8) next( ) - It used to read a ‘single string’ value. It doesn’t consider spaces.
9) nextLine( ) - It used to read It used to read a ‘single string’ value. It doesn’t consider spaces.

- Above all methods are non-static methods, so we must access with object.

Program 43: A java program to read the input values using ‘Scanner’ class
import java.util.Scanner;
class Demo
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter first number:”);
int x = sc.nextInt( );
System.out.println(“Enter second number:”);
int y = sc.nextInt( );
int z = x + y;
System.out.println(“Result is:”+z);
}
}

OUTPUT:
Enter first number:
25
Enter second number:
10
Result is:
35

Page 91
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 44: A java program to read the student details dynamically
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt( );
System.out.println("Enter your name");
String name=sc.next( );
System.out.println("Enter your fee");
double fee=sc.nextDouble( );
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close( );
}
}
OUTPUT:
Enter your rollno
111
Enter your name
Ratan
Enter your fee
450000
Rollno:111 name: Ratan fee:450000

30. WRAPPER CLASSES


 These are the predefined classes in “java.lang” package used to:
1) Represent the primitive data type into object type.
2) Convert string to primitive data and primitive data to string type.
 The below shows various wrapper classes and its methods for parsing.
Wrapper Class Method Description
1) Byte parseByte(String) It used to convert string to byte value.
2) Short parseShort(String) It used to convert string to short value.
3) Integer parseInt(String) It used to convert string to Integer value.
4) Long parseLong(String) It used to convert string to Long value.
5) Float parseFloat(String) It used to convert string to float value.
6) Double parseDouble(String) It used to convert string to double value.
7) Boolean parseBoolean(String) It used to convert string to boolean value.

Program 45: A java program to work with command line arguments


class CmdDemo
{
public static void main(String args[ ])
{
System.out.println(“Before Converting”);
System.out.println(args[0] + args[1]);
System.out.println(“After Converting”);
int x = Integer.parserInt(args[0]);
Page 92
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
int y = Integer.parserInt(args[1]);
int z = x + y;
System.out.println(“Sum =” +z);
}

}
OUTPUT:
>javac CmdDemo.java
>java CmdDemo 10 20
Before Converting
1020
After Converting
30

31. Accept input form the keyboard:


 A stream is required to accept input from the keyboard.
 A stream represents flow of data from one place to another place.
 A stream can carry data form keyboard to memory or memory to printer or from memory to a file.
 A stream is always required if we want to move data from one place to another.
 Basically there are two types of streams:
1) Input Streams
2) Output Streams
 Input streams are those streams which receive or read data coming from some other place.
 Output steams are those streams which send or write data to some other place.
 All streams of input and output are represented by classes in “java.io” package.
 This package contains a lot of classes, all of which can be classified into input and output streams.
 Keyboard is represented by a field, called ‘in’ in ‘System’ class. When we write “System.in”
represents a standard input device i.e. keyboard by default. System class is found in “java.lang”
package and has three fields as follows:
1) System.in: This represents “InputStream” class object, by default represents standard input device
i.e. keyboard.
2) System.out: This represents “OutputStream” class object, by default represents standard output
i.e. monitor. It is used to display normal messages and results.
3) System.err: This filed also represents “PrintStream” object, which by default represents monitor.
It is used to display error messages.
 To accept the data from the keyboard i.e. “System.in”, we need to connect the keyboard to an input
stream object. Here we can use “InputStreamReader” that can read data from the keyboard.
InputStreamReader obj = new InputStreamReader (System.in);
 Now, connect “InputStreamReader” to “BufferedReader”, which is another input type of stream. By
using this we can read data properly coming from the stream in two ways:
1) BufferedReader br = new BufferedReader(obj);
- Here we are creating “BufferedReader” object (br) and connecting the “InputStream” object (obj) to
it.
2) Buffer Reader br = new BufferedReader(new InputStreamReader(System.in));
- Here we can be combined object (br) and object (obj).
 Now we can read the data coming from the keyboard using read( ) and readLine( ) methods available
in “BufferedReader” class.
Page 93
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
31.1 Accepting a single character from the Keyboard:
 Now, the following steps are required to accept a single character from the keyboard:
1) Create a “BufferedReader” class object (br).
2) Then, read a single character from the keyboard using “read( )” method.
 The read( ) method return type is Integer. So we need to do “type casting” for converting int data
type to char type.
 The read( ) method could not accept a character due to insufficient memory or illegal character, then it
gives rise to a runtime error which is called by the name IOException class. Where IO standards for
input/output and Exception represents runtime error.
 When read( ) method is giving IOException. Then we are identifying by using Exception Handling.

Program 46: A java program to accept and display a character from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
//create BufferedReader object to accept data from keyboard
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a character:”);
Char ch = (char)br.read( );
System.out.println(“You entered:” +ch);
}
}

OUTPUT:
Enter a character: A
You entered: A

31.2 Accepting a String of characters from the Keyboard:

 To read string a characters from the keyboard we required readLine( ) method in ‘BufferedReader’
class.
 The readLine( ) method accepts a string from the keyboard and returns the string.
 Here type casting not required because accepting and returning the same data type.
 But this method can give to the runtime error: IOException.

Program 47: A java program to accept and display a String of characters from the keyboard
import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a name:”);
Stringname =br.readLine( );
System.out.println(“You entered:” +name);
}

Page 94
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}

OUTPUT:
Enter a name: Java
You entered: Java

31.3 Accepting a Integer value from the Keyboard:

 To accept an integer value from the keyboard, follow the below steps:
1) First, accept the integer number from the keyboard as a string using readLine( ) method.
String str = br.readLine( );
2) The readLine( ) method return type is Integer. So this should be converted into an int by using
parseInt( ) method of Integer class in ‘java.lang’ package and parseInt( ) is a static method in
Integer class so it can be called by using classname, as follows:
int n = Integer.parseInt(str);
3) We can combine the above two steps in a single statement as follows:
int n = Integer.parseInt(br.readLine( ));

Program 48: A java program to accept an integer from keyboard


import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a value:”);
int num = Integer.parseInt(br.readLine( ) );
System.out.println(“You entered:” +num);
}
}

OUTPUT:
Enter a value: 1234
You entered: 1234

31.4 Accepting a Float value from the Keyboard:

 To accept an float value from the keyboard in the following way:


Float n = Float.parseFloat(br.readLine( ));

Program 49: A java program to accept an integer from keyboard


import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a float value:”);
float num = Float.parseFloat(br.readLine( ) );
System.out.println(“You entered:” +num);

Page 95
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}

OUTPUT:
Enter a float: 12.34
You entered: 12.34

31.5 Accepting a Double value from the Keyboard

 To accept an double value from the keyboard in the following way:


double n = Double.parseDouble(br.readLine( ));

Program 50: A java program to accept a double from keyboard


import java.io.*;
class Accept
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
System.out.println(“Enter a double value:”);
double num = Double.parsedouble(br.readLine( ) );
System.out.println(“You entered:” +num);
}
}

OUTPUT:
Enter a double value: 123456.789
You entered: 123456.789

31.6 Accepting byte, long, short and boolean types of values:

 Similarly, we can write different statements to accept many other data types from the keyboard as
follows:
1) To accept a byte value.
byte n = Byte.parseByte(br.readLine( ));
2) To accept a short value.
short n = Short.parseShort(br.readLine( ));
3) To accept a long value.
long n = Long.parseLong(br.readLine( ));
4) To accept a boolean value.
boolean n = Boolean.parseBoolean(br.readLine( ));

 The classes like Byte, Short, Integer, Long, Float, Double and Boolean belongs to “java.lang”
package. These classes are called as WRAPPER CLASSES.

Page 96
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 51: A java program that accepting and displaying employee details
import java.io.*;
import java.lang.*;
class a
{
public static void main (String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Emp id:");
int id = Integer.parseInt(br.readLine( ));
System.out.println("Enter Emp name:");
String name = br.readLine( );
System.out.println("Enter Emp salary:");
float sal = Float.parseFloat(br.readLine( ));
//display the employee details
System.out.println("Emp Id is:" +id);
System.out.println("Emp name:" +name);
System.out.println("Emp sal is:" +sal);
}
}

Program 52: A java program to perform Fibonacci series


import java.io.*;
class Fib
{
public static void main(String args [ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“How many fibonaccis?”);
int n = Integer.parseInt(br.readLine( ));
long f1 = 0, f2 = 1;
System.out.println(f1);
System.out.println(f2);
long f = f1+f2;
System.out.println(f);
//Already 3 fibonaccis are displayed. So count will start at 3
int count = 3;
while(count<n)
{
f1 = f2;
f2 = f;
f = f1+f2;
System.out.println(f);
count++;
}
}
}

Page 97
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
How many fibonaccies? 5
0
1
1
2
3

32. Garbage Collector in java


 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
 To do so, we were using free( ) function in C language and delete( ) in C++. But, in java it is
performed automatically. So, java provides better memory management.
 Advantage of Garbage Collection:
1) It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
2)It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.

32.1 How can an object be unreferenced?


 There are many ways:
1) By nulling the reference
2) By assigning a reference to another
3) By anonymous object etc.

32.1.1 By nulling a reference:


Employee e=new Employee( );
e=null;
32.1.2 By assigning a reference to another:
Employee e1=new Employee( );
Employee e2=new Employee( );
e1=e2;//now the first object referred by e1 is available for garbage collection
32.1.3 By anonymous object:
new Employee( );

32.3 finalize( ) method


 The finalize( ) method is invoked each time before the object is garbage collected.
 This method can be used to perform cleanup processing.
 This method is defined in Object class as:
protected void finalize( ){}
 Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So
if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects)

32.4 gc( ) method


 The gc( ) method is used to invoke the garbage collector to perform cleanup processing.

Page 98
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 The gc( ) is found in System and Runtime classes.
Syntax: public static void gc( ){}
 Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread
calls the finalize( ) method before object is garbage collected.

Program 52: Java example of garbage collection in java


public class TestGarbage1
{
public void finalize( )
{
System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1( );
TestGarbage1 s2=new TestGarbage1( );
s1=null;
s2=null;
System.gc( );
}
}
OUTPUT:
object is garbage collected
object is garbage collected

33. Importance of Java static Keyword and examples:


 The static keyword in java is used for memory management mainly.
 We can apply java static keyword with variables, methods, blocks and nested class.
 The static keyword belongs to the class than instance of the class (object).
 The static can be:
1) variable (also known as class variable)
2) method (also known as class method)
3) block

33.1 Java static variable

 If you declare any variable as static, it is known static variable.


 The static variable can be used to refer the common property of all objects (that is not unique for each
object).
 Example: company name of employees, college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
 Advantage: It makes your program memory efficient (i.e it saves memory).
 Example program without static variable:
class Student
{
int rollno;
String name;
String college="ITS";
}

Page 99
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In the above example, all students have its unique ‘rollno’ and ‘name’, so instance data member is
required and for college refer to the common property of all objects. If we make it static, this field will
get memory only once.

Program 53: A java program with static variable:


class Student8
{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ( )
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display( );
s2.display( );
}
}
OUTPUT:
111 Karan ITS
222 Aryan ITS

Program 54: A java program of counter without static variable


class Counter
{
int count=0;//will get memory when instance is created
Counter( )
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Counter c1=new Counter( );
Counter c2=new Counter( );
Counter c3=new Counter( );
}
}

Page 100
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
1
1
1
 In the above program 54, we have created an instance variable named count which is incremented in
the constructor.
 Since instance variable gets the memory at the time of object creation, each object will have the copy
of the instance variable, if it is incremented, it won't reflect to other objects.
 So each objects will have the value 1 in the count variable.

Program 55: A java program of counter by static variable


 Static variable will get the memory only once, if any object changes the value of the static variable, it
will retain its value.

class Counter2
{
static int count=0;//will get memory only once and retain its value
Counter2( )
{
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2( );
Counter2 c2=new Counter2( );
Counter2 c3=new Counter2( );
}
}
OUTPUT:
1
2
3
33.2 Java static method:
 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 Static method can access static data member and can change the value of it.
 Static method is a method that doesn’t act up on instance variables of a class.
 Static methods are called with ‘classname’ that is the reason static methods are not accessed by JVM
with instance variables.

Program 56: A java program on static method


class Student9
{
int rollno;
String name;
static String college = "ITS";
static void change( )
Page 101
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
college = "BBDIT";
}

Student9(int r, String n)
{
rollno = r;
name = n;
}
void display ( )
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student9.change( );
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display( );
s2.display( );
s3.display( );
}
}
}
OUTPUT:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Program 57: A java program on static method that performs normal calculation
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}
OUTPUT:
125

Page 102
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 58: A java program on static method trying to access instance variable
class Test
{
int x;//instance variable
Test(int x)
{
this.x = x;
}
static void access( )
{
System.out.println(“X =” +x);
}
}
class Demo
{
public static void main(String args[ ])
{
Test obj = new Test(10);
Test.access( );
}
}
OUTPUT: Run this program for better understanding

33.3 Java static block:


 Is used to initialize the static data member.
 It is executed before main method at the time of class loading.

Program 59: A java program on static block


class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

OUTPUT:
static block is invoked
Hello main

Page 103
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
34. ‘this’ keyword in Java:
 It is a keyword in java language, represents the current class object, it can be used in following 2 ways:
1) this.
2)this( )

34.1 this.
 It is used to differentiate “instance variables” with “formal parameters” of either method (or)
constructor if both are existing with same name.
 Syntax: this.variablename;

Program 59: A java program to work with this.


class Emp
{
int eid;
String ename;
float esal;
Emp(int eid, String ename, float esal)
{
this.eid = eid; //local variable contains highest priority on current class object.
this.ename = ename;
this.esal = esal;
}
void display( )
{
System.out.println("Emp id:" +eid);
System.out.println("Emp name:" +ename);
System.out.println("Emp sal:" +esal);
}
}
class EmpDemo
{
public static void main(String args [ ])
{
Emp e1 = new Emp( 1, "abc", 76.24f);
e1.display( );
Emp e2 = new Emp( 2, "xyz", 960.24f);
e2.display( );
}
}

OUTPUT:
Emp id: 1
Emp name: abc
Emp sal: 76.24
Emp id: 2
Emp name: xyz
Emp sal: 960.24

Page 104
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
34.2 this( ):
1) It is used to call one constructor inside another constructor same class.
2) The main advantage with this( ) is to call multiple constructors by creating single object.
3) The scope of ‘this’ keyword is within the same class.
4) This( ) must be the first statement while calling method or constructor.
5) Syntax:
o this(arguments) //used to call parameterized constructor
o this( ); //used to call no-parameterized constructor

Program 60: A java program to work with this( ).


class A
{
A( )
{
System.out.println(“No parameterized constructor”);
}
A(int x)
{
this( ); // calls no-parameterized
System.out.println(“Single Parameterized constructor”);
}
A(int x, String y)
{
this(10);// calls single parameterized
System.out.println(“Two parameterized constructor”);
}
}
class TestDemo
{
public static void main(String args[ ])
{
A oa = new A(20, “abc”);
}
}
OUTPUT:
No parameterized constructor
Single parameterized constructor
Two parameterized constructor

Page 105
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
35. Arrays
 An array is a data structure which represents a group of elements of same type.
 By using arrays we can store group of int values or a group of float values or group of strings in the
array. But we cannot store all data type values in the same array.
 In Java, arrays are created on dynamic memory allocated by JVM at runtime.
 Types of arrays:
1) Single dimensional array
2) Multi-dimensional array(2D, 3D, .. arrays)
 Advantage of Java Array:
1) Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.
2) Random access: We can get any data located at any index position.
 Disadvantage of Java Array:
1) Size Limit: We can store only fixed size of elements in the array.
2) It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

35.1 Single Dimensional Array:


 A one dimensional (1D) or single dimensional array represents a row or a column of elements.
 Syntax to Declare single dimensional array:
1) dataType[] arr; (or)
2) dataType []arr; (or)
3) dataType arr[];
 Instantiation of an Array in java
- datatype arrayRefVar = new datatype[size];
 Examples:
1) int marks[ ]; //declare marks array of integer type
2) marks = new int [5];// allocate memory for storing 5 elements

Program 61: A java program of single dimensional array with declaration and instantiation
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OUTPUT:
10
20
70
40
50
Page 106
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 62: A java program of single dimensional array with declaration, instantiation and
Initialization
class Testarray1
{
public static void main(String args[])
{
int a[]={9,13,6,3};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
OUTPUT:
9
13
6
3

Program 63: A java program of to find minimum value using array


class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={6,3,2,9};
min(a);//passing array to method
}
}
OUTPUT:
2

Program 64: A java program to find out total marks and percentage of student with 1D array
import java.io.*;
class OneArray
{
public static void main(String args[ ])
{
BufferedReader br = new BufferedReader(new InputStream(System.in));
Sysytem.out.println(“How many subjects: ?”);
int n = Integer.parseInt(br.readLine( ));
int[ ] marks = new int[n];

Page 107
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//store elements into array
for(int i=0; i<n; i++)
{
System.out.println(“Enter marks”);
Mraks[i] = Integer.parseInt(br.readLine( ));
}
//find total marks
int tot = 0;
for(int i=0;i<n;i++)
{
tot = tot + marks[i];
}
System.out.println(“Total marks =” +tot);
// find percent
float percent = (float)tot/n;
System.out.println(“Percentage =”+percent);
}
}

35.2 Multi-Dimensional Array:


 Multi-dimensional arrays represents 2D, 3D,.. arrays which are combinations of several types of
arrays.
 In this, data is stored in row and column based index also known as matrix form.
 For example, a two dimensional array is a combination of two or more 1D arrays and 3D arrays means
a combination of two or more 2D arrays.
 Syntax for two dimensional:
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
 Example to instantiate Multidimensional Array:
int[][] arr=new int[3][3];//3 row and 3 column
 Example to initialize Multidimensional Array
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
 We can declare a two dimensional array and directly store elements at the time of its declaration as:
int marks [ ] [ ] = { { 50, 60, 55, 67, 70}, { 62, 65, 70, 74, 70}, { 72, 66, 77, 80, 69}};
 Here ‘int’ represents integer type elements stored into array, and the array name is ‘marks’. To
represent a two dimensional array, we should use two pairs of square braces [ ] and [ ] after the array
name.
 Each row of elements should be written inside the curly braces { and }.
Page 108
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 The rows in each row should be separated by commas.
 So there are 3 rows and 5 columns in each row then the JVM creates 3X5 = 15 blocks of memory as
there are 15 elements being stored into the array.
 These blocks of memory can be individually referenced to as mentioned here:
marks[0][0], marks[0][1], marks[0][2], marks[0][3], marks[0][4]
marks[1][0], marks[1][1], marks[1][2], marks[1][3], marks[1][4]
marks[2][0], marks[2][1], marks[2][2], marks[2][3], marks[2][4]
 The elements in the array can be referred as “marks[i][j]”, where ‘i’ represents row position and ‘j’
represents column position.
 The memory arrangement of elements in a 2D array as follows:

Marks j=0 j=1 j=2 j=3 j=4


i=0 50 60 55 67 70
i=1 62 65 70 74 70
i=2 72 66 77 0 69
 Another way of creating a two dimensional array is by declaring the array first and then allocating
memory for it by using new operator.
int marks[ ] [ ] = new int [3] [5];
 Here, JVM allots memory for storing 15 integer elements into the array. But there are no actual
elements stored in the array, we can store these elements by accepting them from the keyboard.

Program 65: A java program on multi-dimensional array


class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println( );
}
}
}
OUTPUT:
123
245
445

Page 109
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 66: A java program Transpose of Matrix
import java.io.*;
import java.util.Scanner;
class Matrix
{
public static void main(String args[ ] ) throws IOException
{
Scanner sc = new Scanner(Sytem.in);
System.out.println(“Enter rows and column? “);
int r = sc.nextInt( );
int c = sc.nextInt( );
//creating an array
int arr[ ][ ] = new int [r][c];
//accept a matrix from keyboard
System.out.println(“Enter elements of matrix”);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
arr[i][j] = sc.nextInt( );
System.out.println(“The transpose matrix:”);
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
System.out.println(arr[j][i] +“ ”);
}
System.out.println(“\n”);
}
}
}

OUTPUT:
Enter rows, columns? 3 4
Enter elements of matrix:
1 2 3 4
5 6 7 8
9 9 -1 2
The transpose matrix:
1 5 9
2 6 9
3 7 -1
1 2

Page 110
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 67: A java program Addition of Matrix
class MatrixAdd
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println( );//new line
}
}
}
OUTPUT:
2 6 8
6 8 10

Program 68: A java program Multiplication of Matrix


 In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second
matrix.

Page 111
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//Multiplication Program
public class MatrixMultiplication
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]=c[i][j] + a[i][k]*b[k][j];
}//end of k loop
//printing matrix element
System.out.print(c[i][j]+" ");
}//end of j loop
System.out.println( );//new line
}
}
}

Page 112
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
36. Nested Classes
 In java, it is possible to define a class within another class, such classes are known as nested classes.
 Syntax:
class Outer
{
//class Outer members
class Inner
{
//class Inner members
}
} //closing of class Outer
 Advantages:
1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. It can lead to more readable and maintainable code.

36.1 Static Nested Classes:


 If the nested class i.e the class which is defined within another class, has prefix of static keyword is
called as static nested class.
 The static nested classes can access only static members of its outer class i.e it cannot refer to non-
static members of its enclosing class directly.
 The static members are accessed using the enclosing ‘class name’ as follows:
OuterClass.StaticNestedClass
 Syntax:
class MyOuter
{
static class Nested_Demo
{
}
}
 Initialize an object:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );

Program 69: A java program on static nested classes


public class Outer
{
static class Nested_Demo
{
public void my_method( )

Page 113
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("This is my nested class");
}
}
public static void main(String args[])
{
Outer.Nested_Demo nested = new Outer.Nested_Demo( );
nested.my_method( );
}
}
OUTPUT:
This is my nested class

Program 70: A java program on accessing members of static nested classes


class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass
{
void display( )
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can access display private static member of outer class
System.out.println("outer_private = " + outer_private);
// The following statement will give compilation error as static nested class cannot
//directly access non-static members
// System.out.println("outer_y = " + outer_y);
}
}
}
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );
nestedObject.display( );
}
}Output:
outer_x = 10
outer_private = 30

Page 114
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT-III
37. Relations between classes
 The main purpose of maintaining relations between classes is to achieve the “Reusability”.
 Reusability means using the properties of one class into another class.
 Java supports following 3 types of relations between the classes.
1) Uses-a relation (Weak (or) Association relation)
2) Has-a relation (Strong (or) Aggregation)
3) Is-a relation (Very strong (or) Composition)

37.1 Uses-a relation:


 If one class object is created inside the method of another class then those two classes are in “Uses-a”
relation.
 The scope of “Uses-a” is within the same method.
 Example Program:
class A
{
void f1( )
{
System.out.println(“Hello Java”);
}
}
class B
{
void f2( )
{
A oa = new A( );
oa.f1( );
}
void f3( )
{
oa.f1( );//Invalid method calling
}
}
class UsesaRealtion
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f2( );
ob.f3( );
}
}
 In the above example, class A and class B having a relation, class A properties can be used only inside
‘f2 ( )’ method of class B.

Page 115
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
37.2 Has-a relation:

 If one class object is created inside another class but outside the methods then those two classes are in
“Has-a” relation.
 The scope of “has-a” relation is throughout the class.
 Example program:
class A
{
void f1( )
{
System.out.println(“Hello Java”);
}
}
class B
{
A oa = new A( );
void f2( )
{
oa.f1( );
}
void f3( )
{
oa.f1( );//Valid method calling
}
}
class HasaRealtion
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f2( );
ob.f3( );
}
}

37.3 Is-a relation:


 It can be achieved by using “Inheritance”, this is very strong relation between the classes.
 It can be applied by using “extends” keyword.
 The main advantage is Re-usability.
 Follow the question no 38 for complete concept of inheritance.

Page 116
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
38. Inheritance
 Def:
1) Extending the properties of one class into another class is known as “Inheritance”.
(or)
2) Deriving a new class from the existing class is known as “Inheritance”.
 In java language, inheritance can be achieved by using “extends” keyword.
 The class which is giving the properties (variables and methods) is known as “parent/ super/ base
class”.
 The class which is taking the properties is known as “child/sub/derived class”.

 In the above diagram, programmatically can be represented as shown below:


class A //Super class
{
//methods and fields
}
class B extends A //Derived class
{
//methods and fields
}
 In real time, Inheritance can be used to achieve:
1) Re-Usability: Using the properties of super class by the derived class without redefining the
properties is known as “Re-usability”.
2) Extensibility: Adding new properties to the derived class without disturbing the super class
properties is known as “Extensibility”.
3) Re-Implementation: Providing a new logic to the super class method in the derived class by
maintaining same method name is known as “Re-Implementation”.
4) Method overriding: It can be achieved by run time polymorphism.
 Inheritance is mostly used while designing “Enhanced applications”. It means new updated versions
for the existing application.
 The default super class for every class is “Object” class available in “java.lang” package.
 Inheritance always supports from Top-to-Bottom. The Super class methods can be accessed directly
within the derived class methods. But derived class methods cannot be accessed directly in super class
methods.

Page 117
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 71: A java program on simple Inheritance
class Parent
{
public void p1( )
{
System.out.println("Parent method");
}
}
public class Child extends Parent
{
public void c1( )
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child( );
cobj.c1( ); //method of Child class
cobj.p1( ); //method of Parent class
}
}
OUTPUT:
Child method
Parent method

Program 72: A java program on simple Inheritance


class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle
{
String modelType;
public void showDetail( )
{
vehicleType = "Car"; //accessing Vehicle class member
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car( );
car.showDetail( );
}
}
OUTPUT:
sports Car

Page 118
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
38.1 Types of Inheritance in Java:
 Inheritance always can be done from “Top-to-Bottom”, that means super class properties are inherited
into derived class but derived class properties does not inherit in superclass.
 The various types are as follows:
1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance
5) Hybrid Inheritance
 In java, Single, multilevel and hierarchical is implemented at “class” level but multiple and hybrid
inheritance is implemented at “Interface” level only.

Page 119
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 73: A java program on single Inheritance

class Animal
{
void eat( )
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark( )
{
System.out.println("barking...");
}
}

class TestInheritance{
public static void main(String args[])
{
Dog d=new Dog( );
d.bark( );
d.eat( );
}
}
OUTPUT:
barking…
eating…

Program 74: A java program on Multi level Inheritance


class Animal
{
void eat( )
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark( )
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep( )
{

Page 120
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog( );
d.weep( );
d.bark( );
d.eat( );
}
}
OUTPUT:
weeping...
barking...
eating...

Program 75: A java program on Hierarchical Inheritance


class Animal
{
void eat( )
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark( )
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow( )
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat( );
c.meow( );
c.eat( );
//c.bark( );//Compile Time Error

Page 121
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
OUTPUT:
meowing...
eating...
38.2 Why multiple inheritance is not supported in java?
 Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and
B classes have same method and you call it from child class object, there will be ambiguity to call
method of A or B class.

Program 76: A java program on why multiple inheritance is not supported in java?

class A
{
void msg( )
{
System.out.println("Hello");
}
}
class B
{
void msg( )
{
System.out.println("Welcome");
}
}
class C extends A,B
{//suppose if it were
Public Static void main(String args[])
{
C obj=new C( );
obj.msg( );//Now which msg( ) method would be invoked?
}
}
OUTPUT:
Compile Time Error

38.2 Memory locations in inheritance:


 Whenever object is created for any class, memory is allocated not only for current class but also for all
the super classes in its hierarchy.
 Every derived class object can be referenced not only with same class reference but also with its super
class reference.
 Super class object cannot be referred with derived class reference.

Page 122
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 77: A java program methods accessing in inheritance
class A
{
void f1( )
{
System.out.println(“f1( ) of class A”);
}
}
class B extends A
{
void f2( )
{
System.out.println(“f2( ) of class B”);
}
void f3( )
{
System.out.println(“f3( ) of class B”);
}
}
class Inh
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f2( );
ob.f1( );
ob.f3( );
System.out.println(ob);
System.out.println(“………………”);
A oa = new A( );
oa.f1( );
oa.f2( );//Invalid
System.out.println(“……………..”);
Object o = new B( );
o.f1( );//Invalid because object class is the top class
o.f2( );//Invalid because object class is the top class
}
}

Page 123
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
39. ‘Super’ Keyword in java
 The super keyword in java language, which is used to refer super class object.
 It can be used in two ways:
1) super. at variable level
2) super. at method level
3) super( )
 Note: Without Inheritance, super keyword cannot be used.

39.1 super. at variable level


 It can be used to differentiate super class instance variable with formal parameters of either method or
constructor of derived class if both are existing with same name.
 Syntax: super.variablename;

Program 78: A java program on super. At variable level


class A
{
int x;
}
class B extends B
{
int x;
B(int x)
{
this.x = x + 2;
super.x = x+5;
System.out.println(“ X =” +x);
System.out.println(“ this.x =” +this.x);
System.out.println(“ Super.x =” +super.x);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
B ob = new B( );
}
}
OUTPUT:
X = 10
this.x = 12
super.x = 15

Page 124
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
39.2 super. at method level
 It can be used to differentiate super class method with derived class method, if both are existing with
same name.
 Syntax: super.methodname( );

Program 79: A java program super. At method level


class A
{
void f1( )
{
System.out.println(“f1( ) of A”);
}
}
class B extends A
{
void f1( )
{
Super.f1( );//calls super class method
System.out.println(“f2( ) of B”);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
B ob = new B( );
Ob.f1( );
}
}
OUTPUT:
f1( ) of A
f2( ) of B

39.3 super( ):
 It is used to call super class constructor within derived class constructor.
 Syntax: super ( ); and super(arguments);
 In real time, super( ) can be used to initialize instance variables of all the super classes along with
derived class by creating a single object.
 Super( ) must be first statement while calling other method or constructor and same as for this( ).

Program 80: A java program on super( )


class A
{
A(int x)
{
System.out.println(“A class constructor”);
}
}

Page 125
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class B extends A
{
B(double y)
{
super(10);
System.out.println(“B class constructor”);
}
}
class C extends B
{
C(String z)
{
super(10.34);
System.out.println(“C class constructor”);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
C oc = new C( “Java”);
}
}
OUTPUT:
A class constructor
B class constructor
C class constructor
 Super( ) must be the first statement inside the constructor.
 In every constructor the default first statement is super( ).
 Syntax:
ClassName( )
{
------- //super( ) is the default first statement
-------
}

Program 81: A java program on super( ) is the default first statement

class A
{
A( )
{
System.out.println(“A class constructor”);
}
}
class B extends A
{

Page 126
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
B( )
{
System.out.println(“B class Constructor”);
}
}
class SuperDemo
{
public static void main(String args[ ])
{
B ob = new B( );
}
}
OUTPUT
A class constructor
B class constructor

40. ‘final’ keyword in Java


 The final keyword in java is used to restrict the user.
 The java final keyword can be used in many context are as follows:
1) Variable
2) Method
3) Class
 The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable.
 It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only.

40.1 Java final variable:


 If you make any variable as final, you cannot change the value of final variable(It will be constant).
 Example: There is a final variable speed limit, we are going to change the value of this variable, but it
can't be changed because final variable once assigned a value can never be changed.

Program 82: A java program on Java final variable


class Bike9{
final int speedlimit=90;//final variable
void run( ){
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9( );
obj.run( );
}
}//end of class
OUTPUT:
Compile time error

Page 127
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
40.2 Java final method:
 If you make any method as final, you cannot override it.
 But it is possible to inherit the final method.

Program 83: A java program on Java final method


class Bike
{
final void run( ){System.out.println("running");}
}
class Honda extends Bike{
void run( ){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda( );
honda.run( );
}
}
OUTPUT:
Compile time error

40.3 Java final class:


 If you make any class as final, you cannot extend it.

Program 84: A java program on Java final class


final class Bike
{
void f1( )
{
System.out.println(“Java programming”);
}
}
class Honda1 extends Bike
{
void run( ){System.out.println("running safely with 100kmph");}
public static void main(String args[])
{
Honda1 honda= new Honda1( );
honda.run( );
}
}
OUTPUT:
Compile Time error

Page 128
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
40.4 Can we initialize blank final variable?
 Yes it is possible only in constructor.

Program 85: A java program checks to initialize blank final variable


class Bike10
{
final int speedlimit;//blank final variable
Bike10( )
{
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[])
{
new Bike10( );
}
}
OUTPUT:
70

40.5 Static blank final variable:


 A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

Example: A java program on static blank final variable


class A
{
static final int data;//static blank final variable
static
{
data=50;
}
public static void main(String args[])
{
System.out.println(A.data);
}
}

40.6 Final parameter in Java


 If you declare any parameter as final, you cannot change the value of it.

Program 86: A java program on final parameter


class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}

Page 129
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public static void main(String args[])
{
Bike11 b=new Bike11( );
b.cube(5);
}
}
Output: Compile Time Error

41. Dynamic Polymorphism


 Definition of Dynamic Polymorphism: Verifying super class method at compile time and executing
derived class method at runtime by following ‘polymorphism’ principle is known as “Dynamic
polymorphism/ Runtime polymorphism/ Late Binding”.
 In java language, it can be achieved by using “Overriding”.

41.1 Method Overriding:


 Definition of overriding: In java language, if the same method name is existing both in super and
derived class with same prototype (same return type, same method name and same signature) is known
as “Method Overriding”.
 Method overriding cannot exist without “Inheritance”.
 Sample Program:
class A
{
void f1( )
{
---------
---------
}
}
class B extends A
{
void f1( )
{
---------
---------
}
}
 The main purpose of overriding (or) re-implementation is to change the logic of super class method
within the derived class to provide new services to the end user.

Page 130
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 87: A java program on method overriding
class Vehicle
{
void run( )
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run( )
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2( );
obj.run( );
}
}
OUTPUT:
Bike is running safely

41.2 Rules of Method Overriding:


1) Method name must be same.
2) Method signature must be same.
3) Return type of both the methods must be same, in case of primitive data type and void.
4) If the return type of overridden method is a class then the return type of overriding method can be
same class or its derived class.
5) Without Inheritance it is not possible to achieve method overriding.
6) It is not possible to override static method.
7) Overriding of Java main method is not possible.

Program 88: A java program on Java method overriding of Bank Application


 Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%
and 9% rate of interest.

Page 131
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 89: A java program on bank application with method overriding
class Bank
{
int getRateOfInterest( )
{
return 0;
}
}
class SBI extends Bank
{
int getRateOfInterest( )
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest( )
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest( )
{
return 9;
}
}
class Test2
{
public static void main(String args[])
{
SBI s=new SBI( );
ICICI i=new ICICI( );
AXIS a=new AXIS( );
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest( ));
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest( ));
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest( ));
}
}
OUTPUT:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Page 132
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
42. Difference between method overloading and overriding
SNO Method Overloading Method Overriding
Method overriding is used to provide
Method overloading is used to increase the the specific implementation of the
1
readability of the program. method that is already provided by its
super class.
Method overriding occurs in two
Method overloading is performed within
2 classes that have IS-A (inheritance)
class.
relationship.
In case of method overloading, parameter In case of method overriding,
3
must be different. parameter must be same.
Method overloading is the example of Method overriding is the example of
4
compile time polymorphism. run time polymorphism.
In java, method overloading can't be
performed by changing return type of the
Return type must be same in method
5 method only. Return type can be same or
overriding.
different in method overloading. But you
must have to change the parameter.

43. Abstract classes in Java


43.1 Concrete Method:
 If nay method contains both ‘prototype’ and ‘method body’ is known as ‘concrete method’.
 Syntax:
returntype methodName(list of parameters) //method prototype
{
//method body
}
 If any class contains all concrete methods is known as ‘concrete class’.
 Java allows creating ‘object’ and ‘object reference’ for concrete class.

43.2 Abstract Method and Abstract Class:


 If any method contains only prototype without any method body is known as “Abstract
Method/Incomplete Method”.
 If any class contains at least one abstract method then that class becomes “Abstract class”.
 In java language both abstract method and abstract class should be preceded by ‘abstract’ keyword.
 Therefore the abstract method does not contain any method body, it contains only method header.
 Since, abstract class contains incomplete methods, it is not possible to estimate the total memory
required to create the object by the JVM.
 So, JVM cannot create objects to an abstract class. But we can create object reference to abstract class,
as this will not take any memory. Once the reference is created, it can be used to refer to the objects of
subclasses.
 Syntax: abstract returntype methodname( ); //abstract method
 We should create sub classes by using inheritance and all the abstract methods should be implemented
in the sub classes.
 Then it is possible to create object to the sub classes since they are becomes complete classes.
 An abstract class can contain concrete methods as well as abstract methods.

Page 133
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example:
abstract class A
{
void f1( )
{
-------
-------
}
abstract void f2( );
abstract void f3( );
}

43.3 Rules to be followed while working with abstract class:


1) Abstract class and abstract methods must preceded with ‘abstract’ keyword.
2) Abstract class can have concrete methods along with abstract methods.
3) Object reference can be created for abstract class but object cannot be created.
4) Concrete methods of abstract class can be accessed only within derived class object.
5) If any abstract class is inherited in other class then each and every abstract method must be
overridden in the derived class otherwise derived class also becomes ‘abstract’ class.

Program 90: A java program on abstract classes that all objects need different implementations of
the same method
abstract class MyClass
{
abstract void calculate(double x);
}
class Sub1 extends MyClass
{
void calculate(double x)
{
System.out.println(“Square=” +(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(doublex)
{
System.out.println(“Square root=” +Math.sqrt(x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
System.out.println(“Cube=” +(x*x*x));
}
}

Page 134
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class Sample
{
public static void main(String args[ ])
{
Sub1 obj1 = new Sub1( );
Sub2 obj1 = new Sub2( );
Sub3 obj1 = new Sub3( );
obj1.calculate(3);
obj1.calculate(3);
obj1.calculate(3);
}
}
OUTPUT:
Square = 9
Square root = 2.0
Cube = 125.0
 We cannot create an object to abstract class, but we can create a reference variable to it, as shown
here:
MyClass ref;
ref = obj1;
ref.calculate(3);
ref = obj2;
ref.calculate(4);
ref = obj3;
ref.calculate(5);

Program 91: A java program on abstract class that has abstract method
abstract class Bike
{
abstract void run( );
}
class Honda4 extends Bike
{
void run( )
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4( );
obj.run( );
}
}
OUTPUT:
running safely.

Page 135
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 92: A java program on abstract class that has abstract method

abstract class Shape


{
abstract void draw( );
}
class Rectangle extends Shape
{
void draw( )
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw( )
{
System.out.println("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1( );
s.draw( );
}
}
OUTPUT:
drawing circle

Program 93: A java program on abstract class on bank application


abstract class Bank
{
abstract int getRateOfInterest( );
}
class SBI extends Bank
{
int getRateOfInterest( )
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest( )
{
return 8;

Page 136
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI( );
System.out.println("Rate of Interest is: "+b.getRateOfInterest( )+" %");
b=new PNB( );
System.out.println("Rate of Interest is: "+b.getRateOfInterest( )+" %");
}
}
OUTPUT:
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Program 94: A java program on Abstract class having constructor, data member, methods
abstract class Bike
{
Bike( )
{
System.out.println("bike is created");
}
abstract void run( );
void changeGear( )
{
System.out.println("gear changed");}
}
class Honda extends Bike
{
void run( )
{
System.out.println("running safely..");
}
}
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda( );
obj.run( );
obj.changeGear( );
}
} OUTPUT:
bike is created
running safely..
gear changed

Page 137
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 95: A java program on Abstract class to calculate electricity bill and domestic plans
abstract class Plan
{
protected double rate;
public abstract void getRate( );
public void calculateBill(int units)
{
System.out.println(“Bill amount for “ +units + “units:”);
}
}
class CommercialPlan extends Plan
{
public void getRate( )
{
rate = 5.00;
}
}
class DomesticPlan extends Plan
{
public void getRate( )
{
rate = 2.60;
}
}
class calculate
{
public static void main(String args[ ])
{
Plan p;
System.out.println(“Commercial connection”);
p = new CommericailPlan( );
p.getRate( );
p.calculateBill(250);
System.out.println(“Domestic connection”);
p = new DomesticPlan( );
p.getRate( );
p.calculateBill(150);
}
}
OUTPUT:
Commercial connection
Bill amount for 250 units: 1250
Domestic connection
Bill amount for 150 units: 390

Page 138
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
44. Relation between Concrete class and Abstract Classes

1) If the parameter of any method is concrete class then that method will accept either same class object
or its derived class object.

Example:

2) If the parameter of any method is an ‘abstract’ class then that method will accept only its derived class
object.
Example:

Page 139
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) If the parameter of any method is an ‘object’ class then that will accept any concrete class object.
Example:

4) If the return type of any method is concrete class then that method will return either same class object
(or) its derived class object.
Example:

Page 140
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
5) If the return type of a method is ‘object’ class then that method can return any concrete class object.
Example:

6) If the return type is an ‘abstract’ class then that method returns only its ‘derived’ class objects.
Example:

Page 141
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
45. Interfaces
 The main disadvantage with ‘abstract class’ is, it doesn’t support “Multiple Inheritance” because of
‘ambiguity’ problem.
 Ambiguity problem always occurs while working with ‘concrete classes’.

 In the above example, java compiler will get confusion to verify which super class method of Class-C,
it is called ambiguity problem.
 To overcome above disadvantage of abstract class “Interface” was introduced.
 Interface is an alternative to abstract class mainly introduced to achieve the “Multiple Inheritance” in
java language.
 Interface is by ‘default’ abstract type so that no object can be created but it is possible to create object
reference.
 Interface is a collection of constant variables and abstract methods. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
 In other words, you can say that interfaces can have methods and variables but the methods declared in
interface contain only method signature, not body.

45.1 How to declare Interface in java:


 Interface is declared by using interface keyword.
 It provides total abstraction; means all the methods in interface are declared with empty body and are
public and all variables are “public static final” by default.
 A class that implement interface must implement all the methods declared in the interface.
 Syntax:
interface InterfaceName
{
datatype varname = value;
returntype method( );
}

Page 142
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example:
interface A
{
int x = 10; //constant
void f1( );
}
 Interface can be inherited in any class using ‘implements’ keyword.
 The java compiler adds public and abstract keywords before the interface method. More, it adds
public, static and final keywords before data members.

 If the parameter of any method is “Interface” then that method will accept any of its derived class
object.
 If the return type of any method is “Interface” then that method will return any of its derived class
object.

Program 96: A java program-1 on Interfaces

interface A
{
void f1( );
}
interface B
{
void f2( );
}
class C implements A, B//Multiple Inheritance
{
public void f1( )
{
System.out.println(“f1( ) of class C”);
}
public void f2( )
{
System.out.println(“f2( ) of class C”);
}
}
class InterfaceDemo
{
public static void main(String args[ ])
{
A oa = new C( );

Page 143
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
oa.f1( );
B ob = new B( );
Ob.f1( );
}
}
OUTPUT:
f1( ) of class C
f2( ) of class C
Memory organization of above example program 96:

45.2 Understanding relationship between classes and interfaces:


 A class can extends another class, an interface extends another interface but a class implements an
interface.

Program 97: A java program-2 on Interfaces


interface Drawable
{
void draw( );
}
class Rectangle implements Drawable
{
public void draw( )
{
System.out.println("drawing rectangle");
}
}
Page 144
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
class Circle implements Drawable
{
public void draw( )
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle( );
d.draw( );
}
}
OUTPUT:
drawing circle

Program 98: A java program on Interfaces bank application

interface Bank
{
float rateOfInterest( );
}
class SBI implements Bank
{
public float rateOfInterest( )
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest( )
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI( );
System.out.println("ROI: "+b.rateOfInterest( ));
}
}
OUTPUT:
ROI: 9.15

Page 145
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
45.3 Multiple inheritance in Java by interface
 Any class allows to inherit both class and multiple inheritance at a time.
 Syntax:
class DerivedClassName extends SuperClassName implements Interface1, Interface2
{
---------------------------
---------------------------
}
 Every abstract method of an interface must be overridden in its derived class otherwise derived class
also becomes abstract class.

Program 99: A java program on Multiple inheritance in Java by interface


interface Iface1
{
void f1( );
}
interface Iface2
{
void f2( );
}
class A
{
void f3( )
{
System.out.println(“F3( ) of class A”);
}
}
class B extends A implements Iface1, Iface2
{
public void f1( )
{
System.out.println(“F1( ) of class B”);
}
public void f2( )
{
System.out.println(“F2( ) of class B”);
}
}
class IfaceDemo
{
public static void main(String args[ ])
{
B ob = new B( );
ob.f1( );
ob.f2( );
ob.f3( );
}
}

Page 146
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:
F1( ) of class B
F2( ) of class B
F3( ) of class A

45.4 Inheritance in Interfaces:


 Java supports inheritance between interfaces that means one interface can be extended into other
interface.
 The main purpose of inheritance in interface is to improve the readability of the program.

 Interface supports all types of inheritances.


 Syntax:
interface IFace1
{
-------
-------
}
interface IFace2 extends IFace1
{
-------
-------
}
interface IFace3 extends IFace2
{
-------
-------
}

Program 100: A java program on Inheritance in Interfaces


interface Iface1
{
void f1( );
}
interface Iface2 extends Iface1
{
void f2( );
}

Page 147
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
interface Iface3 extends Iface2
{
void f3( );
}
class A implements Iface3
{
public void f1( )
{
System.out.println(“f1( ) of class A”);
}
public void f2( )
{
System.out.println(“f2( ) of class A”);
}
public void f3( )
{
System.out.println(“f3( ) of class A”);
}
}
class IFaceDemo
{
public static void main(String args[ ])
{
A oa = new A( );
oa.f1( );
oa.f2( );
oa.f3( );
}
}
OUTPUT:
f1( ) of class A
f2( ) of class A
f3( ) of class A

45.5 Static Method in Interface:


 Since Java 8, we can have static method in interface.

Program 101: A java program on static method in interface


interface Drawable
{
void draw( );
static int cube(int x)
{
return x*x*x;
}
}
class Rectangle implements Drawable
{

Page 148
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public void draw( )
{
System.out.println("drawing rectangle");
}
}
class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle( );
d.draw( );
System.out.println(Drawable.cube(3));
}
}
OUTPUT:
drawing rectangle
27

46. Difference between Abstract class and Interface

SNO Abstract Class Interface


Abstract class can have abstract and non- Interface can have only abstract
1
abstract methods. methods.
Abstract class doesn't support multiple
2 Interface supports multiple inheritance.
inheritance.
Abstract class can have final, non-final, static Interface has only static and final
3
and non-static variables. variables.
The abstract keyword is used to declare The interface keyword is used to declare
4
abstract class. interface.
An abstract class can extend another Java An interface can extend another Java
5
class and implement multiple Java interfaces. interface only.
A Java abstract class can have class members Members of a Java interface are public
6
like private, protected, etc. by default.
Example: Example:
public abstract class Shape public interface Drawable
7 { {
public abstract void draw( ); void draw( );
} }

Page 149
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
47. Java Package
 Package is a folder with collection of classes (concrete class or abstract class or Interface) and sub-
packages.
 The main purpose of package in real time is to use the classes of one computer in another computer.
 The main purpose of sub packages is to improve the searching the speed, identification of classes very
easily by the developer.
 Packages are categorized into following two types:
1) Predefined package (built-in package)
2) User defined package
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
 Advantage of Java Package:
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

47.1 Predefined Packages:


 These are the packages which are already available in Java language.
 These packages provide all necessary classes, interfaces and methods for the programmer to perform
any task in their programs.
 Since, Java has an extensive library of packages, a programmer need not think about logic for doing
any task.
 For everything, there is a method available in java and that method can be used by the programmer
without developing the logic on his own.
 The various important packages of Java SE are as follows:
1) java.lang:-
o ‘lang’ stands for language. This package got primary classes and interfaces essential for
developing a basic java program.
o It consists of wrapper classes which are useful to convert primitive data types into objects like
String, StringBuffer, to handle strings.
o Runtime and System classes are also present in ‘java.lang’ package which contain methods to
execute an application and find the total memory and free memory available in JVM.
2) java.util:-
o ‘util’ stands for utility. This package contains useful classes and interfaces like Stack,
LinkedList, HashTable, Arrays, Vector etc.
o These classes are called as collections.
o There are also classes for handling data and time operations.
o The mostly using class in java.util is ‘Scanner’. It is used to read the data dynamically from the
keyboard.
3) java.io:
o ‘io’ stands for input and output. This package contains streams. A stream represents flow of
data from one place to another place.
o Streams are useful to store data in the form of files and to perform reading and writing
operations.
4) java.awt:
o ‘awt’ stands for ‘abstract window toolkit’. This package used to develop GUI where programs
with colorful screens and images etc can be developed.

Page 150
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
o It consists of sub package, ‘java.awt.event’, which is useful to provide action for components
like push buttons, radio buttons, menus etc.
5) javax.swing:
o This package helps to develop GUI like ‘java.awt’. The ‘x’ in javax represents that it is an
extended package which means it is a package developed from another package by adding new
features to it.
o In fact, ‘javax.swing’ is an extended package of ‘java.awt’.
6) java.net:
o ‘net’ stands for network. Client-server programming can be done by using this package.
o Classes related to obtaining authentication for a network, creating sockets at client and server
to establish communication between them.
7) java.applet
o Applets are programs which come from a server into a client and get executed on the client
machine on a network.
o Applet class of this package is useful to create and use applets.
8) java.sql:
o ‘sql’ stands for structure query language. This package is helpful to connect to databases like
Oracle, mySql, etc. to retrieve the data from them and use it in a java program.

47.2 User defined Packages:


 If any package is created by the developer for specific applications and developers purpose is known
as “User defined packages”.
 Java supports ‘package’ keyword to create our own user defined package.
 Syntax:
1) package packagename; //to create a package
2) package packagename.subpackagename; //to create a sub package within a package
 Rules to create user defined package:
1) Package statement must be the first statement of package program.
2) Package program should not contain ‘main( )’ method.
3) Package program should contain only one ‘public class’ or ‘public interface’.
4)Every program must be saved with ‘public classname.java’.
 Syntax to compile java package:
 javac -d directory javafilename.java

Page 151
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
For example:
 javac -d . A.java

The -d switch specifies the destination where to put the generated class file. If you want to keep
the package within the same directory, you can use . (dot).

Program 102: A java program java package


package P1;
public class A
{
void f1( )
{
System.out.println("Welcome to package P1");
}
}

package P2;
public class B
{
void f2( )
{
System.out.println("Welcome to package P2");
}
}
 How to run java package:
To Compile: javac -d . A.java
To Run: java P1.A
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The .
represents the current folder.

47.3 Using of packages:


 There are three ways to access the package from outside the package.
1) import package.*;
2) import package.classname;
3) fully qualified name.

47.3.1 Using packagename.*


 If you use package.* then all the classes and interfaces of this package will be accessible but not sub
packages.
 The import keyword is used to make the classes and interface of another package accessible to the
current package.
Program 103: A java program of package that import the packagename.*
//save by A.java
package pack;
public class A
{
public void msg( )

Page 152
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
System.out.println("Hello");
}
}
public class C
{
public void display( )
{
System.out.println(“In class C”);
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A( );
obj.msg( );
}
}
Output: Hello

47.3.2 Using packagename.classname


 If you import package.classname then only declared class of this package will be accessible.

Program 104: A java program of package by import package.classname


//save by A.java
package pack;
public class A
{
public void msg( ){System.out.println("Hello");}
}
public class C
{
public void msg( ){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[]){
A obj = new A( );
obj.msg( );
}
}
Output: Hello
Page 153
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example 2:
//save by Addition.java
package pack;
public class Addition
{
private double d1, d2;
public Addition(double a, double b)
{
d1= a;
d2 = b;
}
public void sum( )
{
System.out.println(“Sum=” +(d1+d2));
}
}
//save Use.java
import pack.Addition
class Use
{
public static void main(String args[ ])
{
Addition obj = new Addition(10.2, 11.5);
obj.sum( );
}
}
OUTPUT:
>javac Use.java
>java Use
Sum = 21.7

47.3.3 Using fully qualified name


 If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface.
 Syntax: packagename.classname;

Program 105: A java program of package by import fully qualified name


//save by A.java
package pack;
public class A
{
public void msg( )
{
System.out.println("Hello");
}
}

Page 154
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A( );//using fully qualified name
obj.msg( );
}
}
Output: Hello
 Example 2:
class Demo
{
public static void main(String args[ ])
{
java.util.Scanner sn = new java.util.Scanner(System.in);
System.out.println(“Enter first no”);
int n1=sn.nextInt( );
System.out.println(“Enter second no”);
int n2=sn.nextInt( );
System.out.println(n1+n2);
}
}

48. Exception Handling


 A software engineer may have several errors while developing the code. These errors are also
called ‘bugs’ and the process of removing bugs is called ‘debugging’.
 There are basically 3 types of errors in the java program:
1) Compile-time errors: These are syntactically errors found in the code, due to which a program
fails to compile. For example, semicolon missing at the end of the java statement.
Example:
class Err
{
public static void main(String args[ ] )
{
System.out.println(“Hello”) //semicolon missing
}
}
2) Run-time errors: These errors represent inefficiency of the computer system to execute a
particular statement. For example, insufficient memory. These are generally generated because of
‘invalid inputs’.
Example:
class Err
{
public static void main( ) //parameter missing
{
System.out.println(“Hello”);
}
}
Page 155
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) Logical Errors: These errors describe flaws in the logic of the program. The programmer might
be using a wrong formula or the design of the program itself is wrong. These are not detected
either by Java compiler or JVM. Programmer is solely responsible for them.
Example:
class Err
{
public static void main(String args[ ] )
{
double sal= 5000.0;
sal = sal*15/100; //sal+ = sal*15/100;
System.out.println(“Incremented salary =” +sal);
}
}

48.1 Exception Handling:


 Def1: In end user point of view converting system defined error message to user friendly error
message is known as “Exception Handling”.
 Def2:In developer point of view, providing valid information about the exception like exception name,
exception message, line number etc. is known as “Exception Handling”.
 In java language, exception handling can be achieved by using “Try-catch” block.
 Exception handling is a problem identification technique but not problem solving technique.

48.2 Types of exceptions:

1) Predefined Exception:
 If any exception class is already designed by “SUN MICRO SYSTEMS” and raised commonly
in every java program is known as ‘predefined exception’.
2) Asynchronous Exception:
 These are the exceptions raised because of hardware failure or memory failures. These
exceptions cannot handle by developer.
3) Synchronous Exception:
 These exceptions raised because of ‘invalid inputs’. Every synchronous can be handled using
‘try-catch( )’ block.

Page 156
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4) Checked Exceptions:
 The exceptions that are checked at compilation time by the java compiler are called “Checked
Exceptions”.
 Example: IOException, SQLException, etc.
5) Unchecked Exceptions:
 The exceptions that are checked by the JVM are called ‘unchecked exceptions’.
 Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc.
6) User defined exceptions:
 If any exception class is created by the developer is known as ‘user defined exception’, in real
time these are out dated.
 In checked exception, the programmer should either handle them with ‘try-catch( )’ or throw them
without handling them. Consider the following example:
public static void main(String args[ ]) throws IOException
 Here, IOException is an example of checked exception. So we re-throwing to main( ) method without
handling it. This is done by ‘throws’ clause written after main( ) method.
 All exceptions are declared as classes in Java. All these classes are descended from a super class called
“Throwable”.

 Throwable is a most super class that represents all errors and exceptions which may occur in Java.
 Exception is the super class of all exceptions in java.
 Examples scenarios where exceptions may occur:
1) 'ArithmeticException occurs if we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) NullPointerException occurs if we have null value in any variable, performing any operation by the
variable occurs an NullPointerException.
String s=null;
System.out.println(s.length( ));//NullPointerException

Page 157
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) NumberFormatException occurs if the wrong formatting of any value, may occur
‘NumberFormatException’. Suppose I have a string variable that have characters, converting this
variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) ArrayIndexOutOfBoundsException occurs if you are inserting any value in the wrong index, it
would result ArrayIndexOutOfBoundsException as shown below:
int a[ ]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

 Java Exception Handling Keywords:


There are 5 keywords used in java exception handling.
1) try
2) catch
3) finally
4) throw
5) throws

48.3 Handling of Exceptions:


 In java language, exception handling can be achieved using “try-catch( )” block.
 ‘Try’ is a keyword can be used as block, known as try block and it contains the business logic.
 ‘catch’ is a keyword also used as block, it contains logic to display exception message, it is technically
known as catch block.
 Syntax of try-catch:
try
{
//statements
}
Catch(ExceptionClassName ref)
{
//logic to display exception message
}
 Syntax of try-finally:
Try
{
//code that may throw exception
}finally{}
Program 106: A java program without exception handling:
public class Testtrycatch1
{
public static void main(String args[])
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
OUTPUT:
Exception in thread main java.lang.ArithmeticException:/ by zero

Page 158
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 In the above example, “System.out.println("rest of the code...");”statement is not going to
executed. If there can be 100 lines of code after exception. So all the code after exception will not
be executed.
 Solution by exception handling:
Let's see the solution of above problem by java try-catch block.

Program 107: A java program solution of program No. 106 by exception handling

public class Testtrycatch2


{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
OUTPUT:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

 Now as displayed in the above example, rest of the code is executed i.e. rest of the code... statement
is printed.

48.3 Rules to work with ‘try-catch( )’ block:


1) If no exception is raised in try block all the statements of that block is executed by neglecting catch
block.
2) If any exception is raised in try block:
a) JVM creates an object for that exception class and thrown to catch block.
b) The statements of catch block are executed if that object is matching with the given class name.
3) Try block should contain business logic.
4) Catch block should contain logic to display exception message.
5) Control enters into try block whenever program is executed.
6) Catch block is executed whenever exception is raised.
7) One try block can have any number of exceptional statements but only one will be raised at time.
8) One try block can have many number of catch blocks but only one catch block can be executed at a
time.
try
{
------
------
}
catch(ExceptionClassName1 ref)
{
------
Page 159
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
------
}
catch(ExceptionClassName2 ref)
{
------
------
}
9) Once the control comes outside the try block then control never return back to try block.
10) No statements should exist between try and catch block/
11) No try block can exist without catch block. But it is possible with finally block.
12) No catch block can exist without try block.
13) Catch block always should be followed by try block.
14) Try block must exist inside the method body either in main( ) method or any user defined method.
15) The variable whatever defined inside the try block acts as local variable.
Example:
void f1( )
{
int x = 10; //local variable in f1( )
try
{
int y=20; //localvar in try block
}
catch(ExceptionClassName1 ref)
{
-------
-------
}
}
16) Java allows to define multiple “try-catch( )” pairs to handle multiple exceptions at a time.
Example:
try
{
-------
}
catch(ExceptionClassName1 ref)
{
-------
}
try
{
-------
}
catch(ExceptionClassName1 ref)
{
-------
}
17) Java allows to define nested try-catch( ) blocks.

Page 160
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 108: A java program on Number Format exception
class NFException
{
public static void main(String args[ ])
{
try
{
int fn = Integer.parseInt(s[0]);
int sn = Integer.parseInt(s[1]);
System.out.println(“Sum is:”+(fn+sn));
}
catch (NumberFormatException e)
{
System.out.println(“Pls provide only numeric inputs”);
}
}
}
OUTPUT:
 java NFException 10 5
sum is: 15
 java NFException Ten Five
Pls provide only numeric inputs

Program 109: A java program on Multiple catch Exceptions


class MulDemo
{
public static void main(String args[ ])
{
try
{
int fn = Integer.parseInt(s[0]);
int sn = Integer.parseInt(s[1]);
int res = fn/sn;
System.out.println(“Result is:”+res);
}
catch (NumberFormatException e)
{
System.out.println(“pls proved only numeric inputs”);
}
catch (ArithmeticException e)
{
System.err.println(e);
}
}
}
OUTPUT:
 java MulDemo Ten Five
pls proved only numeric inputs

Page 161
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 java MulDemo 10 5
Result is: 2
 java MulDemo 10 0
java.lang.ArithmeticException: / by zero

Program 110: A java program on Multiple try-catch Exception


import java.util.Scanner;
class Edemo
{
public static void main(String args[ ])
{
Scanner sn = new Scanner(System.in);
try
{
System.out.println("Enter class name:");
String cname = sn.nextLine( );
Class c = Class.forName(cname);
Object o = c.newInstance( );
}
catch(ClassNotFoundException e)
{
System.err.println(e);
}
catch(InstantiationException e)
{
System.err.println(e);
}
catch(IllegalAccessException ie)
{
System.err.println(ie);
}
try
{
int fn = 10;
int s = 0;
int res = fn/s;
System.out.println(res);
}
catch(ArithmeticException e)
{
System.err.println(e);
}
}}
OUTPUT:

Page 162
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
48.4 Handling of unknown exceptions:
 If developers knows which type of exception is going to be raised in “try-block( )” is known as
“Known exception”.
 If developer doesn’t knows which type of exception is going to be raised in try-catch( ) block is
called as “Unknown Exception”.
 Unknown exceptions can be handled by “Exception” class.
 Syntax1:
try
{
-----
-----
}
catch(Exception e)//Exception class can handle any exception which is raised in try-block
{
String s = e.getMessage( );
System.out.println(s);//It will display only exception message
}
 Syntax 2:
try
{
-----
-----
}
catch(Exception e)
{
System.err.println(e);//It will exception class name and message
}
 Syntax 3:
try
{
-----
-----
}
catch(Exception e)
{
e.printStackTrace( );//It will exception class name, error message and line number
}

Page 163
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 111: A java program to handle multiple exceptions using common catch block
import java.util.Scanner;
class Edemo
{
public static void main(String s[ ])
{
try
{
int fn = Integer.parseInt(s[0]);
int sn = Integer.parseInt(s[1]);
int res = fn/sn;
System.out.println(res);
int a[ ] = {10, 20, 30};
System.out.println(a[sn]);
}
catch(Exception e)
{
e.printStackTrace( );
}
}
}
OUTPUT:

48.5 Finally Block:


 Finally is a keyword in java language used to hold the mandatory executable statements of “try-
catch( )” block.
 Finally will be executed irrespective of raising of exception that means whether exception is raised
or not raised.
 Finally block should exist after “try-catch( )” only.
 Syntax:
try
{
----
}
catch(Exception e )
{
----
}
finally
{
----
}
 Examples: Finally block can have closing database connection logic, destroying the objects etc.

Page 164
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 112: A java program to handle exceptions with finally block
import java.util.Scanner;
class Edemo
{
public static void main(String args[ ])
{
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter index:");
int i = sc.nextInt( );
String s = "Visakhapatnam";
System.out.println(s.charAt(i));
}
catch(Exception e)
{
e.printStackTrace( );
}
finally
{
System.out.println("Hello Java");
}
}
}
OUTPUT:

Page 165
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
48.6 Finally Block:
 Throws is a keyword in java language, used to throw the exception which is raised in method body
to its calling method.
 Throws keyword always should be followed by ‘method header’.
 Syntax 1:
returntype methodName( ) throws ExceptionClass1, ExceptionClass2, … //for known
exception
{
-----------
-----------
}
 Syntax 2:
returntype methodName( ) throws Exception //for un-known exception
{
-----------
----------- }
 Advantages:
1) Burden on the API developers are reduced.
2) Time consuming process will be reduced while working with exception handling.

Program 113: A java program on throw keyword

public class TestThrow1


{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
OUTPUT:
Exception in thread main java.lang.ArithmeticException: not valid

48.7 Re-throwing of exception:


 Whatever the exception is thrown by JVM is thrown back to JVM once again is known as “Re-
throwing of exception”.
 In real time it isn’t recommended because it gives extra burden to the JVM leads to decrease system
performance.

Page 166
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Example:
class Edemo
{
public static void main(String args[ ] ) throws Exception
{
Class C = Class.forName(s[0]);
Object o = C.newInstance( );
}
}
 In the above example, whatever the exceptions are raised in main( ) method are re-throwing to JVM
without handling using ‘try-catch( )’ block.
 The difference between ‘throw’ and ‘throws’ keyword is, throws is used to throw the predefined or
user defined exception whereas ‘throw’ keyword is used to throw the user defined exceptions only.

48.8 User defined exceptions:


 If you are creating your own Exception that is known as custom exception or user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
 By the help of custom exception, you can have your own exception and message.

Program 114: A java program on user defined exception


class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
Page 167
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:
Exception occured: InvalidAgeException: not valid
rest of the code..

Program 115: A java program on user defined exception


class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

public class Main


{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex)
{
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage( ));
}
}
}
OUTPUT:
Caught
GeeksGeeks

Page 168
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
49. Java Assertions
 Assertion is a statement in java. It can be used to test your assumptions about the program.
 While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
 Advantage of Assertion: It provides an effective way to detect and correct programming errors.
 Syntax- 1 of using Assertion:
assert expression;
 Syntax- 2 of using Assertion:
assert expression1 : expression2;
 If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.

Program 116: A java program on Assertions


import java.util.Scanner;
class Edemo
{
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
System.out.print("Enter ur age ");
int value = scanner.nextInt( );
assert value>=18:" Not valid";
System.out.println("value is "+value);
}
}

OUTPUT:

Page 169
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
50. Collection Frameworks in Java
 Collections in java is a framework that provides an architecture to store and manipulate the group of
objects.
 All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
 Java Collection simply means a single unit of objects.
 Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
 Collection represents a single unit of objects i.e. a group.
 In traditional approach arrays concept was used to manipulate the data but because of some limitations
of arrays, that is replaced with ‘collections’.
 Limitations of array:
1) Array is having fixed size.
2) Array can handle only similar type of data or objects.
3) It is very difficult to perform data manipulations on arrays like searching, sorting , insertion,
deletion, updation, appending, retrieving etc.
 Advantages with collections:
1) It is grow able in size.
2) Every collection is a generic type so that it can handle dissimilar type of data.
3) It is very easy to perform data manipulations because of predefined API available of collections.
4) Collection supports both insertion and deletion operations.

 All collection classes are available in ‘java.util’ package and the implementation classes of different
interfaces are as follows:

SNO Interface Type Implementation Classes


HashSet<T>
1 Set<T>
LinkedHashSet<T>
Stack<T>
LinkedList<T>
2 List<T>
ArrayList<T>
Vector<T>
3 Queue<T> LinkedList<T>
HashMap<K,V>
4 Map<K,V>
HashTable<K,V>

Page 170
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Sets:
1) A set represents a group of elements arranged just like an array.
2) The set will grow dynamically when the elements are stored into it.
3) A set will not allow duplicate elements.
4) If we try to pass same elements that is already available in the set, then it is not stored into the
set.
 Lists:
1) Lists are like sets. They store a group of elements.
2) Lists allows duplicate values to be stored.
 Queues:
1) A queue represents arrangement of elements in FIFO order.
2) This means that an element that is stored as a first element into the queue will be removed first
from the queue.
 Maps:
1) Maps store elements in the form of key and value pairs. If the key is provided then its
corresponding value can be obtained. All the keys should have unique values.
 For any collection class object can be created as shown below:
CollectionClass <Element Type> ref = new CollectionClass<Element Type>( );
 It is predefined class in ‘java.util’ package contains predefined methods to perform data manipulation
operations on retrieved data from database.
1) sort( ): It is a predefined static method in collections class used to arrange the given elements in
ascending order.
2) reverse( ): It is a predefined method in collections class used to reverse the order which is currently
available in collection object.

50.1 Stack Class:


 A stack represents a group of elements stored in LIFO order. This means that the element is stored as a
last element into the stack will be first element to be removed from the stack.
 Inserting elements (objects) into the stack is called ‘push operation’ and removing element into the
stack is called ‘pop operation’.
 Searching an element in the stack is called ‘peep operation’.
 Insertion and deletion of elements take place only from one side of the stack called ‘top’ of the stack.
 The syntax of stack class as:
class Stack<E>
 In the above, ‘E’ stands for element type and the stack object creation that contains Integer objects as
follows:
Stack<Integer> obj = new Stack<Integer>( );
 Stack Class Methods:
1) booelan empty( ): This method tests whether the stack is empty or not. If the stack is empty
then TRUE otherwise returns FALSE.
2) element peek( ): This method returns the top most object from the stack without removing it.
3) element pop( ):This method pops the top most element from the stack and returns it.
4) element push(element obj):This method pushes an element ‘obj’ onto the top of the stack and
returns that element.
5) int search(Object obj):This method returns the position of an element ‘obj’ from the top of the
stack. If the element (object) is not found in the stack then it returns ‘-1’.

Page 171
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 117: A java program on Stack class
import java.util.*
class stackdemo
{
pubic static void main(String[ ] args)
{
Stack <integer> s=new Stack <integer>( );
s.push(40);
s.push(30);
s.push(16);
s.push(25);
System.out.println(s);
boolean b=s.empty( );
System.out.println (b);
int i=s.peek( );
System.out.println (i);
int p=s.search(10);
System.out.println (p);
Collections.sort(s);
System.out.println ("ascending order :"+s);
Collections.reverse(s);
System.out.println ("descending order "+s);
s,pop( );
System.out.println (s);
s.pop( );
System.out.println (s);
}
}

50.2 Linked List Class:


 A linked list contains a group of elements in the form of nodes. Each node will have three fields: the
data field contains the data and the link fields contain references to previous and next nodes.
 A linked list creation is in the form of:
class LinkedList<Element>
 In the above, ‘E’ stands for element type and the linked list object creation that contains objects as
follows:
LinkedList<String>ll = new LinkedList<String>( );
 The important points about Java LinkedList are:
a) Java LinkedList class can contain duplicate elements.
b) Java LinkedList class maintains insertion order.
c) Java LinkedList class is non synchronized.
d) In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
e) Java LinkedList class can be used as list, stack or queue.
 Linked List Methods:
a) void add(int index, Object element):-It is used to insert the specified element at the specified
position index in a list.
b) void addFirst(Object o): It is used to insert the given element at the beginning of a list.
c) void addLast(Object o): It is used to append the given element to the end of a list.
Page 172
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
d) int size( ):It is used to return the number of elements in a list
e) boolean add(Object o): It is used to append the specified element to the end of a list.
f) boolean contains(Object o): It is used to return true if the list contains a specified element.
g) boolean remove(Object o): It is used to remove the first occurence of the specified element in
a list.
h) Object getFirst( ): It is used to return the first element in a list.
i) Object getLast( ):It is used to return the last element in a list.

Program 118: A java program on Linked List class


import java.util.*;
class Tdemo
{
public static void main(String[ ] args)
{
LinkedList<String> LL=new LinkedList<String>( );
LL.add("hyderabad");
LL.add("banglore");
LL.add("hyderabad");
System.out.println(LL);
LL.addFirst("chennai");
System.out.println (LL);
boolean b=LL.contains("banglore");
System.out.println (b);
System.out.println (LL.get(3));
LL.remove(4);
System.out.println (LL);
Collections.reverse(LL);
System.out.println (LL);
LL.clear( );
System.out.println (LL);
}
}

50.3 Array List Class:


 An ArrayList is like an array, which can grow in memory dynamically. It means that when we store
elements into the ArrayList, depending on the number of elements, the memory is dynamically
allocated and re-allocated to accommodate all the elements.
 The ArrayList can be written as:
class ArrayList<E>
 Where ‘E’ represents the type of elements to be stored into the ArrayList. We can create an object to
ArrayList as:
ArrayList<String> arl = new ArrayList<String>( );
 The important points about Java ArrayList class are:
a) Java ArrayList class can contain duplicate elements.
b) Java ArrayList class maintains insertion order.
c) Java ArrayList class is non synchronized.
d) Java ArrayList allows random access because array works at the index basis.

Page 173
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
e) In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if
any element is removed from the array list.
 Array List Methods:
a) void add(int index, Object element)- It is used to insert the specified element at the specified
position index in a list.
b) boolean addAll(Collection c): It is used to append all of the elements in the specified
collection to the end of this list, in the order that they are returned by the specified collection's
iterator.
c) void clear( ): It is used to remove all of the elements from this list.
d) int lastIndexOf(Object o): It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.
e) Object[] toArray( ): It is used to return an array containing all of the elements in this list in
the correct order.
f) Object[] toArray(Object[] a): It is used to return an array containing all of the elements in
this list in the correct order.
g) boolean add(Object o): It is used to append the specified element to the end of a list.
h) boolean addAll(int index, Collection c): It is used to insert all of the elements in the specified
collection into this list, starting at the specified position.
i) int indexOf(Object o): It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
j) void trimToSize( ): It is used to trim the capacity of this ArrayList instance to be the list's
current size.

Program 119: A java program on Array List class

//Array list withstring obiects


import java.util.*;
class ArrayListDemo
{
public static void main(string args[])
{
//create ArrayList
ArrayList<string> arl =new ArrayList<string>( );
//add four objects
arl.add("Apple");
arl.add("Mango");
arl.add("Grapes");
arl.add("Guava");
//display contents
System.out.println("Contents: "+arl);
//remove two objects
arl.remove(3);
arl.remove("Apple");

//display again
System.out.println("Contents after removing: "+arl);
//display its size
System.out.println("Size of Arraylisrt: "+arl.Size( ));

Page 174
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//extract elements using Iterator
System.out.println("Extracting using Iterator);
//add an Iterator to ArrayList to retreive elements
Iterator it = arl.iterator( );

while(it.hasNext( ))
{
System.out.println("it.next( ));
}
}
}

50.4 HashSet Class:


 A “HashSet” represents a set of elements (objects). It doesn’t guarantee the order of elements and also
does not allow duplicate elements to be stored.
 We can create the HashSet class as:
class HashSet<T>
 Where <T> represents the generic type parameter. It represents which type of elements are being
stored into the HashSet. Suppose, we want to create a HashSet to store a group of strings then we can
create the object as:
HashSet<String> hs = new HashSet<String>
 HashSet class Methods:
a) boolean add(obj): This method adds an element obj to the HashSet. It returns true if the
element is added to the HashSet, else it returns false. If the same element is already available in
the HashSet, then the element is not added.
b) boolean remove(obj): This method moves the element obj from the HashSet, if it is present. It
returns TRUE if the element is removed successfully otherwise FALSE.
c) void clear( ): This removes all the elements from the HashSet.
d) boolean contains(obj): This returns TRUE if the HashSet contains the specified element obj.
e) boolean isEmpty( ): This returns true if the HashSet contains no element.
f) int size( ): This returns the number of elements present in the HashSet.

Program 120: A java program on HashSet class


import java.util.*;
class Hsdemo
{
public static void main(String[ ] args)
{
HashSet<String> hs=new HashSet<String> ( );
hs.add("delhi");
hs.add("hyderabad");
hs.add("banglore");
hs.add("hyderabad");
System.out.println(hs);
boolean b=hs.contains("banglore");
System.out.println(b);
hs.remove("delh");
System.out.println(hs);

Page 175
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
hs.clear( );
System.out.println(hs);
}
}

50.5 Hash Map Class:


 HashMap is a collection that stores elements in the form of key-value pairs.
 If key is provided, its corresponding value can be easily retrieved from the HashMap.
 Keys should be unique. This means we cannot use duplicate data forkeys in the HashMap.
 HashMap is not synchronized and hence while using multiple threads on HashMap object gets
unreliable results.
 We can create HashMap class as:
class HashMap<K,V>
 Where ‘K’ represents the type of key element and ‘V’ represents the type of value element. To store a
String as key and an Integer object as its value as:
HashMap<String, Integer> hm = new HashMap<String,Integer>( );
 HashMap class methods:
a) put(key, value): This method stores key-value pair into the HashMap.
b) get(Object key): This method returns the corresponding value when key is given. If the key
doesn’t have a value associated with it, then it returns null.
c) Set<k>keyset( ): This method, when applied on a HashMap object returns all the keys will be
stored.
d) Collection<V>Values( ): This method, when applied on a HashMap object returns all the
values on the HashMap in to a Collection object.
e) clear( ): This method removes all the key-value pairs from the map.
f) isEmpty( ): This method returns true if there are no key-value pairs in the HashMap.
g) Size( ): This method returns number of key-value pair in the HashMap.

Program 121: A java program on HashMap class


import java.util.*
class hmdemo
{
public static void main(String[ ] args)
{
HashMap<Interger,Double> hm=new HashMap<Interger,Double>( );
hm.put(1,78.3);
hm.put(2,68.3);
hm.put(3,88.3);
hm.put(4,58.3);
System.out.println(hm);
Collection<Double> c=hm.values( );
System.out.println(c);
Set<Integer> s=hm.keySet( );
System.out.println(s);
boolean b1=hm.containsKey(3);
System.out.println(b1);
boolean b2=hm.containsValues(62.7);
System.out.println(b2);
Page 176
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
hm.remove(2);
System.out.println(hm);
}
}

50.6 HashTable Class:


 HashTable is similar to HashMap which can store elements in the form of key-value pairs.
 HashTable is synchronized assuring proper results even if multiple threads act on it simultaneously.
 We can create HashTable class as:
class HashTable<K,V>
 Where ‘K’ represents the type of key element and ‘V’ represents the type of value element. For
example, to store a String as key and an Integer object as its value as follows:
HashTable<String, Integer> ht = new HashTable(String,Integer>( );
 HashTable class Methods:
a) put(key,value): This method stores key-value pair into the Hashtable.
b) Value get(Object key): This method returns the corresponding value when key is given. If the
key does not have a value associated with it, then it returns null.
c) Set<k> keyset( ): This method, applied on a HashTable converts it into a Set where only keys
will be stored.
d) Collection<V> values( ): This method, when applied on a HashTable object returns all the
values of the HashTable in to a Collection object.
e) Value remove(Object key): This method removes the key and corresponding value from the
HashTable.
f) void clear( ): This method removes all the key-value pairs from the HashTable.
g) boolean isEmpty( ): This method returns true if there are no key-value pairs in the HashTable.
h) int size( ): This method returns the number of key-value pairs in the HashTable.

Program 122: A java program on HashTable class


//Hashtable with cricket player names and their scores
import java.io.*;
import java.util.*;
class HashtableDemo
{
public static void main(String args[]) throws IOExecption
{
//create Hashtable with names and scores
Hashtable<String, Integer> ht = new Hashtable<String, Integer>( );
ht.put("Ajay", 50);
ht.put("Sachin", 77);
ht.put("Gavaskar", 44);
ht.put("Kapil", 60);
ht.put("Dhoni", 88);
//display all player names using enumerator
System..out.println("The player names: ");
Enumeration e = ht.keys( );
while(e.hasMoreElements( ))
System.out.println(e.nextElements( ))
//accept player name from keyboard
Page 177
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System+-.out.print("Enter player name : ");
String name= br.readLine( );
name= name.trim( ); //remove unneccessary spaces
//.get score of the player
Integer score= ht.get(name);
if(score != null)
{
//convert score from Integer object to int vale
int sc=score.intvalue( );
system.out.print.ln(name+"Scored: "+sc);
}
else System.out.println("Player not found");
}
}

50.7 Vector Class:


 A vector also stores elements (objects) similar to ArrayList. It is synchronized and even if several
threads acts on Vector object simultaneously, the results will be reliable.
 We can create Vector class as follows:
class <Vector>
 Here, ‘E’ represents the type of elements stored into the Vector. For example, if we want to create an
empty Vector that can be used to store Float type objects as follows:
Vector<Float> v= new Vector<Float>( );
 The default capacity of Vector will be 10. For example:
Vector<Integer> v= new Vector<Integer>(101);
 The above vector ‘v’ can store Integer objects and 101 is the capacity of the Vector.
 Another way of creating a Vector object is by specifying a ‘capacity increment; which specifies how
much capacity should be incremented when the Vector is full with elements as follows:
Vector<Integer> v = new Vector<Integer>(101, 20);
 The above Vector ‘v’, 101 is the capacity of the Vector and capacity is incremented to 20 if it is full.
 Vector class methods:
a) booelan add(element obj): This method appends the specified element to the end of the
Vector. If the element is added successfully then the it returns true.
b) void add(int position, element obj): This method inserts the specified element at the specified
position in the Vector.
c) booelan remove(int position): This method removes the element at the specified position in
the Vector. This method also returns the element which was removed from the Vector.
d) void clear( ): This method returns all the elements from the Vector.
e) element set(int pos, element obj): This method replaces an element at the specified position
in the Vector with the specified element obj.
f) boolean contains(Object obj): This method returns true if the Vector contains the specified
element obj.
g) element get(int pos): This method returns the element available at the specified position in the
Vector.
h) int size( ): This method returns the number of elements present in the Vector.
i) int capacity( ): This method returns the current capacity of the Vector.
Page 178
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 123: A java program on Vector class
//Creating a vector with integer elements
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
//take a vector to store Integer objects
vector<Integer> v = new Vector<Integer>( );
//take a int array
int x[]={22,20,10,40,15,60};
//when x[i] is stored into v below.x[i] values are converted int
//Integer objects and stored into v, This is auto boxing.
for(int i=0; i<x.length; i++)
{
v.add(x[i]);
}
//retreive the elements get( )
System.out.println("Vector elements: ");
for(int i=0; i<v.size( ); i++)
{
System.out.println(v.get(i));
}
//retrieve using ListIterator
system.out.println("Elements using List Iterator: ");
ListIterator lit = v.listIterator( );
System.out.println("In forward direction: ");
while(lit.hasNext( ))
System.out.print(lit.next( )+"\t");
System.out.println("\nIn backward direction: ");
while(lit.hasPrevious( ))
System.out.print(lit.preious( )+"\t");
}
}

Page 179
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60. Multi-Threading

 Multi-Tasking:
1) If multiple applications are running simultaneously is known as “Multi-tasking”. It is also known as
process based multi-tasking.
2) Example: In windows O.S. playing a song using media player, downloading a software from any
website, performing operations in calculator etc. can be done simultaneously.

3) Following two concepts were introduced from multi-tasking, these are designed at programming
language level.
a) Multi Processing
b) Multi Threading
 Multi-Processing:
If multiple programs of same application is running simultaneously for multiple requests is
known as ‘Multi-processing”.

 Multi Threading:
If the same program of same application is running simultaneously for multiple requests of end
user is known as “Multi Threading”.

 Java Supports both ‘Multiprocessing’ and ‘Multithreading’. But multithreading can be used in the
development of ‘server softwares’ to control number of requests of end users.

Page 180
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.1 Multithreading in Java:
 Task:
1) A task is nothing but executing set of instructions.
2) Performing or executing more than one task simultaneously is called mutli tasking.
3) Multi tasking is of two types:
a) Process based multi tasking
b) Thread based multitasking
 Process based multi tasking:
1) A process is an instance of a program that is being executed.
2) Process based multi tasking means executing more than one process simultaneously.
3) A program is the smallest unit of code that can be dispatched by the scheduler.
4) Processes are light weight tasks that require their own separated address space.
 Thread based multi threading:
1) A thread is an independent path of execution with in a program.
2) Thread is the smallest unit of dispatchable code.
3) A single program can perform two or more tasks simultaneously.
4) A thread is a light weight task that share same address space.
5) In java, if multiple threads are running simultaneously is known as “Multi-Threading”.
6) In end user point of view, thread is a request and JVM point of view thread is flow of execution.
7) The main advantage with multi-threading is to reduce the end users waiting time while sending
multiple requests to the same program of same application.
8) Thread doesn't block the user because threads are independent and you can perform multiple
operations at same time.
9) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

60.2 Thread life Cycle:


 For every thread predefined 5 states are available and these will be processes automatically by the
JVM while sending request to any program of real time application.
 The java thread states are as follows:
1) New
2) Runnable
3) Running
4) Non-Runnable (Blocked)
5) Terminated

Page 181
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) New: When a new request is send to the server, a new thread will be created. The thread is in new
state if you create an instance of Thread class but before the invocation of start( ) method.
2) Runnable: The thread is in runnable state after invocation of start( ) method, but the thread
scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it, which means the
thread is in under execution.
4) Non-Runnable(Blocked): This is the state when the thread is still alive, but the execution is
stopped temporarily.
5) Terminated (Dead): A thread is in terminated or dead state when its run( ) method exits.
 The thread will be executed only once if it is in ‘new’ and ‘dead’ state.
 If thread is in runnable/running/waiting state, memory is available for that and also these operations
will be performed multiple times.

60.3 Creation of thread:


 Java language provides following two classes in ‘java.lang’ package to create our own user defined
Thread classes.
1) By implementing Runnable Interface
2) By extending Thread Class
 Runnable Interface:
1) It is predefined interface used to create our own Thread class by implementing it.
2) Runnable interface have only one method named run( ).
3) ‘run( )’ method is a predefined method should be overridden in its derived class, the logic whatever
was written inside will be executed multiple times simultaneously for every new request from the user.
Syntax:
public class ClassName implements Runnable
{
public void run( )//used to perform action for a thread.
{
------
------
}

 Thread Class:
1) It is predefined class also can be used to create our own user defined ‘Thread’ class, it was
implemented from ‘Runnable’ interface.
2) Thread class provides constructors and methods to create and perform operations on a thread.
3) Constructors of Thread class:
a) Thread( ): Allocates a new thread object and gives default name for thread like thread-0, thread-
1, etc.
b) Thread(String name): Allocates a new thread object and gives user defined name for that
thread.
c) Thread(Runnable thread): Allocates a new thread object for given resource and gives default
name for thread.
d) Thread(Runnable thread, String name): Allocates a new thread object for given resource and
gives user defined name for that thread.

Page 182
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
4) Methods of Thread Class:
a) public void run( ): is used to perform action for a thread.
b) public void start( ): starts the execution of the thread. JVM calls the run( ) method on the
thread.
c) public void sleep(long milliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
d) public void join( ): waits for a thread to die/terminate.
e) public void join(long milliseconds): waits for a thread to die/terminate for the specified
milliseconds.
f) public int getPriority( ): returns the priority of the thread.
g) public int setPriority(int priority): changes the priority of the thread.
h) public String getName( ): returns the name of the thread.
i) public void setName(String name): changes the name of the thread.
j) public Thread currentThread( ): returns the reference of currently executing thread.
k) public int getId( ): returns the id of the thread.
l) public boolean isAlive( ): tests if the thread is alive.
m) public void yield( ): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
n) public void suspend( ): is used to suspend the thread.
o) public void resume( ): is used to resume the suspended thread.
p) public void stop( ): is used to stop the thread.
q) public void interrupt( ): interrupts the thread.
r) public boolean isInterrupted( ): tests if the thread has been interrupted.
s) public ThreadState getState( ): returns the state of the thread.
t) public boolean isDaemon( ): Tests if the thread is daemon thread.
u) public void setDaemon(boolean b): Marks the thread as daemon or user thread.

 Steps to create the thread program:


a) Step 1: Create any user defined class and make that one as derived class of either ‘Thread’
class or ‘Runnable’ Interface.
b) Step 2: Override run( ) method and write the required logic.
Syntax: public class ClassName extends Thread
{
public voidrun( )
{
-------
-------
}
c) Step3: It is mandatory to define ‘Thread’ class as public.
d) Step 4:Create object for derived class.
e) Step 5: Create individual thread class objects and pass main resource as a parameter.
Syntax:
ClassName cn = new ClassName( );
Thread t1 = new Thread(cn);
Thread t2 = new Thread(cn);
Thread t3 = new Thread(cn);
- In the above, 3 threads are created for single resource.

Page 183
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
f) Call the run( ) method with the help of start( ) method.
Example:
t1.start( );
t2.start( );

Program 124: A Java program by extending Thread class


import java.io.*;
class Multi extends Thread
{
public void run( )
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi( );
t1.start( );
}
}
Output:
thread is running...
 In the above program 124:
1) Thread class constructor allocates a new thread object.
2) When we create an object to ‘Multi’ class, the class constructor is invoked by compiler from where
Thread class constructor is invoked by super( ) as first statement. So, Multi class object is thread
object now.

Program 125: Java Thread Example by implementing Runnable interface


import java.io.*;
class Multi3 implements Runnable
{
public void run( )
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3( );
Thread t1 =new Thread(m1);
t1.start( );
}
}
OUTPUT:
thread is running...
 In the above program 125:
1) If we are not extended Thread class then the class object is not treated as thread object.
2) Thread class object should be explicitly created.

Page 184
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) Class object of the class that is implementing Runnable is passed as parameter to Thread
constructor, so that class ‘run( )’ method may execute.

Program 126: A java program to create a thread


import java.io.*;
class MyThread extends Thread
{
public void run( )
{
for(int i=1; i<=1000; i++)
{
System.out.println(i);
}
}
}
class Tdemo
{
public static void main(String args[ ])
{
MyThread obj = new MyThread( );
obj.start( );
}
}

OUTPUT:

 Note:
1) When we extend Thread class there is no scope to extend any other class. This is a limitation.
2) When we implement Runnable interface there is scope for extending any other class.
 If you are not extending the Thread class, your class object would not be treated as a thread object. So
you need to explicitly create Thread class object.

Page 185
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 127: A java program to stop a Thread in middle
import java.io.*;
class MyThread implements Runnable
{
boolean stop =false;
public void run( )
{
for(int i=1; i<=1000; i++)
{
System.out.println(i);
if(stop) return;
}
}
}
class TDemo
{
public static void main(String args[ ]) throws IOException
{
//Create an object to MyThread class
MyThread obj = new MyThread( );
//attach an object to obj.
Thread t1 = new Thread(obj);
//start thread
t1.start( );
//Accept enter key from keyboard
System.in.read( );
//then make stop as true
obj.stop=true;
}
}
OUTPUT:

Page 186
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 128: Example of sleep method in java
class TestSleepMethod1 extends Thread
{
public void run( )
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TestSleepMethod1 t1=new TestSleepMethod1( );
TestSleepMethod1 t2=new TestSleepMethod1( );
t1.start( );
t2.start( );
}
}
Output:
1
1
2
2
3
3
4
4
 As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time, the thread scheduler picks up another thread and so on.

Program 129: Example of sleep method of single thread


class A
{
void add( )
{
try
{
int a =5, b=10, c;
c=a+b;
Thread.sleep(3000);

Page 187
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println(c);
}
catch(Exception e)
{
System.err.println(e);
}
}
}
class Tdemo
{
public static void main(String a[ ])
{

for (long i=1;i<100;i++)


{
A oa=new A( );
oa.add( );
}
}
}
OUTPUT:

Program 130: Example of sleep method of multithread


class TDemo extends Thread
{
public void run( )
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}

Page 188
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TDemo t1=new TDemo( );
TDemo t2=new TDemo( );
t1.start( );
t2.start( );
}
}
OUTPUT:

Program 131: A java program to control main thread


import java.io.*;
class TDemo
{
public static void main(String args[])
{
System.out.println("My Program");
Thread t = Thread.currentThread( );
System.out.println("Current Thread:"+t);
System.out.println("Thread name is:"+t.getName( ));
}
}
OUTPUT:

Page 189
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.4 Creating Multiple Threads on different objects
 In muti tasking, several tasks are executed at a time. For this purpose, we need more than one thread.
 For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks and these tasks
are executed simultaneously by the two threads.
 So, using more than one thread is called “Multi-Threading”.

Program 132: A Java program to create multiple threads that act upon different object on Theatre
Management
import java.io.*;
class MyThread implements Runnable
{
String str;
MyThread(String str)
{
this.str = str;
}
public void run( )
{
for(int i=1;i<=10;i++)
{
System.out.println(str +":" +i);
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
}
}
class TDemo
{
public static void main(String args[])
{
MyThread obj1 = new MyThread("Cut Ticket");
MyThread obj2 = new MyThread("Show Chair");
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start( );
t2.start( );
}
}

Page 190
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

60.5 Creating Multiple Threads on single object


 In the above theatre example, we have used 2 threads on the 2 objects of “MyThread” class.
 It is also possible to use 2 or more threads on a single object. But it leads to unreliable results.
 When two people perform same task, then we need same object (run( ) method) to be executed each
time.
 For example, in railway reservation every day several people want reservation of a berth for them.
 The procedure to reserve the berth is same for all the people. So we need same object with same run( )
method to be executed repeatedly for all the people.

Program 133: A Java program to create multiple threads that act upon single object
import java.io.*;
class Reserve implements Runnable
{
int available=1;//available berths are 1
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run( )
{
//display available berths
System.out.println("Available berths =" +available);
//if availble berths are more than wanted berths
if(available>=wanted)
{
//get name of the passenger
String name = Thread.currentThread( ).getName( );

Page 191
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//allot the berth to the passenger
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);//wait for printing the ticket
available = available -wanted;//update the no.of available berths
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are availble");
}
}
class TDemo
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
//attach first thread to the object
Thread t1 = new Thread(obj);
//attach second thread to the same object
Thread t2 = new Thread(obj);
//set name to the thread
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}
OUTPUT:

Page 192
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.6 Thread Synchronization:
 When two or more threads need access to a shared resource, they need some way to ensure that the
resources will be used by only one thread at a time.
 When a thread is already acting on a object, preventing any other from acting on the same object is
called “Thread Synchronization” or “Thread safe”.
 Thread synchronization is recommended when multiple threads are used on the same object.
 Synchronized object is like a locked object, locked on a thread called as “mutually exclusive lock”.
 Synchronization can be achieved in two ways:
1) Using synchronized block: Here, we can embed a group of statements inside run( ) method in a
synchronized block.
Syntax:
synchronized(object)
{
statements;
}
The statements inside the synchronized block are all available to only one thread at a time. They are
not available to more than one thread simultaneously.
2) Using synchronized keyword: Here, we can synchronize an entire method by using synchronized
keyword.
Example:
synchronized void display( )
{
statements;
}

Program 134: A Java program to create multiple threads that act upon single object using
synchronized block
import java.io.*;
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run( )
{
synchronized(this)
{
System.out.println("Available berths =" +available);
if(available>=wanted)
{
String name = Thread.currentThread( ).getName( );
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);
Page 193
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
available = available -wanted;
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are availble");
}
}
}
class TDemo1
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}

OUTPUT:

Program 135: A Java program to create multiple threads that act upon single object using
synchronized keyword
import java.io.*;
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
synchronized public void run( )
{

Page 194
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
System.out.println("Available berths =" +available);
if(available>=wanted)
{
String name = Thread.currentThread( ).getName( );
System.out.println(wanted +" Berths reserved for " +name);
try
{
Thread.sleep(1500);
available = available -wanted;
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
}
else
System.out.println("Sorry, no berths are available");
}
}
class TDemo1
{
public static void main(String args[])
{
Reserve obj = new Reserve(1);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.setName("First Person");
t2.setName("Second Person");
t1.start( );
t2.start( );
}
}
OUTPUT:

Page 195
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
60.7 Thread Communication:
 In some cases, two or more threads should communicate with each other.
 For example: Producer - Consumer problem.
 A Consumer thread is waiting for a Producer to produce the data. When the Producer thread
completes production of data, then the Consumer thread should take that data and use it.

Program 136: A Java program shows how two threads can communicate with each other
import java.io.*;
class Communicate1
{
public static void main(String args[]) throws Exception
{
//Producer produces some data which Consumer consumes
Producer obj1 = new Producer( );
//Pass Producer object to Consumer so that it is then available to Consumer
Consumer obj2 = new Consumer(obj1);
//Creation of threads and attach to Producer and Consumer
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//Run the threads
t2.start( );//Consumer waits
t1.start( );//Producer starts production
}
}
class Producer extends Thread
{
//For adding data, we use string buffer object
StringBuffer sb;
//data provider will be true when data production is over
boolean dataprovider = false;
Producer( )
{
sb=new StringBuffer( );//allocating memory
}
public void run( )
{
for(int i=1;i<=10;i++)
{
try
{
sb.append(i+":");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
System.err.println(e);
}

Page 196
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
dataprovider=true;
}
}
class Consumer extends Thread
{
//create Producer reference to refer to Producer object from Consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run( )
{
//If the data production is not over, sleep for 10 milli seconds and check again.
try
{
while(!prod.dataprovider)//This while llop will be broken if ‘dataprovider’ is true
{
Thread.sleep(10);
}
}
catch(Exception e)
{
System.err.println(e);
}
//When the data production is over, display data of StringBuffer
System.out.println(prod.sb);
}
}
OUTPUT:

Key Points:
 In the above program 136: The communication between Producer and Consumer is not in a effective
way because at some point Consumer finds the ‘dataprovider’ is false and it goes into sleep for the
next 10milliseconds.

Page 197
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Mean while, the data production may be over. But Consumer comes out of after 10 milliseconds and
then only it can find ‘dataprovider’ is true.
 This means that there may be a time delay of 1 to 9 milliseconds to receive the data after its actual
production is completed.
 So to improve the efficiency of communication between threads “java.lang.Object” class provides 3
methods:
1) obj.notify( ):This method releases an object and sends a notification to a waiting thread that the
object is available.
2) obj.notifyAll( ):This method is useful to send notification to all waiting threads at once that the
object is available.
3) obj.wait( ): This method makes a thread wait for the object till it receives a notification from
notify( ) or notifyAll( ) methods.
 It is recommended to use the above methods inside a synchronized block.

Program 137: A Java program to demonstrate thread communication using wait( ) and notify( )
methods
import java.io.*;
class Communicate1
{
public static void main(String args[]) throws Exception
{
//Producer produces some data which Consumer consumes
Producer obj1 = new Producer( );
//Pass Producer object to Consumer so that it is then available to Consumer
Consumer obj2 = new Consumer(obj1);
//Creation of threads and attach to Producer and Consumer
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
//Run the threads
t2.start( );//Consumer waits
t1.start( );//Producer starts production
}
}
class Producer extends Thread
{
//For adding data, we use string buffer object
StringBuffer sb;
//dataprovider will be true when data production is over
Producer( )
{
sb=new StringBuffer( );//allocating memory
}
public void run( )
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{

Page 198
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
try
{
sb.append(i+":");
Thread.sleep(1000);
System.out.println("appending");
}
catch(Exception e)
{
System.err.println(e);
}
}
//data production is over, so notify to Consumer thread
sb.notify( );
}
}
}
class Consumer extends Thread
{
//create Producer reference to refer to Producer object from Consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod = prod;
}
public void run( )
{
synchronized(prod.sb)
{
//wait till a notification is received from producer thread. Here there is no
wastage //of time of evena single millisecond
try
{
prod.sb.wait( );
}
catch(Exception e)
{
System.err.println(e);
}
//When the data production is over, display data of StringBuffer
System.out.println(prod.sb);
}
}
}

Page 199
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

KeyPoints:
 In the above program 137: there will not be any wastage of a single millisecond time to receive the
adat by the consumer.
 There is no need to use ‘dataprovider’ variable at Producer side. We can directly send a notification
immediately after the data production is over.
 Here, sb.notify( )is sending a notification to the Consumer thread that the StringBuffer object sb is
available and it can be used now.

60.8 Thread Priority:


 A thread’s priority is used to decide when to switch from one running thread to the next.
 Thread priorities are used by the thread scheduler to decide when each thread should be allowed to
run.
 Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority.
 To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. The general
form is:
final void setPriority(int level)
 Here, level specifies the new priority setting for the calling thread using following 3 constant final
variable are as follows:
a) public static int MIN_PRIORITY
b) public static int NORM_PRIORITY
c) public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.
 To obtain the current priority setting by calling the getPriority( ) method of Thread is:
final int getPriority( )

Program 138: A java program on Thread priorities


class Myclass extends Thread
{
int count=0;
public void run( )
{
for(int i=1;i<=5;i++)
Page 200
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
count++;
//display which thread has completed counting and its priority
System.out.println("Completed thread: "+Thread.currentThread( ).getName( ));
System.out.println("Its priority: "+Thread.currentThread( ).getPriority( ));
}
}
}
class Prior
{
public static void main(String args[])
{
Myclass obj = new Myclass( );
//Create two threads
Thread t1 = new Thread(obj, "One");
Thread t2 = new Thread(obj, "Two");
//set priorities for them
t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);
//starting threads
t1.start( );
t2.start( );
}
}
OUTPUT:
Completed Thread: Two
Its priority: 5
Completed Thread: One
Its priority: 2

Page 201
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61. I/O Streams
 Definition of stream:Stream is flow of data or sequence of data.
 If the data is flow from input component to java program is known as “Input Stream” and if the data
is flow from java program to output component is known as “Output Stream”.

 Input component can be keyboard, file, client machine, etc. and output components can be monitor,
server machine etc.
 Java supports ‘I/O streams’ concept to perform reading and writing operations on input and output
components respectively with the help of predefined classes which are available in ‘java.io.’ package.
 Java supports to perform writing and reading operations on any type of files like text file, image file,
audio file, video file etc.
 In java, System class is found in “java.lang” package and has three fields as follows:
1)System.in: This represents “InputStream” class object, by default represents standard input device
i.e. keyboard.
2) System.out: This represents “OutputStream” class object, by default represents standard output i.e.
monitor. It is used to display normal messages and results.
3) System.err:This filed also represents “PrintStream” object, which by default represents monitor. It
is used to display error messages.
 In ‘java.io’ package all the stream classes are categorized in to following two types:
1) Character Stream Classes: These are the predefined classes used to perform both reading and
writing operations on ‘character data’. Example: doc, pdf, txt files etc.
2) Byte Stream Classes: These are the predefined classes used to perform both reading and writing
operations on ‘character data’ and ‘binary data’. Example: jpeg, png, etc.
 Hierarchy of I/O Stream Classes:

Page 202
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Operations on Files:
1) Open the file.
2) Writing data into the file.
3) Reading data from the file.
4) Copy the file from one location to another file.
5) Delete the file.
6) Create a new file
 Writer:
It is the most super class for all writing related classes used to perform writing operations on character
data.
 Reader:
It is the most super class for all reading related classes used to perform reading operations on character
data.
 OutputStream:
It is the most super class for all writing related classes used to perform writing operations on binary
data and character data.
 InputStream:
It is the most super class for all reading related classes used to perform reading operations on binary
data and character data.
 Following predefine classes can be used while performing operations on files:
1) File
2) FileReader
3) FileWriter
4) FileInputStream
5) FileOutputStream

 File:
It is a predefined class in ‘java.io’ package can be used to represent given file in the form of
object, it provides predefined methods to perform various operations on files like finding length on the
file, finding name, extension of the file, creation of new file, removing the existing file etc.
Syntax: File ref = new File(String pathofthefile);
61.1 FileWriter:
It is used to perform writing operations on character files like txt, pdf, doc etc.
Syntax 1: FileWriter fw = new FileWriter(String pathofthefile);
In the above syntax 1, it always verifies the file in the given location, if it is available that file
will be opened and setting writing mode. If the file is not available it creates a new file in the same
location.
Syntax 2: FileWriter fw = new FileWriter(String pathofthefile, true);
In the above syntax2, opens the file in appending mode.
Syntax 3: File f = new File(String pathofthefile);
FileWriter fw = new FileWriter(f);
In the above syntax 3, opens the file in writing mode.
Syntax 4: File f = new File(String pathofthefile);
FileWriter fw = new FileWriter(f, true);
In the above syntax 4, opens the file in the appending mode.
Note: It is highly recommended to close the file once its operation is completed.

Page 203
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61.2 FileReader:
1) It is a predefined class used to perform reading operation on character files.
2) FileReader class open the given file in reading mode, if the file is not existing then it raises
‘FileNotFoundException’.
Syntax 1: FileReader fr = new FileReader(String pathofthefile); //open the file in reading mode
Syntax 2: File f = new File(String pathofthefile);
FileReader fr = new FileReader(f);// open the file in reading mode.

Program 139: A java program to write the string data in to text file using ‘FileWriter’ class
import java.io.*;
class FWDemo
{
public static void main(String args[])
{
try
{
FileWriter fw = new FileWriter("D:\\sample.txt");
fw.write("Hello Java Programming");
fw.close( );
System.out.println("File writing successful");
}
catch(IOException e)
{
System.err.println(e);
}
}
}
Note: It is highly recommended to close the file once its operation is completed.

What will happen while creation of file with following syntax?


FileWriter fw = new FileWriter(“sample.txt”);
Ans) File will be created in the same location where the current java program was saved.

Program 140: A java program to read the string data from the text file using ‘FileReader’ class
import java.io.*;
class FrDemo
{
public static void main(String args[])
{
try
{
FileReader fr = new FileReader("D:\\sample.txt");
int ch;
while((ch=fr.read( ))!=-1)
{
System.out.println((char)ch);
}
fr.close( );

Page 204
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
catch(IOException e)
{
System.err.println(e);
}
}
}

61.3 FileOutputStream:
1) It is a predefined class used to perform writing operation both on binary files like image, audio,
video files etc. and on character files.
2) While working with ‘FileOutputStream’ if the file is not available then it creates a new file.
Syntax 1: FileOutputStream fos = new FileOutputStream(String pathofthefile); //open file in writing
//mode
Syntax 2: FileOutputStream fos = new FileOutputStream(String pathofthefile, true); //open file in
//appending mode
Syntax 3: File f = new File(String pathofthefile);
FileOutputStream fos = new FileOutputStream(f); //open file in writing mode
Syntax 4: File f = new File(String pathofthefile);
FileOutputStream fos = new FileOutputStream(f, true); //open file in appending mode

Program 141: A java program on File Output Stream on character file


import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes( );//converting string into byte array
fout.write(b);
fout.close( );
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Page 205
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
61.4 FileInputStream:
1) It is a predefined class used to perform reading operation both on binary files like image, audio,
video files etc. and on character files.
2) While working with ‘FileInputStream’ if the file is not available then it raises File not found
exception.
Syntax 1: FileInputStream fis = new FileInputStream (String pathofthefile); //open file in reading
//mode
Syntax 2: File f = new File(String pathofthefile);
FileInputStream fos = new FileInputStream (f); //open file in reading mode

Program 142: A java program to read the data from character file using ‘FileInputStream’ class
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read( ))!=-1)
{
System.out.print((char)i);
}
fin.close( );
}
catch(Exception e)
{
System.out.println(e);
}
}
}

61.5 Random Access File:


 Using a random access file, we can read from a file as well as write to the file.
 Reading and writing using the file input and output streams are a sequential process.
 Using a random access file, we can read or write at any position within the file.
 An object of the RandomAccessFile class can do the random file access. We can read/write bytes and
all primitive types values to a file.
 RandomAccessFile can work with strings using its readUTF( ) and writeUTF( ) methods.
 The RandomAccessFile class is not in the class hierarchy of the InputStream and OutputStream
classes.
 It contains various mode of operations named as follows:
1) “r” - The file is opened in a read-only mode.
2) “rw” - The file is opened in a read-write mode. The file is created if it does not exist.
 We create an instance of the RandomAccessFile class by specifying the file name and the access
mode.
RandomAccessFile raf = new RandomAccessFile("randomtest.txt", "rw");
Page 206
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 A random access file has a file pointer that moves forward when we read data from it or write data to
it.
 The file pointer is a cursor where our next read or write will start.
 Its value indicates the distance of the cursor from the beginning of the file in bytes.
 We can get the value of file pointer by using its getFilePointer( ) method.
 When we create an object of the RandomAccessFile class, the file pointer is set to zero.
 We can set the file pointer at a specific location in the file using the seek( ) method.
 The length( ) method of a RandomAccessFile returns the current length of the file. We can extend or
truncate a file by using its setLength( ) method.

Program 143: A java program on Random Access File


import java.io.*;
public class RandomAccessFileDemo1
{
public static void main(String[] args)
{
try
{
// create a new RandomAccessFile with filename test
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
// write something in the file
raf.writeUTF("Hello World");
// set the file pointer at 0 position
raf.seek(0);
// print the string
System.out.println("" + raf.readUTF( ));
// set the file pointer at 5 position
raf.seek(5);
// write something in the file
raf.writeUTF("This is an example");
// set the file pointer at 0 position
raf.seek(0);
// print the string
System.out.println("" + raf.readUTF( ));
}
catch (IOException ex)
{
ex.printStackTrace( );
}
}
}

Page 207
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT IV
62. Applets in java
 Applet is a Java byte code program embedded in a HTML (Hyper Text Markup Language) page.
 It runs inside the browser and works at client side. So applet = java byte code + HTML page.
 The Applet class is contained in the java.applet package.

62.1 Types of Applets:


 The first type of applets use the Abstract Window Toolkit (AWT) to provide the graphical user
interface.This style of applet has been available since Java was first created.
 The second type of applets are those based on the Swing class JApplet, which inherits Applet. Swing
applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user
interface than does the AWT.
62.2 Applet Basics:
 AWT-based applets are subclasses of Applet. Applets are not stand-alone programs. Instead, they run
within either a web browser or an applet viewer.
 Execution of an applet does not begin at main( ) method.
 The Output of applet’s window is not performed by System.out.println( ). Rather, in an AWT-based
applet, output is handled by drawString( ) method, which is a member of the Graphics class, which
outputs a string to a specified X,Y location.
Syntax: void drawString(String message, int x, int y)
 To deploying an applet, it is to specify the applet directly in an HTML file. For this we required an
APPLET tag.
 When an APPLET tag is encountered in the HTML file, the specified applet will be executed by a
Java-enabled web browser.
 Example:
<html>
<applet code="MyApplet.class" width=200 height=60>
</applet>
</html>
 This HTML contains an APPLET tag that will run an applet called MyApplet in awindow that is 200
pixels wide and 60 pixels high.
62.3 Applet Life cycle:
 To create an applet, we have ‘java.applet’ package which contains following methods of ‘Applet’
class, which are run automatically by any applet program.
 These methods should be overridden in any applet program.
1) public void init( ):
 This method is the first method to be called by the browser and it is executed only once.
 So, the programmer can use this method to initialize any variables, creating components and
creating threads etc.
 When this method execution is completed, the control moves to the start( ) method.
2) public void start( ):
 This method is called after init( ) method and each time the applet is revisited by the user.
 For example, if the user has minimized the web page that contains the applet and moved to
another page then this methods execution is stopped.
 When the user comes back to view the web page again, start( ) method execution will resume.
 This method contains only business logic and the results are also displayed.

Page 208
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
3) public void stop( ):
 This method is called by the browser when the applet is to be stopped.
 If the user minimizes the web page, then this method is called and when the user again comes
back to this page then start( ) method is called.
 In this way start( ) and stop( ) methods can be called repeatedly.
4) public void destroy( ):
 This method is called when the applet is being terminated from memory.
 The stop( ) method will always be called before destroy( ).
 The code related to releasing the memory allocated to the applet and stopping any running
threads should be written in this method.

Hierarchy of Applet

 Executing init( ), start( ), stop( ) and destroy( ) methods in a sequence is called as “Life Cycle of an
Applet” .
 Note that the ‘public static void main(String args[])’ method is not available in applets. It means we
can
compile the applet code but we cannot run it by JVM.
 Once the applet is created, we can compile and obtain its byte code. This byte code is embedded in
HTML page and the page is sent to the client computer.
 The client machine contains a various browsers which are used to execute the applet program.
 The browser contains a small virtual machine called “applet engine” which understands and run the
applet code.
 Applets can show images and animations, play sounds, take user input and send it to the server.
 AWT-based applets also override the paint( ) method, which is defined by the AWT Component class.
 This method is called when the applet’s output must be redisplayed.

62.4 Advantage of Applet:


 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.

Page 209
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
62.5 java.awt.Component class
 This Component class provides one life cycle method of applet.
 public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
62.6 Example of Applet skeleton:
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public void init( )
{
//initialization
}
public void start ( )
{
//start or resume execution
}
public void stop( )
{
//suspend execution
{
public void destroy( )
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}

Program 144: A java program on Sample Applet


//Applet program
import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
public void init( )
{
setBackground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawString(“Hello java applet”, 100, 100);
}
}
 javac Myapp.java

Page 210
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
//Myapp.html
<html>
<applet code = “Myapp.class” height = 300 width = 400>
</applet>
</html>
 appletviewer Myapp.html
OUTPUT:

Program 145: A java program on to create different shapes in applet


//GraphicsDemo.java program
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.drawOval(70,200,30,30);
}
}

// GraphicsDemo.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Page 211
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

Program 146: A java program on to fill colors in shape using applets


import java.applet.*;
import java.awt.*;
public class Myapp extends Applet
{
public void paint(Graphics g)
{
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}
// Myapp.html
<html>
<body>
<applet code="Myapp.class" width="300" height="300">
</applet>
</body>
</html>

Page 212
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 147: A java program on displaying image in applet
import java.awt.*;
import java.applet.*;
public class Myapp extends Applet
{
Image picture;
public void init( )
{
picture = getImage(getDocumentBase( ),"a.jpg");
}
public void paint(Graphics g)
{
g.drawImage(picture, 30,30, this);
}
}
OUTPUT:

Page 213
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63. Event Handling
 Changing the state of an object is known as event. Events are generated as result of user interaction
with the graphical user interface (GUI) components.
 For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page are the activities that causes an event to happen.
 The way in which an event is handled and controlled is called “eventhandling”.
 Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
 Events are supported by a number of packages, including java.util, java.awt, and java.awt.event.
63.1 Types of events:
1) Foreground Events:
 The events which require the direct interaction of user.
 They are generated as consequences of a person interacting with the graphical components in
Graphical User Interface.
 For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page etc.
2) Background Events:
 Some events can occur without human interaction such as operating system interrupts, hardware or
software failure, timer expires, an operation completion etc.

63.2 Java Event Delegation Model:


 In delegation event model has two key objects named as: a sourceand a listener.
 Sourceis an object that generates an event and sends it to one or more “Listeners”.
 Alistener is also an object that simply waits until it receives an event. Once an event is received, the
listener processes the event and then returns.
 The advantage of delegation event mode is that application logic that processes events is separated
from the user interface logic.
 In the delegation event model, listeners must register with a source in order to receive an event
notification.
 This provides an important benefit: the notifications are sent only to the registered listeners and
saves lots of time.

63.3 Event Sources:


 A source is an object that generates an event and it may generate more than one type of event.
 A source must register listeners in order to receive notifications about a specific type of event.
 Each type of event has its own registration method.
 Syntax: public void addTypeListener(TypeListener el)
 Here, ‘Type’ is the name of the event and ‘el’ referes to the event listener.
 Example 1: A method to register keyboard event listener is : addKetListener( ).
 Example 2: A method to register mouse motion listener is : addMouseMotionListener( ).
 In order to unregister a listener the following method is used:
public void removeTypeListener(TypeListener el)

Page 214
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.4 Event Listeners:
 A listener is an object that is notified when an event occurs.
 It has two major requirements: First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to receive and process
these notifications.
 The methods that receive and process events are defined in a set of interfaces, such as those found in
java.awt.event.
 For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.

63.5 Event Classes:


 The classes that represent events are called "Event Classes".
 At the root of the Java event class hierarchy is EventObject, which is in java.util. It is thesuperclass
for all events. Its one constructor is shown here:
EventObject(Object src)
 Here, src is the object that generates this event.
 EventObject class defines two methods: getSource( ) and toString( ).
 The getSource( ) method returns the source of the event. Its general form is shown here:
Object getSource( )
 The toString( ) returns the string equivalent of the event.
 The class AWTEvent, defined within the java.awt package, is a subclass of EventObject.
 It is the superclass of all AWT-based events used by the delegation event model.
 Its getID( ) method can be used to determine the type of the event. The signature of this method is
shown here:int getID( )
 The commonly Used Event Classes in java.awt.eventand description are as follows:

Page 215
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.6 The ActionEvent Class:
 An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected.
 The ActionEvent class defines four integer constants that can beused to identify any modifiers
associated with an action event as follows:ALT_MASK, CTRL_MASK,META_MASK, and
SHIFT_MASK.
 ActionEvent has these three constructors:
1) ActionEvent(Object src, int type, String cmd)
2) ActionEvent(Object src, int type, String cmd, int modifiers)
3) ActionEvent(Object src, int type, String cmd, long when, int modifiers)
 Here, src is a reference to the object that generated this event.
 The type of the event is specified by type, and its command string is cmd.
 The argument modifiers indicates which modifier keys (alt, ctrl, meta, and/or shift) were pressed when
the event was generated.
 The when parameter specifies when the event occurred.
 The ActionEvent has following methods:
1) getActionCommand( ):This method returns the name of the command for invoking the
ActionEvent object. The form is: String getActionCommand( )
2)getModifiers( ): This method returns a value that indicates which modifier keys(alt, ctrl, meta,
and/or shift) were pressed when the event was generated. Its formis: int getModifiers( )
3) getWhen( ): This method returns the time at which the event took place. This is called the event’s
timestamp. Itsform is:long getWhen( )

63.7 The AdjustmentEvent Class:


 An AdjustmentEvent is generated by a scroll bar.
 The AdjustmentEvent class defines five types of integer constants that can be used to identify them.
The constants and their meanings are shown here:

 The ‘AdjustmentEvent’ has one constructor:


AdjustmentEvent(Adjustable src, int id, int type, int val)
 Here, src is a reference to the object that generated this event. The id specifies the event.
 The type of the adjustment is specified by type, and its associated value is val.
 The AdjustmentEvent has following methods:
1) getAdjustable( ): This method returns the object that generated the event.
Its form is: Adjustable getAdjustable( ).
2) getAdjustmentType( ): This method returns the type of the adjustment event.
Its form is: int getAdjustmentType( ).
3) getValue( ): This method returns the amount of the adjustment can be obtained.
Its form is: int getValue( ).

Page 216
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.8 The ComponentEvent Class:
 A ComponentEvent is generated when the size, position, or visibility of a component is changed.
 The ComponentEvent class defines integer constants and their meanings are shown here:

 The ComponentEvent has one constructor:


ComponentEvent(Component src, int type)
 Here, src is a reference to the object that generated this event. The type of the event is specified by
type.
 ComponentEvent is the superclass either directly or indirectly of ContainerEvent,FocusEvent,
KeyEvent, MouseEvent, and WindowEvent.
 The ComponentEvent has following method:
1) getComponent( ): This method returns the component that generated the event.
Its form is: Component getComponent( ).

63.9 The ContainerEvent Class:


 A ContainerEvent is generated when a component is added to or removed from acontainer.
 There are two types of container events. The ContainerEvent class definesint constants that can be
used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.
 These indicate that a component has been added to or removed from the container.
 ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)
 Here, src is a reference to the container that generated this event. The type of the event is specified by
type, and the component that has been added to or removed from the container is comp.
 The ContainerEvent has following method:
1) getContainer( ):This method returns reference to the container.Its form is: Container getContainer(
).
2)getChild( ): This method returns a reference to the component that was added to or removed from
the container. Its form is: Component getChild( ).

63.10 The FocusEvent Class:


 A FocusEvent is generated when a component gains or loses input focus.
 These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
 FocusEvent is a subclass of ComponentEvent and has three constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
 Here, src is a reference to the component that generated this event. The type of the event is specified
by type.
 The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false.
 The other component involved in the focus change, called the opposite component, ispassed in other.
Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus.
Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus.
 The FocusEvent has following method:

Page 217
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
1) You can determine the other component by calling getOppositeComponent( ).
Itsform is: Component getOppositeComponent( ). The opposite component is returned.
2) isTemporary( ): This method indicates if this focus change is temporary.
Its form is: boolean isTemporary( ). The method returns true if the change is temporary. Otherwise, it
returns false.

63.11 The InputEvent Class:


 The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component
input events.
 Its subclasses are KeyEvent and MouseEvent.
 The keyboard events and mouse events defines several integer constantsare as follows:

 To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods. The forms of
these methods are shown here:
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )

63.12 The ItemEvent Class:


 An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item
is selected or deselected.
 There are two types of item events, which are identified by the following integerconstants:

 The ItemEvent defines one integer constant named as ITEM_STATE_CHANGED, that signifies a
change of state.
 ItemEvent has one constructor:
ItemEvent(ItemSelectable src, int type, Object entry, int state)
 Here, src is a reference to the component that generated this event. For example, this might be a list or
choice element.
 The type of the event is specified by type. The specific item that generated the item event is passed in
entry. The current state of that item is in state.
 The ‘ItemEvent’ has following methods:
1)getItem( ): This method can be used to obtain a reference to the item that changed.
Its form is: Object getItem( )
2)getItemSelectable( ): This method an be used to obtain a reference to the ItemSelectable object that
generated an event. Its form is:ItemSelectable getItemSelectable( ).
3)getStateChange( ): This method returns the state change (SELECTED orDESELECTED) for the
event. Its form is:int getStateChange( ).

Page 218
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.13 The KeyEvent Class:
 A KeyEvent is generated when keyboard input occurs. The KeyEvent is a subclass of InputEvent.
 There are three types of key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.
 The first two events are generated when any key is pressed or released. The last event occurs only
when a character is generated.
 Remember, not all keypresses result in characters. For example, pressing shift does not generate a
character.
 There are many other integer constants that are defined by KeyEvent. For example,VK_0 through
VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbersand letters. Here are
some others:

 The ‘KeyEvent’ has one constructor:


KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
 Here, src is a reference to the component that generated the event. The type of the event is specified by
type. The system time at which the key was pressed is passed in when.
 The modifiers argument indicates which modifiers were pressed when this key event occurred.
 The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
 The characterequivalent (if one exists) is passed in ch.
 If no valid character exists, then ch containsCHAR_UNDEFINED.
 For KEY_TYPED events, code will contain VK_UNDEFINED.
 The ‘KeyEvent’ has following methods:
1) getKeyChar( ): This method returns the character that was entered. Its form is: char getKeyChar( ).
2) getKeyCode( ): This method returns the key code. Its form is: int getKeyCode( ).
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a
KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

63.14 The MouseEvent Class:


 MouseEvent is a subclass of InputEvent.
 There are eight types of mouse events. The MouseEvent class defines the following integer constants
that can be used to identify them:

 The ‘MouseEvent’ has one constructor:


MouseEvent(Component src, int type, long when, int modifiers,int x, int y, int clicks, boolean triggersPopup)
 Here, src is a reference to the component that generated the event. The type of the event is specified by
type. The system time at which the mouse event occurred is passed in when. The modifiers argument
indicates which modifiers were pressed when a mouse event occurred.

Page 219
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
 The ‘MouseEvent’ has following methods:
1) getX( ): This method return the X coordinates of the mouse when the event occurred. Its form is: int
getX( ).
2)getY( ): This method return the Y coordinates of the mouse when the event occurred. Its form is: int
getY( ).
3)getPoint( ): This method returns X and Y coordinates of the mouse. Its form is: Point getPoint( ).
4)translatePoint( ): This method changes the location of the event. Its form is: void translatePoint(int
x, int y).
5)getClickCount( ): This method obtains the number of mouse clicks for this event. Its form is: int
getClickCount( ).
6)isPopupTrigger( ): This method tests if this event causes a pop-up menu to appear on this
platform.Its form is: boolean isPopupTrigger( ).
7)getButton( ): This method returns a value that represents the button that caused the event.For most
cases, the return value will be one of these constants defined by MouseEvent:

The NOBUTTON value indicates that no button was pressed or released.

63.15 The MouseWheelEvent Class:


 The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of
 MouseEvent.
 If a mouse has a wheel, it is typically located between the left and right buttons. Mouse wheels are
used for scrolling.
 MouseWheelEvent defines these two integer constants:

 The MouseWheelEventhas one constructor:


MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean
triggersPopup, int scrollHow, int amount, int count)
 Here, src is a reference to the object that generated the event. The type of the event is specified by
type. The system time at which the mouse event occurred is passed in when.
 The modifiers argument indicates which modifiers were pressed when the event occurred. The
coordinates of the mouse are passed in x and y.
 The number of clicks is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up
menu to appear on this platform.
 The scrollHow value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_ SCROLL.
 The number of units to scroll is passed in amount. The count parameter indicates the number of
rotational units that the wheel moved.
 The MouseWheelEventhas following methods:
1) getWheelRotation( ): This method used to obtain the number of rotational units.If the value is
positive, the wheel moved counterclockwise. If the value is negative, the wheel moved clockwise.
2)getScrollType( ): This method used to obtain the type of scroll. Its form is: int getScrollType( ).It
returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.

Page 220
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
63.16 The TextEvent Class:
 This class describe text events. These are generated by text fields and text areaswhen characters are
entered by a user or program.
 TextEvent defines the integer constant TEXT_VALUE_CHANGED.
 The TextEventhas one constructor:
TextEvent(Object src, int type)
 Here, src is a reference to the object that generated this event. The type of the event is specified by
type.

63.17 The WindowEvent Class:


 WindowEvent is a subclass of ComponentEvent. There are ten types of window events. The
WindowEvent class defines integer constants that can be used to identify them.
 The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
 The WindowEventhas several constructor:
WindowEvent(Window src, int type)
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
 Here, src is a reference to the object that generated this event. The type of the event is type. other
specifies the opposite window when a focus or activation event occurs.
 The fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs.
 The WindowEvent has following methods:
1)getWindow( ): It returns the Window object that generated the event.
Its form is: Window getWindow( ).

Page 221
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
64. Sources of Event
 The below table lists some of the user interface components that can generate the events.

65. Event Listener Interfaces


 The delegation event model has two parts: sources and listeners.
 The listeners are created by implementing one or more of the interfaces definedby the java.awt.event
package.
 When an event occurs, the event source invokes the appropriate method defined by the listener and
provides an event object as its argument.

65.1 The ActionListener Interface:


 This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its
general form is:
void actionPerformed(ActionEvent ae)

Page 222
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
65.2 The AdjustmentListener Interface:
 This interface defines the adjustmentValueChanged( ) method that is invoked when anadjustment
event occurs. Its general form is:
void adjustmentValueChanged(AdjustmentEvent ae)

65.3 The ComponentListener Interface:


 This interface defines four methods that are invoked when a component is resized, moved, shown, or
hidden.
 The general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

65.4 The ContainerListener Interface:


 This interface contains two methods. When a component is added to a container, componentAdded( )
is invoked. When a component is removed from a container,componentRemoved( ) is invoked.
 The general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)

65.5 The FocusListener Interface:


 This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is
invoked. When a component loses keyboard focus, focusLost( )is called.
 The general forms are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)

65.6 The ItemListener Interface:


 This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes.
 Its general form is shown here:
void itemStateChanged(ItemEvent ie)

65.7 The KeyListener Interface:


 This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a
character has been entered.
 For example, if a user presses and releases the a key, three events are generated in sequence: key
pressed, typed, and released.
 If a user presses and releases the home key, two key events are generated in sequence: key pressed and
released.
 The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

Page 223
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
65.8 The The MouseListener Interface:
 This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked.
 When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the
mouse is pressed and released, respectively.
 The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

65.9 The MouseMotionListener Interface:


 This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouseis moved.
 Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

65.10 The MouseWheelListener Interface:


 This interface defines the mouseWheelMoved( ) method that is invoked when the mousewheel is
moved.
 Its general form is shown here:
void mouseWheelMoved(MouseWheelEvent mwe)

65.11 The TextListener Interface:


 This interface defines the textValueChanged( ) method that is invoked when a changeoccurs in a text
area or text field.
 Its general form is shown here:
void textValueChanged(TextEvent te)

65.12 The WindowFocusListener Interface:


 This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called
when a window gains or loses input focus.
 Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)

65.13 The WindowListener Interface:


 This interface defines seven methods.
 The windowActivated( ) and windowDeactivated( ) methods are invoked when a window is
activated or deactivated, respectively.
 If a window is iconified, the windowIconified( ) method is called.
 When a window is deiconified, the windowDeiconified( ) method is called.
 When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called,
respectively.
 The windowClosing( ) method is called when a window is being closed.
 The general forms of these methods are:
Page 224
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

66. Java Event Listners and methods


Corresponding
Source of Interface
S.No Event Name Methods of Interface
Event (or)
Event Listner
Action/Button
1 Button ActionListener void actionPerformed(ActionEvent ae)
Event
Checkbox
Checkbox
2 Item Event Group ItemListener void itemStateChanged(ItemEvent ie)
Choice
List
void
Adjustment
3 Scrollbar AdjsutmentListener adjustmentValueChanged(AdjustmentEvent
Event
ae)
void mouseDraged(MouseEvent me)
4 Mouse Event Mouse MouseMotionListener
void mouseMoved(MouseEvent me)
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
5 Mouse Event Mouse MouseListener void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Mouse Wheel void mouseWheelMoved(MouseWheelEvent
6 Mouse MouseWheelListener
Event me)
7 Text Event TextFiled Action Listener void actionPerformed(actionEvent ae)
8 Text Event Text Area Action Listener void actionPerformed(actionEvent ae)

67. Handling Mouse Events:


 To handle mouse events, you must implement the MouseListener and the MouseMotionListener
interfaces.
 The following applet demonstrates the process. It displays the current coordinates of the mouse in the
applet’s status window.
 Each time a button is pressed, the word "Down" is displayed at the location of the mouse pointer.
 Each time the button is released, the word "Up" is shown.
 If a button is clicked, the message "Mouse clicked" is displayed in the upper-left corner of the applet
display area.
 As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the
applet display area.
 When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.

Page 225
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 Notice that the two variables, mouseX and mouseY, store the location of the mouse when a mouse
pressed, released, or dragged event occurs.
 These coordinates are then used by paint( ) to display output at the point of these occurrences.

Program 148: A java program on Handling Mouse Events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Appletimplements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init( )
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint( );
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint( );
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint( );
}

Page 226
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "Down";
repaint( );
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "Up";
repaint( );
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint( );
}
// Handle mouse moved.When dragging the mouse, a * is shown, which tracks with
the mouse pointer as it is dragged.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX( ) + ", " + me.getY( ));
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
OUTPUT SCREENS:

Page 227
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
68. Handling Keyboard Events
 To handle keyboard events by implementing the KeyListener interface.
 When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed(
) event handler.
 When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is
executed.
 If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked.

Program 149: A java program on Handling Keyboard Events


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Appletimplements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init( )
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{

Page 228
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar( );
repaint( );
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
OUTPUT:

69. Adapter Classes


 An adapter class provides an empty implementation of all methods in an event listener interface.
 Adapter classes are useful when you want to process only some of the events that are handled by a
particular event listener interface.
 The following table lists the commonly used adapter classes in java.awt.event and notes the interface
that each implements.

Page 229
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 150: A java program on Adapter Classes
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init( )
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
adapterDemo.showStatus("Mouse dragged");
}
}

Page 230
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
70. Inner classes
 An inner class is a class defined within another class or within another expression.

Program 151: A java program on Inner Classes

import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet
{
public void init( )
{
addMouseListener(new MyMouseAdapter( ));
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}
70.1 Anonymous Inner Class:
 An anonymous class is a class whose name is not written and for which only one objecy is created.

Program 152: A java program on Anonymous Inner Classes


import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet
{
public void init( )
{
addMouseListener(new MouseAdapter( )
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
});
}
}
Page 231
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

Page 232
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
UNIT - V

71. Introduction to AWT:


 The Abstract Window Toolkit (AWT) was Java’s first GUI framework, and it has been part of Java
since version 1.0.
 It contains numerous classes and methods that allow you to create windows and simple controls.

71.1 AWT Classes:


 The AWT classes are contained in the java.awt package are as follows:
Classes Description
AWTEvent Encapsulates AWT events.
The border layout manager. Border layouts use five components:
BorderLayout
North, South, East, West, and Center.
Button Creates a push button control.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
Color Manages colors.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Cursor Encapsulates a bitmapped cursor.
Font Encapsulates a type font.
Creates a standard window that has a title bar, resize corners, and a
Frame
menu bar.
Encapsulates the graphics context. This context is used by the various
Graphics
output methods to display output in a window.
The grid layout manager. Grid layout displays components in a
GridLayout
twodimensionalgrid.
Image Encapsulates graphical images.
Label Creates a label that displays a string.
Creates a list from which the user can choose. Similar to the standard
List
Windows list box.
Menu Creates a pull-down menu.
MenuBar Creates a menu bar.
MenuComponent An abstract class implemented by various menu classes.
MenuItem Creates a menu item.
Panel The simplest concrete subclass of Container.
Point Encapsulates a Cartesian coordinate pair, stored in x and y.
Scrollbar Creates a scroll bar control.
A container that provides horizontal and/or vertical scroll bars for
ScrollPane
another component.
TextArea Creates a multiline edit control.
TextComponent A superclass for TextArea and TextField.
TextField Creates a single-line edit control.
Toolkit Abstract class implemented by the AWT.
Window Creates a window with no frame, no menu bar, and no title.

Page 233
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
72. Handling Buttons:
 When a button ispressed an event is generated, this event is sent to appropriate listener that is
registered with the button.
 The listener then implements ActionListenerinterface, defines the actionPerformed( ) method.
 An ActionEvent object is passed as parameter to the method. It contains reference to button that
generated the event and reference to the action command string.
 ActionCommand string is used to label the button by default.
 getActionCommand( ) method is used to get the label of the button that is pressed.

Program 153: A java program that handling the buttons


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Button1 extends Applet implements ActionListener
{
String msg=" ";
public void init( )
{
Button one = new Button("one");
Button two= new Button("Two");
Button three = new Button("Three");
add(one);
add(two);
add(three);
one.addActionListener(this);// link the Java button with the ActionListener
two.addActionListener(this);
three.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals("one"))
msg= "Button one is pressed";
elseif(str.equals("Two"))
msg= "Button Two is pressed";
elseif(str.equals("Three"))
msg = "Button Three is pressed";
}
public void paint(Graphics g)
{
g.drawString(msg,10,20);
}
}

//Button1.html
<html>
<applet code ="Button1.class" width = 500 height = 200>
</applet>
Page 234
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

74. Handling Checkboxes:


 Each time a checkbox is selected or deselected an event is generated and send to the listener that is
registered with it.
 The listener implements the ItemListener interface.
 ItemListener defines the method itemStateChanged( ).
 An ItemEvent object is passed as parameter to this method.

Program 154: A java program that handling the checkboxes


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CheckBoxDemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
public void init( )
{
c1 = new Checkbox("Bold",null,true);
c2 = new Checkbox("Italic",false);
c3 = new Checkbox("Undefined");
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
msg="Bold:" +c1.getState( );
g.drawString(msg,150,100);
msg="Italic:" +c2.getState( );

Page 235
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
g.drawString(msg,150,140);
msg="Undefined:" +c3.getState( );
g.drawString(msg,150,180);
}
}
//CheckBoxDemo.html
<html>
<applet code ="CheckBoxDemo.class" width = 500 height = 200>
</applet>

OUTPUT:

75. Handling Radio Buttons/Checkbox Groups:


 Each time a radio buttion is selected an event is generated and sent to the registered listener.
 The listener implements ItemListener interface which defines the method itemStateChanged( ).

Program 155: A java program that handling the Radio Buttons/Checkbox Groups
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RadioDemo extends Applet implements ItemListener
{
String msg=" ";
Checkbox c1,c2,c3;
CheckboxGroup cbg;
public void init( )
{
cbg = new CheckboxGroup( );
c1 = new Checkbox("Bold",cbg,true);
c2 = new Checkbox("Italic",cbg,false);
c3 = new Checkbox("Undefined",cbg,false);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
Page 236
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox( ).getLabel( );
g.drawString(msg, 6, 100);
}
}
//RadioDemo.html
<html>
<applet code ="RadioDemo.class" width = 500 height = 200>
</applet>

OUTPUT:

76. Handling TextField:


 Text fields perform their own editing functions and generally will not respond to the individual key
events that occur within a text filed.
 But if you press ENTER they may respond i.e an ActionEvent can be generated.

Program 156: A java program that handling the Text Filed


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextFieldDemo extends Applet implements ActionListener
{
TextField tf1, tf2;
public void init( )
{
Label name = new Label("Name",Label.RIGHT);
Page 237
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Label pwd = new Label("Password",Label.RIGHT);
tf1 = new TextField(15);
tf2 = new TextField(8);
tf2.setEchoChar('*');
add(name);
add(tf1);
add(pwd);
add(tf2);
// register to receive action events
tf1.addActionListener(this);
tf2.addActionListener(this);
}
//User pressed ENTER button.
public void actionPerformed(ActionEvent ae)
{
repaint( );
}
public void paint(Graphics g)
{
g.drawString("Name: "+tf1.getText( ),6,60);
g.drawString("Selected text is: "+tf1.getSelectedText( ),6,80);
g.drawString("Password is: "+tf2.getText( ),6,100);
}
}
// TextFieldDemo.html
<html>
<applet code ="TextFieldDemo.class" width = 500 height = 200>
</applet>

OUTPUT:

Page 238
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
77. Handling TextArea:
 TextArea is called as simple multi line editor.
 Constructors of TextArea:
1) TextArea( ) throws HeadlessException
2) TextArea(int numlines, int numchars) throws HeadlessException
3) TextArea(String str ) throws HeadlessException
4) TextArea(String str, int numlines, int numchars ) throws HeadlessException
5) TextArea(String str, int numlines, int numchars, int sBars ) throws HeadlessException
 Note: ‘numlines’ specifies height of the text area, numchars specifies width of the text area, sBars
specify scrollbars.
 It contains constants such as: SCROLLBAR_BOTH, SCROLLBAR_NONE,
SCROLLBAR_HORIZONTAL_ONLY, SCROLLBAR_VERTICAL_ONLY.
 TextArea is a subclass of TextComponent.
 The method supported are: getText( ), setText( ), getSelectedText( ), select( ), isEditable( ) and
setEditable( ).
 Other methods that are supported by TextArea are:
1) append( ):Appends the specified string to the end of the current text.
Syntax: void append(String str)
2) insert( ): Inserts the string passed in ‘str’ at specified index.
Syntax:void insert(String str, int index)
3) replaceRange( ): Used to replace the text.
Syntax: void replaceRange(String str, int startIndex, int endIndex)

Program 157: A java program on Text Area


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{
public void init( )
{
String val = "Hello java programming\n" + "Welcome to CSE department\n";
TextArea ta = new TextArea(val, 10,30);
add(ta);
}
}

// TextAreaDemo.html
<html>
<applet code ="TextAreaDemo.class" width = 500 height = 200>
</applet>

Page 239
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

78. Handling Choice List:


 Choice class is used to create a pop-up list of items from which user can select one item.
 It has only the default constructor:
Choice obj = new Choice( );
 The default constructor creates an empty list.
 To add a selection to the list add( )method is used and follow the below syntax.
void add(String str)
 Here, ‘str’ specifies name of the item being added.
 Methods of Choice Controls:
1) getSelectedItem( ): It used to determine which item is selected.
Syntax:String getSelectedItem( )
2) getSelectedIndex( ): It returns the index of the item.
Syntax:int getSelectedIndex( )
3) getItemCount( ):It used to get count of nuber of items present in the list.
Syntax: int getItemCount( )
4) select( ):It used to set the currently selected item with either a zero based integer index or a string
that will match name in the list.
Syntax: void select(int index) and void select(String name)
5)getItem( ): It used to get the item at specified index.
Syntax: String getItem(int index)
 Each time an item is selected an item event is generated and sent to the listener.
 The listener implements the ItemListener interface, which defines the itemStateChanged( ) method.

Program 158: A java program on Choice List


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ChoiceDemo extends Applet implements ItemListener
{
Choice veh, comp;
String msg=" ";
public void init( )
{
veh = new Choice( );
comp = new Choice( );
//add items to ‘veh’ list
Page 240
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
veh.add("car");
veh.add("Bike");
//add items to ‘comp’ list
comp.add("Hero Motors");
comp.add("Honda");
comp.add("Maruthi");
comp.add("Ford");
// add choice lists to window
add(veh);
add(comp);
// register to receive item events
veh.addItemListener(this);
comp.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
msg = "Selected Vehicle";
msg+=veh.getSelectedItem( );
g.drawString(msg,100,150);
msg="Selected Company";
msg+=comp.getSelectedItem( );
g.drawString(msg,100,180);
}
}
//ChoiceDemo.html
<html>
<applet code ="ChoiceDemo.class" width = 500 height = 200>
</applet>

OUTPUT 1:

Page 241
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT 2:

79. Handling Lists:


 List class provides a multiple choice, scrolling selection list.
 List can be created to allow multiple selections.
 List provides the following constructors:
1) List( ) throws HeadlessException
2) List(int numRows) throws HeadlessException
3) List(int numRows, boolean multipleSelect) throws HeadlessException
 To add an item to the list, use add( ) method:
1) void add(String name)
2) void add(String name, int index)
 For lists that allow single selection, we can determine which item is currently selected by calling
either String getSelectedItem( )or int getSelectedIndex( ).
 For lists that support multiple selections either getSelectedItem( ) or getSelectedIndex( )can be used
in the following form:
1) String[ ] getSelectedItem( )
2) int[ ] getSelectedIndex( )
 int getItemCount( ) is used to get the count of the items selected.
 List Methods:
1) void select(int index): It used to set the currently selected item with a zero based index.
2) String getItem(int index): It used to obtain the name associated with the item at the specified
index.
 In order to process list events ActionListener interface is to be implemented.
 Each time a list item is double clicked an ActionEvent is generated.
 getActionCommand( ) method can be used to get the newly selected item.
 Each time an item is selected or deselected an ItemEvent object is generated and getStateChange( )
method can be used to determine whether a selection or deselection triggered the event.
 getItemSelectable( ) returns a reference to the object that generated the event.

Page 242
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 159: A java program on Handling Lists
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ListDemo extends Applet implements ActionListener
{
List veh, comp;
String msg=" ";
public void init( )
{
veh = new List(4,true);
comp = new List(4, false);
veh.add("car");
veh.add("Bus");
veh.add("Bike");
veh.add("Lorry");
comp.add("Hero Motors");
comp.add("Honda");
comp.add("Maruthi");
comp.add("Ford");
comp.add("AshokLeyland");
comp.select(1);
add(veh);
add(comp);
veh.addActionListener(this);
comp.addActionListener(this);
}
public void actionPerformed(ActionEvent ie)
{
repaint( );
}
public void paint(Graphics g)
{
int ind[ ];
msg = "Selected Vehicle";
ind=veh.getSelectedIndexes( );
for(int i=0;i<ind.length;i++)
msg+=veh.getItem(ind[i])+ " ";
g.drawString(msg,100,150);
msg="Selected Company";
msg+=comp.getSelectedItem( );
g.drawString(msg,100,180);
}
}

Page 243
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

80. Handling Scroll Bars:


 To process scroll bar events, implement the AdjustmentListener interface.
 Each time a user interacts with a scroll bar, an AdjustmentEvent object is generated.
 The getAdjustmentType( ) method can be used to determine the type of the adjustment.
 The types of adjustment events are as follows:

 The setPreferredSize( ) to set the size of the scrollbars.

Program 160: A java program on Handling Scroll Bars


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SBDemo" width=300 height=200>
</applet>
*/
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener
{
String msg = "";
Scrollbar vertSB, horzSB;
public void init( )
{
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height);
vertSB.setPreferredSize(new Dimension(20, 100));
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
horzSB.setPreferredSize(new Dimension(100, 20));
add(vertSB);
add(horzSB);
// register to receive adjustment events
Page 244
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint( );
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me)
{
int x = me.getX( );
int y = me.getY( );
vertSB.setValue(y);
horzSB.setValue(x);
repaint( );
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me)
{
}
// Display current value of scroll bars.
public void paint(Graphics g)
{
msg = "Vertical: " + vertSB.getValue( );
msg += ", Horizontal: " + horzSB.getValue( );
g.drawString(msg, 6, 160);
// show current mouse drag position
g.drawString("*", horzSB.getValue( ),
vertSB.getValue( ));
}
}
OUTPUT:
>javac SBDemo.java
>appletviewer SBDemo.java

Page 245
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
81. Layout Managers:
 A layout manager is an instance of any class that implements the LayoutManager interface.
 The layout manager is set by the setLayout( ) method. Its form is:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager.
 If no call to setLayout( ) is made, then the default layout manager is used by JVM.

81.1 Handling Flow Layout:


 FlowLayout is the default layout manager.
 FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.
 The direction of the layout is governed by left to right and top to bottom.
 When a line is filled, layout advances to the next line.
 A small space is left between each component, by default.
 The constructors for FlowLayout:
1) FlowLayout( ):It creates the default layout, which centers components and leaves five pixels of
space between each component.
2) FlowLayout(int how):It specify how each line is aligned. Valid values for how are as follows:
a) FlowLayout.LEFT
b) FlowLayout.CENTER
c) FlowLayout.RIGHT
d) FlowLayout.LEADING
e) FlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge alignment, respectively.
3) FlowLayout(int how, int horz, int vert): Itspecify the horizontal and vertical space left between
components in horz and vert, respectively.

Program 161: A java program on Handling Flow Layout


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=240 height=200>
</applet>
*/
public class FlowLayoutDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox windows, android, solaris, mac;
public void init( )
{
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
windows = new Checkbox("Windows", null, true);
android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(windows);
add(android);
Page 246
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
add(solaris);
add(mac);
// register to receive item events
windows.addItemListener(this);
android.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie)
{
repaint( );
}
// Display current state of the check boxes.
public void paint(Graphics g)
{
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows: " + windows.getState( );
g.drawString(msg, 6, 100);
msg = " Android: " + android.getState( );
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState( );
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState( );
g.drawString(msg, 6, 160);
}
}

OUTPUT:
>javac FlowLayoutDemo.java
>appletviewer FlowLayoutDemo.java

Page 247
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
81.2 Handling Border Layout:
 The BorderLayout class implements a common layout style for top-level windows.
 It 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.
 The constructors defined by BorderLayout:
a) BorderLayout( ): The first form creates a default border layout.
b) BorderLayout(int horz, int vert): The second allows you to specify the horizontal and vertical
space left between components in horz and vert, respectively.
 BorderLayout defines the following constants that specify the regions:
a) BorderLayout.CENTER
b) BorderLayout.EAST
c) BorderLayout.NORTH
d) BorderLayout.SOUTH
e) BorderLayout.WEST
 The add( ) method is used to adding the components. Its form is:
void add(Component compRef, Object region)
 Here, compRef is a reference to the component to be added, and region specifies where the component
will be added.

Program 162: A java program on Handling Border Layout


import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet
{
public void init( )
{
setLayout(new BorderLayout( ));
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
Page 248
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

81.3 Handling Grid Layout:


 GridLayout lays out components in a two-dimensional grid which defines the number of rows and
columns.
 The constructors supported by GridLayout are shown here:
a) GridLayout( ): It creates a single-column grid layout.
b) GridLayout(int numRows, int numColumns): It creates a grid layout with the specified number
of rows and columns.
c) GridLayout(int numRows, int numColumns, int horz, int vert): It allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.

Program 163: A java program on Handling Grid Layout


import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet
{
static final int n = 4;
public void init( ) {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
Page 249
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:

Page 250
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
82 Window Fundamentals
82.1 Component:
 At the top of the AWT hierarchy is the Component class.
 Component is an abstract class that encapsulates all of the attributes of a visual component.
 Except for menus, all user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component. For example: mouse and keyboard events, positioning and sizing
the window and repainting.
 A Component object is responsible for remembering the current foreground and background colors
and the currently selected text font.

82.2 Container:
 The Container class is a subclass of Component.
 It has additional methods that allow other Component objects to be nested within it.
 A container is responsible for laying out (that is, positioning) any components that it contains.

82.3 Panel:
 The Panel class is a concrete subclass of Container and it is the superclass for Applet.
 A Panel is a window that does not contain a title bar, menu bar, or border. So for this reason see these
items when an applet is run inside a browser.
 When you run an applet using an applet viewer, the applet viewer provides the title and border.
 Other components can be added to a Panel object by its add( ) method (inherited from Container).
 Once these components have been added, you can position and resize them manually using the
setLocation( ), setSize( ), setPreferredSize( ), or setBounds( ) methodsdefined by Component.

82.4 Window:
 The Window class creates a top-level window. A top-level window is not contained within any other
object; it sits directly on the desktop.
 Generally, you cannot create Window objects directly. Instead, wecan use a subclass of Window
called Frame.

82.5 Frame:
 Frame is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.

Page 251
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
83. Working with Frame Windows
 A frame creates a standard-style window and a Frame’s has two constructors:
1) Frame( ) throws HeadlessException
2) Frame(String title) throws HeadlessException
 The first form creates a standard window that does not contain a title and the second form creates a
window with the title specified by title.
 A HeadlessException is thrown if an attempt is made to create a Frame instancein an environment
that does not support user interaction.
 Frame has several methods are as follows:
1) setSize( ): It is used to set the dimensions of the window. Its signature is:
a) void setSize(int newWidth, int newHeight)
b) void setSize(Dimension newSize)
 The new size of the window is specified by newWidth and newHeight, or by the width and
height fields of the Dimension object passed in newSize.
 The dimensions are specified in terms of pixels.

2) getSize( ):This method returns the current size of the window contained within the width and height
fields of a Dimension object. Its form is: Dimension getSize( ).

3) setVisible( ):

 After a frame window has been created, it will not be visible until you call setVisible( ).
 Its form is: void setVisible(boolean visibleFlag).
 The component is visible if the argument to this method is true. Otherwise, it is hidden.

4) setTitle( ):

 You can change the title in a frame window using setTitle( ).


 Its form is: void setTitle(String newTitle).
 Here, newTitle is the new title for the window.

5) windowClosing( ):

 To intercept a window-close event, you mustimplement the windowClosing( ) method of the


WindowListener interface.
 InsidewindowClosing( ), you must remove the window from the screen.

6) The drawstring( ) method of Graphics class can be used to display the text in Frame.
7) Components can be added to the Frame by using add( ) method.
8) A components can be displayed with required font by using setFont( ) method.
Syntax: Font f = new Font(“name”, style, size);
setFont(f);
9) A component can be placed in a particular location in the Frame by using setBounds( ) method.
10) To set color we can use setColor( ) method.
Example 1: setColor(Color.yellow);
Example 2: Color c = new Color(r,g,b);
setColor(c);
11)To display images in the Frame we can use drawIamge( ) method of Graphics class.

Page 252
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
83.1. Creating a Frame:
 There are two ways we can create a Frame.
a) Create an object to Frame class.
Syntax: Frame obj = new Frame( );
b) Create a class that exteds Frame class
Example:
class MyFrame extends Frame
//Now create an object to the user defined class MyFrame
Obj = new MyFrame( );

83.2 Creating a Frame by creating object to Frame class:


import java.awt.*;
class MyFrame
{
public static void main(String args[ ])
{
//Create Frame object
Frame obj = new Frame( );
//Setting the size of Frame
obj.setSize(400,300);
//Display the Frame
obj.setVisible(true);
}
}

83.3 Creating a Frame by extending Frame class


import java.awt.*;
class MyFrame extends Frame
{
public static void main(String args[ ])
{
//Create Frame object
MyFrame obj = new MyFrame( );
obj.setSize(400,300);
obj.setTitle(“First Frame”);
obj.setVisible(true);
}
}

83.4 Closing a Frame:


 Step 1: Attach WindowListener to the Frame.
 Step 2: Implement an appropriate method of the listener interface.
 Step 3: This method is called and executed when the event is generated.
Example Program:
import java.awt.*;
import java.event.*;
class MyFrame extends Frame
{

Page 253
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
public static void main(String args[ ])
{
MyFrame f = new MyFrame( );
f.setSize(400,300);
f.setTitle(“First Frame”);
f.setVisible(true);
f.addWindowListener(new MyClass( ) );
}
}
class MyClass implements WindowListener
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

Program 164: A java Button Example with ActionListener Event Handling by using Frames
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener
{
public ButtonDemo( )
{
FlowLayout fl = new FlowLayout( );// set the layout to frame
setLayout(fl);
Button rb = new Button("Red");
Button gb = new Button("Green");
Button bb = new Button("Blue");
rb.addActionListener(this);// link the Java button with the ActionListener
gb.addActionListener(this);
bb.addActionListener(this);
add(rb);// add each Java button to the frame
add(gb);
add(bb);
}
// override the only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand( );// to know which Java button user clicked
System.out.println("You clicked " + str + " button");
if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);

Page 254
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}
public static void main(String args[])
{
ButtonDemo obj = new ButtonDemo( );
obj.setTitle("Button in Action");
obj.setSize(300, 350);
obj.setVisible(true);
}
}
OUTPUT:

Program 165: A java CheckBox Example with ItemListener Event Handling by using Frames
import java.awt.*;
import java.awt.event.*;
public class CheckTest extends Frame implements ItemListener
{
Checkbox nameBox, boldBox, italicBox, exitBox;
Label lab;
public CheckTest( )
{
nameBox = new Checkbox("Monospaced");
boldBox = new Checkbox("Bold", true);
italicBox = new Checkbox("Italic");
lab = new Label("Way 2 Java");

exitBox = new Checkbox( );


exitBox.setLabel("Close");
exitBox.setState(false);
exitBox.setBackground(Color.cyan);

Page 255
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
exitBox.setForeground(Color.blue);
exitBox.setFont(new Font("Serif", Font.BOLD, 12));

nameBox.addItemListener(this);
boldBox.addItemListener(this);
italicBox.addItemListener(this);
exitBox.addItemListener(this);

add(nameBox, "North");
add(boldBox, "West");
add(italicBox, "East");
add(exitBox, "South");
add(lab, "Center");

System.out.println("exit box label: " + exitBox.getLabel( ));


System.out.println("exit box state: " + exitBox.getState( ));

setTitle("Check Boxes in Action");


setSize(300, 300);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
String fontName = "";
int b = 0, i = 0;

if(nameBox.getState( ) == true)
fontName = "Monospaced";
else
fontName = "Dialog";

if(boldBox.getState( ) == true)
b = Font.BOLD;
else
b = Font.PLAIN;

if(italicBox.getState( ) == true)
i = Font.ITALIC;
else
i = Font.PLAIN;

if(exitBox.getState( ) == true)
System.exit(0);

Font f1 = new Font(fontName, b+i, 20);


lab.setFont(f1);
}
public static void main(String args[])

Page 256
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
{
new CheckTest( );
}
}
OUTPUT:

84. Creating MenuBars, MenuItems and Menus:


 A menu bar is associated at top level window and it displays a list of menu choices.
 Each choice is associated with a drop-down menu.
 This concept is implemented in the AWT by the MenuBar, Menu, and MenuItem classes.
 In general, a MenuBar contains one or more Menu objects.
 Each Menu object contains a list of MenuItem objects.
 Each MenuItem object can be selected by the user.
 Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can becreated.
 It is also possible to include checkable menu items. These are menu options oftype
CheckboxMenuItem and will have a check mark next to them when they are selected.
 MenuBar: MenuBar holds the menus. MenuBar is added to frame with setMenuBar( ) method. By
default, the menu bar is added to the north (top) of the frame. MenuBar cannot be added to other sides
like south and west etc.
 Menu: Menu holds the menu items. Menu is added to frame with add( ) method.
 MenuItem: MenuItem displays the actual option user can select. Menu items are added to menu with
method addMenuItem( ). A dull-colored line can be added in between menu items with
addSeparator( ) method.
 CheckboxMenuItem: It differs from MenuItem in that it appears along with a checkbox. The
selection can be done with checkbox selected.

Program 166: A java menus with Event handling by using Frames


import java.awt.*;
import java.awt.event.*;
public class SimpleMenuExample extends Frame implements ActionListener
{
Menu states, cities;
public SimpleMenuExample( )
{
MenuBar mb = new MenuBar( ); // begin with creating menu bar
setMenuBar(mb); // add menu bar to frame
Page 257
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
states = new Menu("Indian States");// create menus
cities = new Menu("Indian Cities");
mb.add(states); // add menus to menu bar
mb.add(cities);
states.addActionListener(this); // link with ActionListener for event handling
cities.addActionListener(this);
states.add(new MenuItem("Himachal Pradesh"));
states.add(new MenuItem("Rajasthan"));
states.add(new MenuItem("West Bengal"));
states.addSeparator( ); // separates from north Indian states from south Indian
states.add(new MenuItem("Andhra Pradesh"));
states.add(new MenuItem("Tamilnadu"));
states.add(new MenuItem("Karnataka"));
cities.add(new MenuItem("Delhi"));
cities.add(new MenuItem("Jaipur"));
cities.add(new MenuItem("Kolkata"));
cities.addSeparator( ); // separates north Indian cities from south Indian
cities.add(new MenuItem("Hyderabad"));
cities.add(new MenuItem("Chennai"));
cities.add(new MenuItem("Bengaluru"));

}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand( );// know the menu item selected by the user
System.out.println("You selected " + str);
}
public static void main(String args[])
{
new SimpleMenuExample( );
setTitle("Simple Menu Program"); // frame creation methods
setSize(300, 300);
setVisible(true);
}
}
OUTPUT:

Page 258
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
INTRODUCTION TO SWINGS:

85. The origin of Swing


 The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited
graphical interface.
 The look and feel of each AWT component is defined by the platform, not by Java andit was fixed
could not be changed easily.
 Swing eliminates a number of the limitations inherent in the AWT.
 Swing components are lightweight.
 Swing was included as part of the Java Foundation Classes (JFC). Swing was initially available for
use with Java 1.1 as a separate library.
 Swing also uses the same event handling mechanism as the AWT. Therefore, a basic understanding of
the AWT and of event handling is required to use Swing.
 Swings are used to create window-based applications.
 Unlike AWT, Java Swing provides two features named as: platform-independent and
lightweightcomponents.
 The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, etc.
 Swing components are lightweight. This means that they are written entirely in Java and do not map
directly to platform.
 Swing supports a pluggable look and feel (PLAF). Because each Swing component is interpret by
Java, the look and feel of a component is under the control of Swing.

86. The MVC Architecture


 The MVC pattern is a model of how a user interface can be structured. Therefore it defines the
following 3 elements:d
1) Model that represents the data for the application.
2) View is the visual representation of that data.
3) Controller that takes user input on the view and translates that to changes in the model.
 The Model corresponds to the state information associated with the component. For example, in the
case of a check box, the model contains a field that indicates if the box is checked
or unchecked.
 The View determines how the component is displayed on the screen.
 The Controller determines how the component reacts to the user.For example, when the user clicks a
check box, the controller reacts by changing the model to reflect the user’s choice (checked or
unchecked).
 This then results in the view is being updated.
 By separating a component into a model, a view, and a controller, the specific implementation of each
can be changed without affecting the other two.
 In Swings, it uses a modified version MVC architecture that combines the view and the controller
into a single logical entity called the UIdelegate.
 This approach is called the Model-Delegate architecture or the Separable Model architecture.
 To support the Model-Delegate architecture, most Swing components contain twoobjects.
 The first object represents the model. The second object represents the UIdelegate. Models are
defined by interfaces. For example, the model for a button is defined by the ButtonModel interface.

Page 259
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
 UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is
ButtonUI.

87. Difference between AWT and Swing


SNo Java AWT Java Swing
Java swing components are platform-
1 AWT components are platform-dependent.
independent.
2 AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and
3 Swing supports pluggable look and feel.
feel.
Swing provides more powerful
AWT provides less components than
4 components such as tables, lists,
Swing.
scrollpanes, colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model View
5 Swing follows MVC.
Controller).

88. Components and Containers


 A Swing GUI consists of two key items: components and containers.
 A component is an independent visual control, such as a push button or slider.
 A container holds a group of components.
 So, all Swing GUIs will have at least one container. Because containers are components, a container
can also hold other containers.
88.1 Components:
 Swing components are derived from the JComponent class.
 JComponent provides the functionality that is common to all components.
 JComponent supports the pluggable look and feel.
 JComponent inherits the AWT classes Container and Component.
 All of Swing’s components are represented by classes defined within the package“javax.swing”.
 All the swing component classes begin with the letter J. For example, the class for a label is JLabel;
the class for a push button is JButton; and the class for a scroll bar is JScrollBar.
88.2 Containers:
 Swing defines two types of containers.
 The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. These containers do not
inherit JComponent. They do, however, inherit the AWT classes Component and Container.
 So, the top-level containers are heavyweight.
 The second type of containers supported by Swing are lightweight containers. Lightweight containers
do inherit JComponent.
 An example of a lightweight container is JPanel, which is a general-purpose container.

89. JLabel:
 JLabel is the Swing component that creates a label, which is a component that displays text and/or an
icon.
 The label is Swing’s simplest component because it does not respond to user input and just displays
output.

Page 260
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 167: A java program on JLabel in Swings
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
OUTPUT:

90. JButton
 In order to create buttons we will create objects to JButton class in Swings.
 The following are the constructors in JButton class.
1) JButton(Icon icon)
2) JButton(String str)
3) JButton(String str, Icon icon)
 Here, str and icon are the string and icon used for the button.
 Whenever a button is pressed an ActionEvent is generated.
 To handle this event ActionListener interface is to be implemented and actionPerformed( )method
should be overridden.

Page 261
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 168: A java program on JButton in Swings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonInAction extends JFrame implements ActionListener
{
Container c;
public JButtonInAction( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout

JButton rb = new JButton("Yellow");


JButton gb = new JButton("Pink");
JButton bb = new JButton("Blue");
rb.addActionListener(this); // linking to listener
gb.addActionListener(this);
bb.addActionListener(this);
c.add(rb); // adding buttons
c.add(gb);
c.add(bb);
setTitle("Buttons In Action"); // usual set methods of AWT frame
setSize(300, 350);
setVisible(true);
}
// override the abstract method of ActionListener
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand( ); // know which button user clicked
if(str.equals("Yellow"))
c.setBackground(Color.yellow);
else if(str.equals("Pink"))
c.setBackground(Color.pink);
else if(str.equals("Blue"))
c.setBackground(Color.blue);
}
public static void main(String args[])
{
new JButtonInAction( );
}
}

Page 262
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

91. JCheckBox
 Checkboxes in swings can be used by creating objects to JCheckBox class.
 The constructor of this class is: JcheckBox(String str)
 Whenever a checkbox is checked and unchecked an ItemEvent is generated.
 In order to handle it ItemListener interface is to be implemented and itemStateChanged( ) method
should be overridden.

Program 169: A java program on JCheckBox in Swings

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBox1 extends JFrame implements ItemListener
{
JCheckBox rb,gb,bb;
Container c;
public JCheckBox1( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout
rb = new JCheckBox("Yellow");
gb = new JCheckBox("Pink");
bb = new JCheckBox("Blue");
rb.addItemListener(this); // linking to listener
gb.addItemListener(this);
bb.addItemListener(this);
c.add(rb); // adding buttons
c.add(gb);
c.add(bb);
Page 263
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
setTitle("Check Boxes In Action"); // usual set methods of AWT frame
setSize(300, 350);
setVisible(true);
}
// override the abstract method of ActionListener
public void itemStateChanged(ItemEvent e)
{
if(rb.isSelected( ))
c.setBackground(Color.yellow);
else if(gb.isSelected( ))
c.setBackground(Color.pink);
else if(bb.isSelected( ))
c.setBackground(Color.blue);
}
public static void main(String args[])
{
new JCheckBox1( );
}
}

OUTPUT:

92. JRadioButton
 Radio Buttons are supported by JRadioButton class.
 It supports one of the constructor: JRadioButton(String str)
 Here, str is the label for the button.
 Whenever a Radio Buttion is selected an ItemEvent is generated.
 In order to handle it ItemListener interface is to be implemented and itemStateChanged( ) method
should be overridden.

Page 264
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
Program 170: A java program on JRadioButton in Swings
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButton1 extends JFrame implements ItemListener
{
JRadioButton rb,gb,bb;
Container c;
public JRadioButton1( )
{
c = getContentPane( ); // create the container
c.setLayout(new FlowLayout( )); // set the layout
rb = new JRadioButton("Yellow");
gb = new JRadioButton("Pink");
bb = new JRadioButton("Blue");
rb.addItemListener(this); // linking to listener
gb.addItemListener(this);
bb.addItemListener(this);
c.add(rb); // adding buttons
c.add(gb);
c.add(bb);
setTitle("Radio Buttons In Action"); // usual set methods of AWT frame
setSize(300, 350);
setVisible(true);
}
// override the abstract method of ActionListener
public void itemStateChanged(ItemEvent e)
{
if(rb.isSelected( ))
c.setBackground(Color.yellow);
else if(gb.isSelected( ))
c.setBackground(Color.pink);
else if(bb.isSelected( ))
c.setBackground(Color.blue);
}
public static void main(String args[])
{
new JRadioButton1( );
}
}

Page 265
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

93. JList
 Radio Buttons are supported by JList class.
 It supports one of the constructor: JList(E[ ]items). This creates a JList that contains the items in the
array specified by items.
 A JList generates a ListSelectionEvent when the user makes or changes a selection.
 In order to handle it ListSelectionListener interface is to be implemented and valueChanged( )
method should be overridden.
 A JList allows the user to select multiple ranges of items within the list, but
 you can change this behavior by calling setSelectionMode( ).
 Its signature is: void setSelectionMode(int mode)
 Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
1) SINGLE_SELECTION
2) SINGLE_INTERVAL_SELECTION
3) MULTIPLE_INTERVAL_SELECTION

Program 171: A java program on JList in Swings


import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class JList1 extends JFrame implements ListSelectionListener
{
JList colors;
Container c;
public JList1( )
{
c = getContentPane( );
c.setLayout(new FlowLayout( ));

Page 266
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
String names[] = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow" }; //Add all
items into array.
colors = new JList(names); // creating JList object
colors.setVisibleRowCount(5);
colors.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
c.add(new JScrollPane(colors));
colors.addListSelectionListener(this);
setTitle("Practcing JList");
setSize(300,300);
setVisible(true);
}
public void valueChanged(ListSelectionEvent e)
{
String str = (String) colors.getSelectedValue( );
if(str.equals("Red"))
c.setBackground(Color.red);
else if(str.equals("Green"))
c.setBackground(Color.green);
else if(str.equals("Blue"))
c.setBackground(Color.blue);
else if(str.equals("Cyan"))
c.setBackground(Color.cyan);
else if(str.equals("Magenta"))
c.setBackground(Color.magenta);
else if(str.equals("Yellow"))
c.setBackground(Color.yellow);
}
public static void main(String args[])
{
new JList1( );
}
}

OUTPUT:

Page 267
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
94. JComboBox(JChoiceBox)
 The object of JComboBox class is used to show popup menu of choices.
 Choice selected by user is shown on the top of a menu. It inherits JComponent class.

Program 172: A java program on JComboBox in Swings


import javax.swing.*;
import java.awt.event.*;
public class JComboBox1
{
JFrame f;
JComboBox cb;
JLabel label;
JComboBox1( )
{
f=new JFrame("ComboBox Example");
label = new JLabel( );
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb);
f.add(label);
f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected: "+ cb.getItemAt(cb.getSelectedIndex(
));
label.setText(data);
}
});
}
public static void main(String[] args)
{
new JComboBox1( );
}
}

Page 268
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

95. JTable
 The JTable class is used to display data in tabular form. It is composed of rows and columns.
 It has following constructors:
1) JTable(Object[][] rows, Object[] columns): It Creates a table with the specified data.

Program 173: A java program on JTable in Swings


import javax.swing.*;
public class JTableDemo
{
JFrame f;
JTableDemo( )
{
f=new JFrame( );
String data[][]={ {"11011","ABC","3500"},
{"11099","XYZ","2500"},
{"11366","PQR","6000"}
};
String column[]={"EmpID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new JTableDemo( );
}

Page 269
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
}
OUTPUT:

96. JScrollBar
 The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation
of a scrollbar.
 It inherits JComponent class.

Program 174: A java program on JScrollBar in Swings


import javax.swing.*;
import java.awt.event.*;
class JScrollDemo
{
JScrollDemo( )
{
JFrame f= new JFrame("Scrollbar Example");
JLabel label = new JLabel( );
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JScrollBar s=new JScrollBar( );
s.setBounds(100,100, 50,100);
f.add(s);
f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
s.addAdjustmentListener(new AdjustmentListener( )
{
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue( ));
}
});
}
public static void main(String args[])
{
new JScrollDemo( );
}
}

Page 270
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
OUTPUT:

97. JMenu
 The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
 The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.
 The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.

Program 175: A java program on JMenu in Swings


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MenuDemo implements ActionListener
{
JLabel jlab;
MenuDemo( )
{
// Create a new JFrame container.
JFrame jfrm = new JFrame("Menu Demo");
jfrm.setLayout(new FlowLayout( ));
jfrm.setSize(220, 200);
jlab = new JLabel( );
JMenuBar jmb = new JMenuBar( );
JMenu jmFile = new JMenu("File");
JMenuItem jmiOpen = new JMenuItem("Open");
JMenuItem jmiClose = new JMenuItem("Close");
JMenuItem jmiSave = new JMenuItem("Save");
JMenuItem jmiExit = new JMenuItem("Exit");
jmFile.add(jmiOpen);
jmFile.add(jmiClose);
jmFile.add(jmiSave);
jmFile.addSeparator( );
jmFile.add(jmiExit);
Page 271
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam
jmb.add(jmFile);
// Add action listeners for the menu items.
jmiOpen.addActionListener(this);
jmiClose.addActionListener(this);
jmiSave.addActionListener(this);
jmiExit.addActionListener(this);
// Add the label to the content pane.
jfrm.add(jlab);
// Add the menu bar to the frame.
jfrm.setJMenuBar(jmb);
// Display the frame.
jfrm.setVisible(true);
}
// Handle menu item action events.
public void actionPerformed(ActionEvent ae)
{
// Get the action command from the menu selection.
String comStr = ae.getActionCommand( );
// If user chooses Exit, then exit the program.
if(comStr.equals("Exit"))
System.exit(0);
// Otherwise, display the selection.
jlab.setText(comStr + " Selected");
}
public static void main(String args[])
{
new MenuDemo( );
}
}
OUTPUT:

Page 272
Prepared by: B. Vamsi and Ch. Sudhakar, Asst.Prof of CSE – Vignan’s IIT (A), Visakhapatnam

S-ar putea să vă placă și