0% found this document useful (0 votes)
10 views

Oops Notes

This document provides an introduction to Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses Java's features, including its portability, security, robustness, and garbage collection, as well as the Java Runtime Environment (JRE), Java Development Kit (JDK), and Java Virtual Machine (JVM). The document emphasizes the advantages of Java as a programming language and its architecture-neutral nature.

Uploaded by

PAVITHRA N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Oops Notes

This document provides an introduction to Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses Java's features, including its portability, security, robustness, and garbage collection, as well as the Java Runtime Environment (JRE), Java Development Kit (JDK), and Java Virtual Machine (JVM). The document emphasizes the advantages of Java as a programming language and its architecture-neutral nature.

Uploaded by

PAVITHRA N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 203

UNIT I

INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object Oriented Programming Paradigms – Features of Object Oriented
Programming – Java Buzzwords - Overview of Java – Data Types, Variables and Arrays- Operators -
Control Statements - Programming Structures in Java - Defining classes in Java - constructors - methods
- access specifiers - static members - JavaDoc comments.

OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model organized
around objects rather than actions and data. An object-oriented program can be characterized as data
controlling access to code. Concepts of OOPS
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
List of object-oriented programming languages

Ada 95 Fortran 2003 PHP since v4, greatly enhanced in v5

BETA Graphtalk Python

C++ IDLscript Ruby

C# J# Scala

COBOL Java Simula (the first OOP language)

Cobra LISP Smalltalk

ColdFusion Objective-C Tcl

Common Lisp Perl since v5

OBJECT
An object is any real world entity. The two broad classifications of objects are: Tangible Objects
(Physical objects) and Intangible Objects (Conceptual objects). Tangible objects have physical form that can
be perceived by touch eg. Car, Dishwasher. Intangible objects don’t have physical form; they exist only in
concept eg. Bank Account, A course offered by a University.
Objects have states and behaviors. Example: A dog has states - color, name, breed and behaviors –

1
wagging the tail, barking, eating.
An object is an instance of a class.
An object contains an address and takes up some space in memory. Objects can communicate
without knowing details of each other's data or code, the only necessary thing is that the type of message
accepted and type of response returned by the objects.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
 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.
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. A class consists of Data members and
methods. The primary purpose of a class is to hold data/information. The member functions determine
the behavior of the class,
i.e. Provide a definition for supporting various operations on data held in the form of an object. Class
doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior by the child class from the
parent class. When one object acquires all the properties and behaviours of another object, it is known as
inheritance. It provides code reusability and establishes relationships between different classes. A class
which inherits the properties is known as Child Class (sub-class or derived class) whereas a class whose
properties are inherited is known as Parent class (super-class or base class).
Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and hybrid
inheritance is supported through interface only.

2
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

Polymorphism is classified into two ways:


Method Overloading(Compile time Polymorphism)
Method Overloading is a feature that allows a class to have two or more methods having the same name
but the arguments passed to the methods are different. Compile time polymorphism refers to a process
in which a call to an overloaded method is resolved at compile time rather than at run time.
Method Overriding(Run time Polymorphism)
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. For example: phone call, we don't know the internal processing. In java, we use abstract class
and interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines. A java class is the example of encapsulation.

JAVA BUZZWORDS

Two main feature of Java is Portable and Secure but there other reasons why Java is considered as a powerful
programming language are discussed below. These buzzwords were also discussed by the Java team to describe the
power of Java.

 1. Simple

 2. Secure

3
 3. Portable

 4. Object-Oriented

 5. Robust

 6. Mutithreaded

 7. Architecture Neutral

 8. Interpreted

 9. High Performance

 10. Distributed

 11. Dynamic

Simple: Java inherits all the best features from the programming languages like C, C++ and thus makes it really
easy for any developer to learn with little programming experience. The concept of Object Oriented programming
was not invented by Java but it was just adopted by the Java team. Programming notation of Java is not different
from the programming language like C and C++ which makes developers have little trouble to learn Java.

Secure: When Java programs are executed they don’t instruct commands to the machine directly. Instead Java
Virtual machine reads the program (ByteCode) and convert it into the machine instructions. This way any program
tries to get illegal access to the system will not be allowed by the JVM. Allowing Java programs to be executed by
the JVM makes Java program fully secured under the control of the JVM.

Portable: Java programs are portable because of its ability to run the program on any platform and no dependency
on the underlying hardware / operating system.

Object Oriented Programming Language: Java programming language was influenced from its previous
successors programming language like C++. Java developers did not just took everything and implemented in Java
but they analyzed the current challenges in the existing language and then included what is necessary.

Java is object oriented programming language but everything in Java are not objects. Java manages to maintain
balance and adopted what make sense in the current situation. The object oriented model in Java is simple and easy
to extend and also the primitive types such as integers, are retained for high-performance.

Robust: Following features of Java make it Robust.

 Platform Independent

 Object Oriented Programming Language

 Memory management

 Exception Handling

Platform Independent: Java program are written once and executed on any platform this makes the job of
developer easier to develop programs and not code machine dependent coding.

4
Object Oriented Programming Language: helps to break the complex code into easy to understand objects and
manage high complexity programs in distributed team environment.

Memory Management: In traditional programming language like C, C++ user has to manage memory by
allocating and deallocating memory which leads to memory leaks in the program. In Java, memory management is
taken care by the Java Virtual Machine and safe from memory crashes. All the allocation and clean of the memory
is done automatically.

Exception Handling: In Java, developers are forced to handle the exception during the development time. All the
possible exception are errored out during the compilation of the program. This way when the exception happens
during runtime there is proper exception handling mechanism already coded in the program.

Multithreaded: Java allows you to develop program that can do multiple task simultaneously. Interactive based
programming allows you to write program that responds to the user actions and helps developers to just implement
the logic based on the user action instead to manage the complete multi-tasking solution.

Architecture-Neutral: The major challenge when Java was developing is to have programming language with
which a program can be developed and executed anytime in future. With changing environments of hardware,
processor, Operating system there was need to have program still adopt to this architecture changes. Java code does
not depend on the underlying architecture and only depends on it JVM thus accomplish the architecture neutral
programming language.

Interpreter: The compiled code of Java is not machine instructions but rather its a intermediate code called
ByteCode. This code can be executed on any machine that implements the Java virtual Machine. JVM interprets
the ByteCode into Machine instructions during runtime.

High Performance: When java programs are executed, JVM does not interpret entire code into machine
instructions. If JVM attempts to do this then there will huge performance impact for the high complexity programs.
JVM was intelligently developed to interpret only the piece of the code that is required to execute and untouch the
rest of the code. The performance of java is never questioned compared with another programming language.

Distributed: Java has a feature called Remote Method Invocation (RMI) using which a program can invoke
method of another program across a network and get the output.

Dynamic: Java programs access various runtime libraries and information inside the compiled code (Bytecode).
This dynamic feature allows to update the pieces of libraries without affecting the code using it.

FEATURES OF JAVA
The main objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some awesome features which play important role in
the popularity of this language. The features of Java are also known as java buzzwords.
A list of most important features of Java language are given below.
Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many confusing and rarely-used features e.g. explicit pointers, operator
overloading etc.
 There is no need to remove unreferenced objects because there is Automatic Garbage Collection in
java.

5
Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporates both data and
behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent

6
Java is platform independent because it is different from other languages like C, C++ etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides software-based
platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox

7
 Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
dynamically load Java classes into the Java Virtual Machine. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
 Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
These security are provided by java language. Some security can also be provided by application developer
through SSL, JAAS, Cryptography etc.
Robust
 Robust simply means strong. Java is robust because:
 It uses strong memory management.
 There are lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
 There is exception handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.
Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't require any
type of implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an interpreted language
that is why it is slower than compiled languages e.g. C, C++ etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages i.e. C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

GARBAGE COLLECTION
Objects are dynamically allocated by using the new operator, dynamically allocated objects must be
manually released by use of a delete operator. Java takes a different approach; it handles deallocation
automatically this is called garbage collection. When no references to an object exist, that object is assumed
to be no longer needed, and the memory occupied by the object can be reclaimed. Garbage collection only
occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or
more objects exist that are no longer used.
8
THE JAVA ENVIRONMENT
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing java applications. It is used to provide
runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries +
other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.

6
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Internal Architecture of JVM

1. Classloader
Classloader is a subsystem of JVM that is used to load class files.
2. Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.
3. Heap
It is the runtime data area in which objects are allocated.
4. Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation
and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

7
5. Program Counter Register
PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
6. Native Method Stack
It contains all the native methods used in the application.
7. Execution Engine
Contains a virtual processor, Interpreter to read bytecode stream then execute the instructions and Just-In-
Time(JIT) compiler is used to improve the performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here,
the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

STRUCTURE OF JAVA PROGRAM


A first Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Java World");
}
}
To compile:
javac Simple.java
To execute:
java Simple
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The core advantage of
static method is that there is no need to create object to invoke the static method. The main method is
executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.

A program is written in JAVA, the javac compiles it. The result of the JAVA compiler is the .class file or
the bytecode and not the machine native code (unlike C compiler).
The bytecode generated is a non-executable code and needs an interpreter to execute on a machine. This
interpreter is the JVM and thus the Bytecode is executed by the JVM.
And finally program runs to give the desired output.

8
DEFINING CLASSES IN JAVA
The class is at the core of Java .A class is a template for an object, and an object is an instance of a class. A
class is declared by use of the class keyword
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
...
type methodnameN(parameter-list) {
// body of method
}
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. The methods and variables defined within a class are called members of the class. In most classes,
the instance variables are acted upon and accessed by the methods defined for that class.
Variables defined within a class are called instance variables because each instance of the class (that is, each
object of the class) contains its own copy of these variables. Thus, the data for one object is separate and
unique from the data for another.

A Simple Class
class called Box that
defines three instance variables: width, height, and depth.
class Box {
double width;
double height;
double depth;
}
The new data type is called Box. This name is used to declare objects of type Box. The class declaration
only creates a template. It does not create an actual object.

To create a Box object

Box mybox = new Box(); // create a Box object called mybox

mybox will be an instance of Box.


9
Each time you create an instance of a class, you are creating an object that contains its own copy of each
instance variable defined by the class. To access these variables, you will use the dot (.) operator. The dot
operator links the name of the object with the name of an instance variable.
Example1:
/* A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0

Example2:
// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;

10
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Declaring Objects
First, declare a variable of the class type. This variable does not define an object.Instead, it is simply a
variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. This is done
using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for
an object and returns a reference to it. This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated.
Syntax:
Box mybox = new Box();
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yet
refer to an actual object. The next line allocates an object and assigns a reference to it to mybox. After the
second line executes, we can use mybox as if it were a Box object. But in reality, mybox simply holds, in
essence, the memory address of the actual Box object.

Assigning Object Reference Variables


Syntax:
Box b1 = new Box();
Box b2 = b1;
b2 is being assigned a reference to a copy of the object referred to by b1. b1 and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original

11
object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object
through b2 will affect the object to which b1 is referring, since they are the same object.

CONSTRUCTORS
Constructors are special member functions whose task is to initialize the objects of its class.
It is a special member function, it has the same as the class name.
Java constructors are invoked when their objects are created. It is named such because, it constructs
the value, that is provides data for the object and are used to initialize objects.
Every class has a constructor when we don't explicitly declare a constructor for any java class the
compiler creates a default constructor for that class which does not have any return type.
The constructor in Java cannot be abstract, static, final or synchronized and these modifiers are not
allowed for the constructor.
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Default constructor (no-arg constructor)


A constructor having no parameter is known as default constructor and no-arg constructor.
Example:
/* Here, Box uses a constructor to initialize the
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

12
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
new Box( ) is calling the Box( ) constructor. When the constructor for a class is not explicitly defined , then
Java creates a default constructor for the class. The default constructor automatically initializes all instance
variables to their default values, which are zero, null, and false, for numeric types, reference types, and
boolean, respectively.

Parameterized Constructors
A constructor which has a specific number of parameters is called parameterized constructor. Parameterized
constructor is used to provide different values to the distinct objects.
Example:
/* Here, Box uses a parameterized constructor to
initialize the dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {

13
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Output:
Volume is 3000.0
Volume is 162.0
Box mybox1 = new Box(10, 20, 15);
The values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object. Thus, mybox1’s
copy of width, height, and depth will contain the values 10, 20, and 15 respectively.

Overloading Constructors
Example:
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.
*/
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}

14
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

METHODS
Syntax:
type name(parameter-list) {
// body of method
}
 type specifies the type of data returned by the method. This can be any valid type, including class
types that you create.
 If the method does not return a value, its return type must be void.
 The name of the method is specified by name.
 The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters
are essentially variables that receive the value of the arguments passed to the method when it is
called. If the method has no parameters, then the parameter list will be empty.
 Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
Syntax:
return value;
Example:
// This program includes a method inside the box class.
class Box {
double width;
double height;
double depth;
// display volume of a box
15
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
Output:
Volume is 3000.0
Volume is 162.0
The first line here invokes the volume( ) method on mybox1. That is, it calls volume( ) relative to the
mybox1 object, using the object’s name followed by the dot operator. Thus, the call to mybox1.volume( )
displays the volume of the box defined by mybox1, and the call to mybox2.volume( ) displays the volume
of the box defined by mybox2. Each time volume( ) is invoked, it displays the volume for the specified box.

Returning a Value
Example:
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables

16
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000
Volume is 162

when volume( ) is called, it is put on the right side of an assignment statement. On the left is a variable, in
this case vol, that will receive the value returned by volume( ).
Syntax:
vol = mybox1.volume();
executes, the value of mybox1.volume( ) is 3,000 and this value then is stored in vol.

There are two important things to understand about returning values:


• The type of data returned by a method must be compatible with the return type specified by the method.
• The variable receiving the value returned by a method (such as vol, in this case) must also be compatible
with the return type specified for the method.

Adding a Method That Takes Parameters


Example:
// This program uses a parameterized method.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

17
}

class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000
Volume is 162

The this Keyword


this keyword is used to to refer to the object that invoked it. this can be used inside any method to refer to
the current object. That is, this is always a reference to the object on which the method was invoked. this()
can be used to invoke current class constructor.
Syntax:
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
Example:
class Student
{
int id;
String name;
student(int id, String name)
{
this.id = id;
this.name = name;

}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
18
Student stud1 = new Student(01,"Tarun");
Student stud2 = new Student(02,"Barun");

stud1.display();
stud2.display();
}
}
Output:
01 Tarun
02 Barun

Overloading Methods
When two or more methods within the same class that have the same name, but their parameter declarations
are different. The methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Example:
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
19
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

Method Overriding
When a method in a subclass has the same name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the superclass. When an overridden method is
called from within its subclass, it will always refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Example:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the
version of show( ) inside B overrides the version declared in A. If you wish to access the superclass version
of an overridden method, you can do so by using super. For example, in this version of B, the superclass
version of show( ) is invoked within the subclass’ version. This allows all instance variables to be displayed.
20
class B extends A {
int k;
B(int a, int b, int c) {

super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).

ACCESS PROTECTION
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
1) Private Access Modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, 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.
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
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class.
For example:
class A{
private A(){}//private constructor
21
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

If you make any class constructor private, you cannot create the instance of that class from outside the class.
For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

2) Default Access Modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.
Example:
In this example, 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.
//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
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

22
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.
Example:
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.
//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{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:
Hello

4) Public Access Modifier


The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example:
//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();
}
}

23
Output:
Hello

Access Modifier Within Class Within Package Outside Package Outside Package
By Subclass Only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Java access modifiers with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why there is compile time error.

STATIC MEMBERS
Static is a non-access modifier in Java which is applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
Static blocks
If you need to do computation in order to initialize your static variables, you can declare a static block that
gets executed exactly once, when the class is first loaded.
Example:
// Java program to demonstrate use of static blocks
class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
24
public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40

Static variables
When a variable is declared as static, then a single copy of variable is created and shared among all objects
at class level. Static variables are, essentially, global variables. All instances of the class share the same
static variable.
Important points for static variables :-
 We can create static variables at class-level only.
 static block and static variables are executed in order they are present in a program.
Example:
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Output:
Static block initialized.
x = 42
a=3
b = 12

Static methods
When a method is declared with static keyword, it is known as static method. When a member is declared
static, it can be accessed before any objects of its class are created, and without reference to any object. The
most common example of a static method is main( ) method. Methods declared as static have several
25
restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Syntax:
classname.method( )
Example:
//Inside main( ), the static method callme( ) and the static variable b are accessed through their class name
//StaticDemo.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Output:
a = 42
b = 99
JAVA COMMENTS
The java comments are statements that are not executed by the compiler and interpreter. The comments can
be used to provide information or explanation about the variable, method, class or any statement. It can also
be used to hide program code for specific time.
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
public class CommentExample1
{
public static void main(String[] args)
{
int i=10;//Here, i is a variable
System.out.println(i);
}
}

26
Output:
10

2) Java Multi Line Comment


The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
10

3) Java Documentation Comment


The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/

Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{

27
return a-b;
}
}
This type of comment is used to produce an HTML file that documents your program. The documentation
comment begins with a /** and ends with a */.
DATATYPES IN JAVA
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: The primitive data types include Integer, Character, Boolean, and Floating
Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. These can
be put in four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
• Floating-point numbers This group includes float and double, which represent numbers with fractional
precision.
• Characters This group includes char, which represents symbols in a character set, like letters and numbers.
• Boolean This group includes boolean, which is a special type for representing true/false values.
Example :
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
28
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
Output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.

VARIABLES
A variable is a container which holds the value and that can be changed durig the execution of the program.
A variable is assigned with a datatype. Variable is a name of memory location. All the variables must be
declared before they can be used. There are three types of variables in java: local variable, instance variable
and static variable.

20

1) Local Variable
A variable defined within a block or method or constructor is called local variable.
 These variable are created when the block in entered or the function is called and destroyed after
exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared. i.e. we can
access these variable only within that block.
Example:
import java.io.*;
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
Output:
Student age is : 5

2) Instance Variable
Instance variables are non-static variables and are declared in a class outside any method, constructor or
29
block.
 As instance variables are declared in a class, these variables are created when an object of the class is
created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not specify any
access specifier then the default access specifier will be used.
Example:
import java.io.*;
class Marks{
int m1;
int m2;
}
class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new Marks();
obj1.m1 = 50;
obj1.m2 = 80;
//second object
Marks obj2 = new Marks();
obj2.m1 = 80;
obj2.m2 = 60;
//displaying marks for first object
System.out.println("Marks for first object:");
System.out.println(obj1.m1);
System.out.println(obj1.m2);
//displaying marks for second object
System.out.println("Marks for second object:");
System.out.println(obj2.m1);
System.out.println(obj2.m2);
}}
Output:
Marks for first object:
50
80
Marks for second object:
80
60
3) Static variable
Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the difference is that static variables are
declared using the static keyword within a class outside any method constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class irrespective of how
many objects we create.
 Static variables are created at start of program execution and destroyed automatically when execution
ends.
Example:
import java.io.*;
class Emp {

30
// static variable salary
public static double salary;
public static String name = "Vijaya";
}
public class EmpDemo
{
public static void main(String args[]) {

//accessing static variable without object


Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}
}
Output:
Vijay’s average salary:10000.0

Difference between Instance variable and Static variable


INSTANCE VARIABLE STATIC VARIABLE
Each object will have its own copy of instance We can only have one copy of a static variable per
variable class irrespective of how many objects we create.
Changes made in an instance variable using one In case of static changes will be reflected in other
object will not be reflected in other objects as each objects as static variables are common to all object
object has its own copy of instance variable of a class.
We can access instance variables through object Static Variables can be accessed directly using class
references name.
Class Sample Class Sample
{ {
int a; static int a;
} }

OPERATORS IN JAVA
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups –
 Arithmetic Operators
 Increment and Decrement
 Bitwise Operators
 Relational Operators
 Boolean Operators
 Assignment Operator
 Ternary Operator
Arithmetic Operators
Arithmetic operators are used to manipulate mathematical expressions
Operator Result

31
Example:
// Demonstrate the basic arithmetic operators.
class BasicMath
{
public static void main(String args[])
{
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}}
Output:
Integer Arithmetic
a=2
b=6
c=1
32
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6
dc = 1.5
dd = -0.5
de = 0.5

Modulus Operator
The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-point
types as well as integer types.
Example:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output:
x mod 10 = 2
y mod 10 = 2.25

Arithmetic Compound Assignment Operators


Java provides special operators that can be used to combine an arithmetic operation with an assignment.
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
Syntax:
var op= expression;
Example:
// Demonstrate several assignment operators.
class OpEquals
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
33
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Output:
a=6
b=8
c=3

Increment and Decrement Operators


The ++ and the – – are Java’s increment and decrement operators. The increment operator increases its
operand by one. The decrement operator decreases its operand by one.
Example:
// Demonstrate ++.
class IncDec
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output:
a=2
b=3
c=4
d=1

34
Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types: long, int, short, char, and

byte. These operators act upon the individual bits of their operands.

Bitwise Logical Operators


The bitwise logical operators are &, |, ^, and ~. the bitwise operators are
applied to each individual bit within each operand.

Example:
// Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
String binary[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b)|(a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
35
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
Output:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100

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

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

36
5
2
Relational Operators
The relational operators determine the relationship that one operand has to the other.Specifically, they
determine equality and ordering. The outcome of these operations is a boolean value.
Boolean Operators
The Boolean logical operators shown here operate only on boolean operands. All of the binary logical
operators combine two boolean values to form a resultant boolean value.

Example:
// Demonstrate the boolean logical operators.
class BoolLogic
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d= a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
Output:
a = true
b = false
a|b = true
a&b = false
37
a^b = true
!a&b|a&!b = true
!a=false
In the output, the string representation of a Java boolean value is one of the literal values true or false. Java
AND Operator Example: Logical && and Bitwise &
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.
Example:
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<b&a<c);//false & true = false
}
}
Output:
false
false

Assignment Operator
The assignment operator is the single equal sign, =.
Syntax:
var = expression;
Here, the type of var must be compatible with the type of expression.
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.

Ternary Operator
Ternary operator in java is used as one liner replacement for if-then-else statement and used a lot in java
programming. it is the only conditional operator which takes three operands.
Syntax:
expression1 ? expression2 : expression3
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);
}
}

38
Output:
2

CONTROL STATEMENTS
Selection Statements in Java
A programming language uses control statements to control the flow of execution of program based on
certain conditions.
Java’s Selection statements:
 if
 if-else
 nested-if
 if-else-if
 switch-case
 jump – break, continue, return

if Statement
if statement is the most simple decision making statement. It is used to decide whether a certain statement or
block of statements will be executed or not that is if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
if(condition)
{
//statements to execute if
//condition is true
}
Condition after evaluation will be either true or false. If the value is true then it will execute the block of
statements under it. If there are no curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement
will consider the immediate one statement to be inside its block.

Example:
class IfSample
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
39
if(x < y)
System.out.println("x is less than y");
x = x * 2;
if(x == y)
System.out.println("x now equal to y");
x = x * 2;
if(x > y)
System.out.println("x now greater than y");
// this won't display anything
if(x == y)
System.out.println("you won't see this");
}
}
Output:
x is less than y
x now equal to y
x now greater than y

if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true else if it is false
the else block is executed.
Syntax:.
If(condition)
{
//Executes this block if
//condition is true
}
else
{
//Executes this block if
//condition is false
}

40
Example:

public 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

Nested if Statement
Nested if-else statements, is that using one if or else if statement inside another if or else if statement(s).

Example:
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
41
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");}
}
}
Output:
i is smaller than 15
i is smaller than 12 too

if-else-if ladder statement


The if statements are executed from the top down. The conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed.
Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;

Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
42
}
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){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade

Switch Statements
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to
different parts of your code based on the value of an expression.
Syntax:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Example:
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");

43
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}}}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.

44
ITERATIVE 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.

 while loop
 do-while loop
 For loop
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax:
while(condition) {
// body of loop
}

While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. It is called as Entry
controlled loop.
Normally the statements contain an update value for the variable being processed for the next
iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
Example:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 5;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
Output:
tick 5
tick 4

45
tick 3
tick 2
tick 1
do-while loop:
do while loop checks for condition after executing the statements, and therefore it is called as Exit
Controlled Loop.
Syntax:
do {
// body of loop
} while (condition);

do while loop starts with the execution of the statement(s). There is no checking of any condition for
the first time.
After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
Example
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5

46
for loop

for loop provides a concise way of writing the loop structure. A for statement consumes the initialization,
condition and increment/decrement in one line.
Syntax
for(initialization; condition; iteration) {
// body
}

Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value.
It is also an Entry Control Loop as the condition is checked prior to the execution of the loop
statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of its life
cycle.
Example
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
System.out.println(i);
}
}}
Output:
1
2
47
3
4
5

for-each Loop

The for-each loop is used to traverse array or collection 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(type itr-var : collection) statement-block

Example:
// Use a for-each style for loop.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
Example:
// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
48
System.out.print(".");
System.out.println();
}}
}
Output:

..........
.........
........
.......
......
.....
....
...
..
.
JUMP STATEMENTS
Java 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.

Example:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
49
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.

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

Example:
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without
printing a newline.
Output:
01
23
45
67
89

Return
The last control statement is return. The return statement is used to explicitly return from a method. That is,
it causes program control to transfer back to the caller of the method.
Example:
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
50
Output:
Before the return.

ARRAYS
 Array is a collection of similar type of elements that have contiguous memory location.
 In Java all arrays are dynamically allocated.
 Since arrays are objects in Java, we can find their length using member length.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each have an index beginning from 0.
 Java array can be also be used as a static field, a local variable or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.

Advantage of Java Array


 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.
Disadvantage of Java Array
 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.

Types of Array in java


1. One- Dimensional Array
2. Multidimensional Array

One-Dimensional Arrays
An array is a group of like-typed variables that are referred to by a common name. An array declaration has
two components: the type and the name. type declares the element type of the array. The element type
determines the data type of each element that comprises the array. We can also create an array of other
primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the
element type for the array determines what type of data the array will hold.
Syntax:
type var-name[ ];
Instantiation of an Array in java
array-var = new type [size];
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization

51
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
Declaration, Instantiation and Initialization of Java Array
Example:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//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:
33
3
4
5

Passing Array to method in java


We can pass the java array to method so that we can reuse the same logic on any array.
Example:
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[]={33,3,4,5};
min(a);//passing array to method
}}
Output:
3
52
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of
square brackets ([]) per dimension.
Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Example:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19

When you allocate memory for a multidimensional array, you need only specify the memory for the first
(leftmost) dimension. You can allocate the remaining dimensions separately. For example, this following
code allocates memory for the first dimension of twoD when it is declared. It allocates the second
dimension manually.
53
Syntax:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];

twoD[3] = new int[5];


Example:
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
0
12
345
6789
The array created by this program looks like this:

54
PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be
categorized in two form, built-in package and 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.

Defining a Package
To create a package the programmer need to include a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. If package statement is omitted, the class names
are put into the default package, which has no name.
Syntax:
package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called
MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any classes you declare
to be part of MyPackage must be stored in a directory called MyPackage.

It is possible to create a hierarchy of packages. The general form of a multileveled package statement is
shown here:
package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system. For example, a
package declared as
package java.awt.image;

55
needs to be stored in java\awt\image in a Windows environment. We cannot rename a package without
renaming the directory in which the classes are stored.

Finding Packages and CLASSPATH

First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if
your package is in a subdirectory of the current directory, it will be found. Second, you can specify a
directory path or paths by setting the CLASSPATH environmental variable. Third, you can use the
classpath option with java and javac to specify the path to your classes.

consider the following package specification:


package MyPack
In order for a program to find MyPack, one of three things must be true. Either the program can be
executed from a directory immediately above MyPack, or the CLASSPATH must be set to include the path
to MyPack, or the -classpath option must specify the path to MyPack when the program is run via java.
When the second two options are used, the class path must not include MyPack, itself. It must simply
specify the path to MyPack. For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
then the class path to MyPack is
C:\MyPrograms\Java
Example:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then, try
executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
56
Remember, you will need to be in the directory above MyPack when you execute this command.
(Alternatively, you can use one of the other two options described in the preceding section to specify the
path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed
by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

Example:
package pck1;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd)
{
rollno = rno;
name = sname;
address = sadd;
}
public void showDetails()
{
System.out.println("Roll No :: " + rollno);
System.out.println("Name :: " + name);
System.out.println("Address :: " + address);
}
}
public class DemoPackage
{
public static void main(String ar[])
{
Student st[]=new Student[2];
st[0] = new Student (1001,"Alice", "New York");
st[1] = new Student(1002,"BOb","Washington");
st[0].showDetails();
st[1].showDetails();
}
}
There are two ways to create package directory as follows:
1. Create the folder or directory at your choice location with the same name as package name. After
compilation of copy .class (byte code file) file into this folder.
2. Compile the file with following syntax.
javac -d <target location of package> sourceFile.java

The above syntax will create the package given in the sourceFile at the <target location of pacakge> if it is
not yet created. If package already exist then only the .class (byte code file) will be stored to the package
given in sourceFile.

Steps to compile the given example code:


57
Compile the code with the command on the command prompt.
javac -d DemoPackage.java
1. The command will create the package at the current location with the name pck1, and contains the file
DemoPackage.class and Student.class
2. To run write the command given below
java pckl.DemoPackage

Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully qualified type
name to run or access it.

Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Name :: Bob
Address :: Washington

58
UNIT II INHERITANCE, PACKAGES AND INTERFACES
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner
Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding –
Dynamic Method Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces:
Packages – Packages and Member Access –Importing Packages – Interfaces.

OVERLOADING METHODS
When two or more methods within the same class that have the same name, but their
parameter declarations are different. The methods are said to be overloaded, and the process is
referred to as method overloading. Method overloading is one of the ways that Java supports
polymorphism. There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Example: // Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
} // Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
} // Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
} // Overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result; // call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
OBJECTS AS PARAMETERS
Object as an argument is use to establish communication between two or more objects of
same class as well as different class, i.e, user can easily process data of two same or different
objects within function. In Java, When a primitive type is passed to a method, it is done by use of
call-by-value . Objects are implicitly passed by use of call-by-reference.

This means when we pass primitive data types to method it will pass only values to
function parameters so any change made in parameter will not affect the value of actual
parameters. Whereas Objects in java are reference variables, so for objects a value which is the
reference to the object is passed. Hence the whole object is not passed but its referenced gets
passed. All modification to the object in the method would modify the object in the Heap.
PROGRAM:
Class Add
{
int a;
int b;
Add(int x,int y)// parametrized constructor
{
a=x;
b=y;
}
void sum(Add A1) // object 'A1' passed as parameter in function 'sum'
{
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b :"+sum1);
}}
public class classExAdd
{
public static void main(String arg[])
{
Add A=new Add(5,8);
/* Calls the parametrized constructor
with set of parameters*/
A.sum(A);
}}
OUTPUT:
Sum of a and b :13

While creating a variable of class type, we only create a reference to an object. When we pass
this reference to a function, the parameters that receive it will refer to the same object as that
referred to by the argument.

RETURNING OBJECTS
In java, a function can return any type of data, including class type objects.For ex: In the
program given below, the add() function return an object which contain sum of values of two
different Numbers(objects).
import java.util.Scanner;
class TwoNum
{
private int a,b;

Scanner kb=new Scanner(System.in);

void getValues() // getValues() take values of a,b for every no.


{
System.out.print("Enter a: ");
a=kb.nextInt();
System.out.print("Enter b: ");
b=kb.nextInt();
}
void putValues()// putValues() show values for every no.
{
System.out.println(a+" "+b);
}

TwoNum add(TwoNum B)/*class type function add() takeobject 'B' as parameter*/


{
TwoNum D=new TwoNum();//object D act as instance variable
D.a=a+B.a;
D.b=b+B.b;
return (D);//returning object D
}}
class ExTwoNum
{
public static void main(String arg[])
{
TwoNum A=new TwoNum();
A.getValues();
A.putValues();

TwoNum B=new TwoNum();


B.getValues();
B.putValues();

TwoNum C;
/*object A calls add() passing object B
as parameter and result are return at C*/
C=A.add(B);

C.putValues();
}}
OUTPUT
Enter a: 23
Enter b: 34
23 34
Enter a: 25
Enter b: 35
25 35
48 69 /*sum*/
INNER CLASSES
Inner class means one class which is a member of another class. There are basically four types of
inner classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes
NESTED INNER CLASS
Nested Inner class can access any private instance variable of outer class. Like any other
instance variable, we can have access modifier private, protected, public and default modifier.
Like class, interface can also be nested and can have access specifiers.
EXAMPLE:
class Outer {
// Simple nested inner class
class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.show();
}}
Output:
In a nested class method
METHOD LOCAL INNER CLASSES
Inner class can be declared within a method of an outer class. In the following example, Inner is
an inner class in outerMethod().
Example:
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
}}
Inner y = new Inner(); y.innerMethod();
}}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer(); x.outerMethod();
}}
Output:
Inside outerMethod
Inside innerMethod
STATIC NESTED CLASSES
Static nested classes are not technically an inner class. They are like a static member of outer
class.
Example:
class Outer {
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
// A static inner class static class Inner {
public static void main(String[] args)
{
System.out.println("inside inner class Method");
outerMethod();
}}}
OUTPUT:
inside inner class Method inside outerMethod
ANONYMOUS INNER CLASSES
Anonymous inner classes are declared without any name at all. They are created in two ways.
a) As subclass of specified type
class Demo {
void show()
{
System.out.println("i am in show method of super class");
}}
class Flavor1Demo
{
// An anonymous class with Demo as base class
static Demo d = new Demo()
{
void show()
{
super.show();
System.out.println("i am in Flavor1Demo class");
}};
public static void main(String[] args)
{
d.show();
}}
Output:
i am in show method of super class
i am in Flavor1Demo class
In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show(). In anonymous class
show() method is overridden.
b) As implementer of the specified interface
Example:
class Flavor2Demo
{
// An anonymous class that implements Hello interface
static Hello h = new Hello()
{
public void show()
{
System.out.println("i am in anonymous class");
}
};
public static void main(String[] args) { h.show();
}}
interface Hello { void show(); }
OUTPUT:
i am in anonymous class
In above code we create an object of anonymous inner class but this anonymous inner
class is an implementer of the interface Hello. Any anonymous inner class can implement only
one interface at one time. It can either extend a class or implement interface at a time.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties
and behaviors of one class to another, i.e., acquiring the properties and behavior of child class
from the parent class. When one object acquires all the properties and behaviors’ of another
object, it is known as inheritance. Inheritance represents the IS-A relationship, also known as
parent-child relationship.
Uses of inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and hybrid
inheritance is supported through interface only.
Syntax:
class subClass extends superClass
{
//methods and fields
}
Terms used in Inheritance

 Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in previous class.

SINGLE INHERITANCE

In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
ClassB b = new ClassB();//Assigning ClassB object to ClassB reference
.dispA();//call dispA() method of ClassA b
b.dispB();//call dispB() method of ClassB
}
}
Output :
disp() method of ClassA
disp() method of ClassB
MULTILEVEL INHERITANCE
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class
becomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
ClassC c = new ClassC();//Assigning ClassC object to ClassC reference
c.dispA();//call dispA() method of ClassA
c.dispB();//call dispB() method of ClassB
c.dispC();//call dispC() method of ClassC
}}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC
HIERARCHICAL INHERITANCE
In Hierarchical Inheritance, one class is inherited by many sub classes.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB();//Assigning ClassB object to ClassB reference
b.dispB();//call dispB() method of ClassB
b.dispA();//call dispA() method of ClassA
ClassC c = new ClassC();//Assigning ClassC object to ClassC reference
c.dispC();//call dispC() method of ClassC
c.dispA();//call dispA() method of ClassA
ClassD d = new ClassD();//Assigning ClassD object to ClassD reference
d.dispD();//call dispD() method of ClassD
d.dispA();//call dispA() method of ClassA
}}
Output :
disp() method of ClassB disp() method of ClassA disp() method of ClassC disp() method of
ClassA disp() method of ClassD disp() method of ClassA

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again Hybrid
inheritance is also not directly supported in Java only through interface we can achieve this.
Flow diagram of the Hybrid inheritance will look like below. As you can ClassA will be acting
as the Parent class for ClassB & ClassC and ClassB & ClassC will be acting as Parent for
ClassD.

Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages such as
Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance). As the Child class has
to manage the dependency of more than one Parent class. But you can achieve multiple
inheritance in Java using Interfaces.

“super” KEYWORD
Usage of super keyword
1. super() invokes the constructor of the parent class.
2. super.variable_name refers to the variable in the parent class.
3. super.method_name refers to the method of the parent class.
1. SUPER() INVOKES THE CONSTRUCTOR OF THE PARENT CLASS
super() will invoke the constructor of the parent class. Even when you don’t add super() keyword
the compiler will add one and will invoke the Parent Class constructor.
Example:
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor
Child Class default Constructor
Even when we add explicitly also it behaves the same way as it did before. class ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}}
Output:
Parent Class default Constructor
Child Class default Constructor
You can also call the parameterized constructor of the Parent Class. For example, super(10) will
call parameterized constructor of the Parent class.
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor called");
}
ParentClass(int val)
{
System.out.println("Parent Class parameterized Constructor, value: "+val);
}}
public class SubClass extends ParentClass
{
SubClass()
{
super();//Has to be the first statement in the constructor
System.out.println("Child Class default Constructor called");
}
SubClass(int val)
{
super(10);
System.out.println("Child Class parameterized Constructor, value: "+val);
}
public static void main(String args[])
{
SubClass s = new SubClass();//Calling default constructor
SubClass s1 = new SubClass(10); //Calling parameterized constructor
}}
Output
Parent Class default Constructor called
Child Class default Constructor called
Parent Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10
2. super.variable_name refers to the variable in the parent class
When we have the same variable in both parent and subclass class ParentClass
{

int val=999;
}
public class SubClass extends ParentClass
{
int val=123;

void disp()
{
System.out.println("Value is : "+val);
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.disp();
}
}
Output
Value is : 123
This will call only the val of the sub class only. Without super keyword, you cannot call the val
which is present in the Parent Class. class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;

void disp()
{
System.out.println("Value is : "+super.val);
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.disp();
}
}
Output
Value is : 999
3. super.method_name refers to the method of the parent class
When you override the Parent Class method in the Child Class without super keywords support
you will not be able to call the Parent Class method. Let’s look into the below example
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show();
}
}
Output:
Child Class method
Here we have overridden the Parent Class disp() method in the SubClass and hence SubClass
disp() method is called. If we want to call the Parent Class disp() method also means then we
have to use the super keyword for it.
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
//Calling SubClass disp() method disp();
//Calling ParentClass disp() method super.disp();
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.show();
}
}
Output
Child Class method
Parent Class method
When there is no method overriding then by default Parent Class disp() method will be called.
class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void show()
{
disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show();
}}
Output:
Parent Class method
METHOD OVERRIDING
Declaring a method in sub class which is already present in parent class is known as
method overriding. Overriding is done so that a child class can give its own implementation to a
method which is already provided by the parent class. In this case the method in parent class is
called overridden method and the method in child class is called overriding method.
Example
Lets take a simple example to understand this. We have two classes: A child class Boy
and a parent class Human. The Boy class extends Human class. Both the classes have a common
method void eat(). Boy class is giving its own implementation to the eat() method or in other
words it is overriding the eat() method.
The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of Human is
eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
DYNAMIC METHOD DISPATCH
 Dynamic method dispatch is also known as run time polymorphism.
 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than
compile time.
To properly understand Dynamic method dispatch in Java, it is important to understand the
concept of upcasting because dynamic method dispatch is based on upcasting.
Upcasting :
It is a technique in which a superclass reference variable refers to the object of the subclass.
Example :
class Animal{}
class Dog extends Animal{}
Animal a=new Dog();//upcasting
In the above example, we've created two classes, named Animal(superclass) & Dog(subclass).
While creating the object 'a', we've taken the reference variable of the parent class(Animal), and
the object created is of child class(Dog).
Example to demonstrate the use of Dynamic method dispatch :
 In the below code, we've created two classes: Phone & SmartPhone.
 The Phone is the parent class and the SmartPhone is the child class.
 The method on() of the parent class is overridden inside the child class.
 Inside the main() method, we've created an object obj of the Smartphone() class by taking
the reference of the Phone() class.
 When obj.on() will be executed, it will call the on() method of the SmartPhone() class
because the reference variable obj is pointing towards the object of class SmartPhone().
class Phone{
public void showTime()
{
System.out.println("Time is 8 am");
}
public void on()
{
System.out.println("Turning on Phone...");
}}

class SmartPhone extends Phone


{
public void music()
{
System.out.println("Playing music...");
}
public void on()
{
System.out.println("Turning on SmartPhone...");
}}
public class CWH
{
public static void main(String[] args)
{

Phone obj = new SmartPhone(); // Yes it is allowed


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed }}
Output :
Time is 8 am
Turning on SmartPhone...
Note: The data members can not achieve the run time polymorphism.
ABSTRACT CLASS
A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).Abstraction is a process of hiding
the implementation details and showing only functionality to the user. Abstraction lets you focus
on what the object does instead of how it does it. It needs to be extended and its method
implemented. It cannot be instantiated.
Example abstract class:
abstract class A{
}
abstract method:
A method that is declared as abstract and does not have implementation is known as abstract
method.
abstract void printStatus();//no body and abstract
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes.If you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
Example1:
File: TestAbstraction1.java
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}}
//In real scenario, method is called by programmer or user
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() met
hod
s.draw();
}}
Output:
drawing circle
Abstract class having constructor, data member, methods
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body 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
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Example3:
interface A
{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c()
{
System.out.println("I am c");}
}
class M extends B
{
public void a()
{
System.out.println("I am a");
}
public void b()
{
System.out.println("I am b");
}
public void d()
{
System.out.println("I am d");
}}
class Test5
{
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I am a
I am b
I am c
I am d
FINAL KEYWORD
Final keyword can be used along with variables, methods and classes.
1. final variable
2. final method
3. final class
1. Java final variable
A final variable is a variable whose value cannot be changed at anytime once assigned, it
remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60;
void increaseSpeed()
{
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel();
t.increaseSpeed();
}}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final
field Travel.SPEED cannot be assigned.The above code will give you Compile time error, as we
are trying to change the value of a final variable ‘SPEED’.
2. Java final method
When you declare a method as final, then it is called as final method. A final method
cannot be overridden.
package com.javainterviewpoint;
class Parent
{
public final void disp()
{
System.out.println("disp() method of parent class");
}
}
public class Child extends Parent
{
public void disp()
{
System.out.println("disp() method of child class");
}
public static void main(String args[])
{
Child c = new Child(); c.disp();
}
}
Output :
We will get the below error as we are overriding the disp() method of the Parent class. Exception
in thread "main" java.lang.VerifyError: class com.javainterviewpoint.Child overrides final
methoddisp.()
java.lang.ClassLoader.defineClass1(NativeMethod)atjava.lang.ClassLoader.defineClass(Unkno
wnSource)atjava.security.SecureClassLoader.defineClass(UnknownSource)at
java.net.URLClassLoader.defineClass(UnknownSource)atjava.net.URLClassLoader.access$100(
UnknownSource)atjava.net.URLClassLoader$1.run(UnknownSource)at
java.net.URLClassLoader$1.run(Unknown Source)
3. Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the below example
package com.javainterviewpoint;
final class Parent
{
}
public class Child extends Parent
{
public static void main(String args[])
{
Child c = new Child();
}}
Output :
We will get the compile time error like “The type Child cannot subclass the final class
Parent” Exception in thread "main" java.lang.Error: Unresolved compilation problem
PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can becategorized in two form, built-in package and user-defined package. There
are many built-in packages suchas 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.
Defining a Package
To create a package the programmer need to include a package command as the first
statement in aJava source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If package
statement is omitted, the class namesare put into the default package, which has no name.
Syntax:
package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called
MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called MyPackage.It is
possible to create a hierarchy of packages. The general form of a multileveled package statement
is
shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For
example, a
package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment. We cannot rename a package
withoutrenaming the directory in which the classes are stored.
Finding Packages and CLASSPATH
First, by default, the Java run-time system uses the current working directory as its starting point.
Thus, if your package is in a subdirectory of the current directory, it will be found. Second, you
can specify a directory path or paths by setting the CLASSPATH environmental variable. Third,
you can use the classpath option with java and javac to specify the path to your classes.
consider the following package specification:
package MyPack
In order for a program to find MyPack, one of three things must be true. Either the
program can be executed from a directory immediately above MyPack, or the CLASSPATH
must be set to include the path to MyPack, or the -classpath option must specify the path to
MyPack when the program is run via java.
When the second two options are used, the class path must not include MyPack, itself. It
must simply specify the path to MyPack. For example, in a Windows environment, if the path to
MyPack is
C:\MyPrograms\Java\MyPack
then the class path to MyPack is
C:\MyPrograms\Java
Example:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then, try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command.
(Alternatively, you can use one of the other two options described in the preceding section to
specify the path MyPack.) As explained, AccountBalance is now part of the package MyPack.
This means that it cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
Example:
package pck1;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd)
{
rollno = rno;
name = sname;
address = sadd;
}
public void showDetails()
{
System.out.println("Roll No :: " + rollno);
System.out.println("Name :: " + name);
System.out.println("Address :: " + address);
}
}
public class DemoPackage
{
public static void main(String ar[])
{
Student st[]=new Student[2];
st[0] = new Student (1001,"Alice", "New York");
st[1] = new Student(1002,"BOb","Washington");
st[0].showDetails();
st[1].showDetails();
}
}
There are two ways to create package directory as follows:
1. Create the folder or directory at your choice location with the same name as package
name. After compilation of copy .class (byte code file) file into this folder.
2. Compile the file with following syntax.
javac -d <target location of package> sourceFile.java
The above syntax will create the package given in the sourceFile at the <target location of
pacakge> if it is not yet created. If package already exist then only the .class (byte code file) will
be stored to the package given in sourceFile.
Steps to compile the given example code:
Compile the code with the command on the command prompt.
javac -d DemoPackage.java
1. The command will create the package at the current location with the name pck1, and
contains the file
DemoPackage.class and Student.class
2. To run write the command given below
java pckl.DemoPackage
Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully qualified
typename to run or access it.
Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Name :: Bob
Address :: Washington
INTERFACE IN JAVA
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction and multiple inheritance. 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 fields are public, static and final by
default. A class that implement interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Relationship between classes and interfaces

Example:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Example:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
Output:
drawing circle

MULTIPLE INHERITANCE IN JAVA BY INTERFACE

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Interface inheritance

A class implements interface but one interface extends another interface .

Example:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Nested Interface in Java
An interface can have another interface i.e. known as nested interface.
interface printable
{
void print();
interface MessagePrintable
{
void msg();

}}

Key points to remember about interfaces:

1) We can’t instantiate an interface in java. That means we cannot create the object of an
interface
2) Interface provides full abstraction as none of its methods have body. On the other hand
abstract class provides partial abstraction as it can have abstract and concrete(methods with
body) methods both.
3) “implements” keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be
mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else
the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
interface Try
{
int a=10; public int a=10;
public static final int a=10; final int a=10;
static int a=0;
}
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler will
throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized at the
time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-initialized.
class Sample implements Try
{
public static void main(String args[])
{
x=20; //compile time error
}
}
11) An interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.

12) A class can implement any number of interfaces.


13) If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14) A class cannot implement two interfaces that have methods with same name but different
return type.
interface A
{
public void aaa();
}
interface B
{
public int aaa();
}
class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}
15) Variable names conflicts can be resolved by interface
name. interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
Advantages of interface in java:
• Without bothering about the implementation part, we can achieve the security of
implementation
• In java, multiple inheritance is not allowed, however you can use interface to make use of
it as you can implement more than one interface.

DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE


ABSTRACT CLASS INTERFACE
Abstract class can have abstract and non- Interface can have only abstract methods. Sinc Java 8, it
abstract methods. can have default and static methods also.
Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
Abstract class can provide the Interface can't provide the implementation of abstract
implementation of interface. class.
The abstract keyword is used to declare The interface keyword is used to declareinterface.
abstract class.
An abstract class can extend another Java class An interface can extend another Java interfaceonly.
and implement multiple Java interfaces.
An abstract class can be extended using An interface class can be implemented using keyword
keyword extends. implements
A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
Example: Example:
public abstract class Shape{ public public interface Drawable{ void draw();
abstract void draw(); }
}
Unit – III

EXCEPTION HANDLING AND MULTITHREADING

Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s
Built-in Exceptions – User defined Exception. Multithreaded Programming: Java Thread
Model–Creating a Thread and Multiple Threads – Priorities – Synchronization – Inter Thread
Communication- Suspending–Resuming, and Stopping Threads –Multithreading. Wrappers –
Auto boxing.

Difference between error and exception


Errors indicate serious problems and abnormal conditions that most applicationsshould not try to
handle. Error defines problems that are not expected to be caught under normal circumstances by
our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditionsand take
necessary corrective actions. Few examples
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
o An exception (or exceptional event) is a problem that arises during the execution of a
program.
o When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
o If an exception is raised, which has not been handled by programmer then program
execution can get terminated and system prints a non user friendly error message.
Ex: Exception in thread "main" java.lang.ArithmeticException: / by zero
atExceptionDemo.main(ExceptionDemo.java:5)

Where, ExceptionDemo : The class name main :


The method name ExceptionDemo.java :
The filenamejava:5 : Line number
An exception can occur for many different reasons. Following are somescenarios where an exception
occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications orthe JVM
hasrun out of memory.

Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. Theexception class
is a subclass of the Throwable class.
Key words used in Exception handling
There are 5 keywords used in java exception handling.

A try/catch block is placed around the code that might generate an


1. try exception. Code within a try/catch block is referred to as protected code.

A catch statement involves declaring the type of exception we are trying


2. catch to catch.

A finally block of code always executes, irrespective of occurrence of an


3. finally Exception.

It is used to execute important code such as closing connection, stream


4. throw etc. throw is used to invoke an exception explicitly.

5. throws throws is used to postpone the handling of a checked exception.


Syntax : //Example-predefined Excetion - for
try //ArrayindexoutofBounds Exception
public class ExcepTest

//Protected
code
public static void main(String args[])
{ int a[] = new int[2];

catch(ExceptionType1 e1) try


{ System.out.println("Access element three :" +a[3]);

//Catch block
{ System.out.println("Exception thrown :" + e);

catch(ExceptionType2 e2)
finally

//Catch block { a[0] = 6;


System.out.println("First element value: " + a[0]);
catch(ExceptionType3 e3)
System.out.println("The finally statement is

{ executed");
//Catch block }

} }

finally }
{
Output
Exceptionthrown
//The finally block always :java.lang.ArrayIndexOutOfBoundsException:3 First
executes. element value: 6The finally statement is executed
}
Note : here array size is 2 but we are trying to access3rdelement.
Uncaught Exceptions
This small program includes an expression that intentionally causes a divide-by-zero error:
class Exc0 { public static void main(String args[]) { int d = 0; int a =42 / d; } } When the Java run-
time system detects the attempt to divide by zero, it constructs a new exception object and then
throws this exception. This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with immediately

Any exception that is not caught by your program will ultimately be processed by the default handler.
The default handler displays a string describing the exception, prints a stack trace from the point at
which the exception occurred, and terminates the program. Here is the exception generated when
this example is executed:
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

Using try and Catch


To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block. Immediately following the try block, include a catch clause that specifies
the exception type that you wish to catch. A try and its catch statement form a unit. The the following
program includes a try block and a catch clause that processes the ArithmeticException generated
by the division-by-zero error:
class Exc2 {
public static void main(String args[]) {int d, a;
try { // monitor a block of code.d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by
zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
The call to println( ) inside the try block is never executed. Once an exception isthrown, program
control transfers out of the try block into the catch block.
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed. After one catch statement executes, the others
are bypassed, and execution continues after the try/catch block.
The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {try {
int a = args.length; System.out.println("a
= " + a);int b = 42 / a;
int c[] = { 1 };c[42] =
99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Here is the output generated by running it both ways:


C:\>java MultiCatcha = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch
blocks.
C:\>java MultiCatch TestArga = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42 After try/catch
blocks.
Nested try Statements
The try statement can be nested. That is, a try statement can be inside the block
of another try. Each time a try statement is entered, the context of that exception
is pushed on the stack. If an inner try statement does not have a catch handler
for a particular exception, the stack is unwound and the next try statement’s
catch handlers are inspected for a match. This continues until one of the catch
statements succeeds, or until all of the nested try statements are exhausted. If no
catch statement matches, then the Java run-time system will handle the
exception.
// An example of nested try
statements.class NestTry {
public static void main(String
args[]) {try {
int a = args.length;
/* If no command-line args are
present, the following
statement will generate
a divide-by-zero
exception. */int b =
42 / a;
System.out.println("
a = " + a); try { //
nested try block
/* If one command-line
arg is used,then a divide-
by-zero exception
will be generated by the following
code. */ if(a==1) a = a/(a-a); //
division by zero
/* If two command-line args are used,
then generate an out-of-bounds
exception. */if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " +
e);
}
} catch(ArithmeticException e)
{ System.out.println("Divide
by 0: " + e);
}
}
}

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

THROW
it is possible for your program to throw an exception explicitly, using the throw
statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Primitive types, such as int or char, as well as non-Throwable classes, such as
String and
Object, cannot be used as exceptions. There are two ways you can obtain a
Throwable object: using a parameter in a catch clause, or creating one with the
new operator.
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block is
inspected to see if it has a catch statement that matches the type of exception. If
it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on. If no matching catch is found,
then the default exception handler halts the program and prints the stack trace
//
Demonstrate
throw. class
ThrowDemo
{ static void
demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside
demoproc."); throw e; // rethrow the
exception
}
}
public static void main(String
args[]) {try {
demoproc();
}
catch(NullPointerException
e) {
System.out.println("Recaug
ht: " + e);
}
}
}
Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

Throws
If a method is capable of causing an exception that it does not handle, it must
specify this behaviour so that callers of the method can guard themselves
against that exception. You do this by including a throws clause in the method’s
declaration. A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. This is the general
form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method
can throw.
class ThrowsDemo {
static void throwOne() throws
IllegalAccessException { System.out.println("Inside
throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String
args[]) {try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo

finally
The finally keyword is designed to address this contingency. finally creates a
block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute
whether or not an exception is thrown. If an exception is thrown, the finally
block will execute even if no catch statement matches the exception. Any time
amethod is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing file
handles and freeing up any other resources that might have been allocated at the
beginning of a method with the intent of disposing of them before returning.
The finally clause is optional.
//
Demonstra
te finally.
class
FinallyDe
mo {
// Through an exception out of the
method.static void procA() {
try {
System.out.println("inside
procA"); throw new
RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a
try block. static void
procB() {
try {
System.out.println("inside
procB");return;
} finally {
System.out.println("procB's
finally");
}
}
// Execute a try block
normally. static void
procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's
finally");
}
}
public static void main(String
args[]) {try {
procA();
} catch (Exception e) {
System.out.println("Exception
caught");
}
procB();
procC();
}
}
Here is the output generated by the preceding program:
inside procA
procA’s
finally
Exception
caught inside
procB procB’s
finally inside
procC procC’s
finally

Categories of Exceptions
Checked exceptions −A checked exception is an exception that occurs at the
compiletime, these are also called as compile time exceptions. These
exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs
at thetime of execution. These are also called as Runtime Exceptions. These
include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Common scenarios where exceptions may occur:
There are given some scenarios where unchecked exceptions can occur.They are
as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException. int a=50/0;//ArithmeticException

2) Scenario where 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());//NullPointerExc
eption

3) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index,
it would resultArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java’s Built-in Exceptions


User-defined Exceptions
All exceptions must be a child of Throwable.
If we want to write a checked exception that is automatically
enforced bythe Handle ,we need to extend the Exception class.
User defined exception needs to inherit (extends) Exception class
inorder to act as an exception.
throw keyword is used to throw such exceptions.

class MyOwnException extends Exception


{
Public MyOwnExcepation(String msg)
{
Super(msg);
}
}
class EmployeeTest
{

static void employeeAge(int age) throws


MyOwnException { if(age < 0)

throw new MyOwnException("Age can't be less than zero"); else


System.out.println("Input is valid!!");
}
public static void main(String[] args)
{
try { employeeAge(-2);
}
catch (MyOwnException e)

{
e.printStackTrace();
}
}
}

Advantages of Exception Handling


Exception handling allows us to control the normal flow of the program by using
exception handling in program.
It throws an exception whenever a calling method encounters an error providing
that the calling method takes care of that error.
It also gives us the scope of organizing and differentiating between different
error types using a separate block of codes. This is done with the help of try-
catch blocks.
Thread
A thread is a single sequential( separate ) flow of control within program. Sometimes, it
is called an execution context or light weight process.

Multithreading
Multithreading is a conceptual programming concept where a program (process) is
divided into two or more subprograms (process), which can be implemented at the same
time in parallel. A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each thread defines a
separate path of execution.

Multitasking
Executing several tasks simultaneously is called
multi-tasking. There are 2 types of multi-tasking
1. Process-based multitasking
2. Thread-based multi-tasking

1. Process-based multi-tasking
Executing various jobs together where each job is a separate independent operation,
is called process-based multi-tasking.

2. Thread-based multi-tasking
Executing several tasks simultaneously where each task is a separate
independent part of the same program is called Thread-based multitasking
and each independent part is called Thread. It is best suitable for the
programmatic level. The main goal of multi-tasking is to make or do a better
performance of the system by reducing response time
Multithreading vs Multitasking
Multithreading is to execute Multitasking is to run multiple processes
multiple threads in a on a computer concurrently.
process concurrently.
Execution
In Multithreading, the CPU switches In Multitasking, the CPU switches
between multiple threads in the same between multiple processes to complete the
process. execution.
Resource Sharing
In Multithreading, resources are shared In Multitasking, resources are shared
among multiple threads in a process. among multiple processes.

Complexity
Multithreading is light-weight and easy to Multitasking is heavy-weight and harder
create. to create.

Life Cycle of Thread


A thread can be in any of the five following states

1.Newborn State
When a thread object is created a new thread is born and said to be in Newborn state.

2.Runnable State
If a thread is in this state it means that the thread is ready for execution and waiting for the
availability of the processor. If all threads in queue are of same priority then they are given
time slots for execution in round robin fashion

3.Running State
It means that the processor has given its time to the thread for execution. A thread keeps running
until the following conditions occurs

 Thread give up its control on its own and it can happen in the following situations.
 A thread gets suspended using suspend() method which can only be revived with
resume() method.
 A thread is made to sleep for a specified period of time using sleep(time) method, where
time in milliseconds.
 A thread is made to wait for some event to occur using wait () method. In this case a
thread can be scheduled to run again using notify () method.
 A thread is pre-empted by a higher priority thread
4.Blocked State
If a thread is prevented from entering into runnable state and subsequently running state, then
a thread is said to be in Blocked state.

5.Dead State
A runnable thread enters the Dead or terminated state when it completes its task or otherwise

The Main Thread

When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main method.
This thread is called as main thread. Although the main thread is automatically created, you
can control it by obtaining a reference to it by calling currentThread() method.
Two important things to know about main thread are,

 It is the thread from which other threads will be produced.


 main thread must be always the last thread to finish execution.
EXAMPLE4.1
class MainThread

{
public static void main(String[] args)
{
Thread t1=Thread.currentThread(); t.setName("MainThread"); System.out.println("Name of
thread is "+t1);

}
}

Output:
Name of thread is Thread[MainThread,5,main]
Creation Of Thread

Thread Can Be Implemented In Two Ways


1) Implementing Runnable Interface

2) Extending Thread Class

1. Create Thread by Implementing Runnable


The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run()

EXAMPLE 4.2
public class ThreadSample implements Runnable
{

public void run()


{
try

{
for (int i = 5; i > 0; i--)

{
System.out.println("Child Thread" + i); Thread.sleep(1000);

}
}

catch (InterruptedException e)
{

System.out.println("Child interrupted");
}
System.out.println("Exiting Child Thread");
}
}

public class MainThread


{

public static void main(String[] arg)


{

ThreadSample d = new ThreadSample(); Thread s = new Thread(d);


s.start(); try

{
for (int i = 5; i > 0; i--)

{
System.out.println("Main Thread" + i); Thread.sleep(5000);
}

}
catch (InterruptedException e)

{
System.out.println("Main interrupted");

}
System.out.println("Exiting Main Thread");

}}

2. Extending Thread Class


The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which is
the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

EXAMPLE 4.2
public class ThreadSample extends Thread
{

public void run()


{
try
{
for (int i = 5; i > 0; i--)

System.out.println("Child Thread" + i); Thread.sleep(1000);


}

}
catch (InterruptedException e)

{
System.out.println("Child interrupted");

}
System.out.println("Exiting Child Thread");
}

}
public class MainThread

{
public static void main(String[] arg)

{
ThreadSample d = new ThreadSample(); d.start();

try
{

for (int i = 5; i > 0; i--)


{
System.out.println("Main Thread" + i); Thread.sleep(5000);

}
}

catch (InterruptedException e)
{
System.out.println("Main interrupted");
}
System.out.println("Exiting Main Thread");

}
}

Thread priority
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 (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defined in Thread class: public static int MIN_PRIORITY


public static int NORM_PRIORITY 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.

EXAMPLE 4.3
public class MyThread1 extends Thread { MyThread1(String s)
{

super(s);
start();

}
public void run()
{
for(int i=0;i<5;i++)

{
Thread cur=Thread.currentThread(); cur.setPriority(Thread.MAX_PRIORITY); int
p=cur.getPriority();

System.out.println("Thread Name"+Thread.currentThread().getName());
System.out.println("Thread Priority"+cur);
}

}
}
class MyThread2 extends Thread { MyThread2(String s)
{
super(s);

start();
}

public void run()


{

for(int i=0;i<5;i++)
{

Thread cur=Thread.currentThread(); cur.setPriority(Thread.MIN_PRIORITY);


System.out.println(cur.getPriority());
int p=cur.getPriority();

System.out.println("Thread Name"+Thread.currentThread().getName());
System.out.println("Thread Priority"+cur);
}

}
}

public class ThreadPriority {


public static void main(String[] args)
{

MyThread1 m1=new MyThread1("MyThread1"); MyThread2 m2=new


MyThread2("MyThread2");

}
}

Synchronizing Threads

 Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
 Java Synchronization is better option where we want to allow only one thread to access
the shared resource

General Syntax
synchronized(object)
{
//statement to be synchronized

}
Why use Synchronization

The synchronization is mainly used to

 To prevent thread interference.


 To prevent consistency problem.
Types of Synchronization
There are two types of synchronization

 Process Synchronization
 Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and
inter-thread communication.
1. Mutual Exclusive
• Synchronized method.

• Synchronized block.
• static synchronization.

2. Cooperation (Inter-thread communication in java)

Synchronized method
• If you declare any method as synchronized, it is known as synchronized method.
• Synchronized method is used to lock an object for any shared resource.

• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

Example 4.4
package Thread;
public class SynThread

{
public static void main(String args[])
{
share s = new share();
MyThread m1 = new MyThread(s, "Thread1");
MyThread m2 = new MyThread(s, "Thread2");

MyThread m3 = new MyThread(s, "Thread3");


}

}
class MyThread extends Thread

{
share s;

MyThread(share s, String str)


{

super(str); this.s = s; start();


}
public void run()

{
s.doword(Thread.currentThread().getName());

}
}

class share
{

public synchronized void doword(String str)


{

for (int i = 0; i < 5; i++)


{
System.out.println("Started:" + str); try

{
Thread.sleep(1000);

}
catch (Exception e)
{
}}}}

Synchronized block
• Synchronized block can be used to perform synchronization on any specific resource
of the method.
• Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
• If you put all the codes of the method in the synchronized block, it will work same as
the synchronized method.

Example 4.5
class Table{

void printTable(int n){ synchronized(this){//synchronized block for(int i=1;i<=5;i++){


System.out.println(n*i); try{
Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

}
}

}//end of the method


}

class MyThread1 extends Thread{ Table t;

MyThread1(Table t){ this.t=t;


}
public void run(){ t.printTable(5);

}
}

class MyThread2 extends Thread{ Table t;


MyThread2(Table t){ this.t=t;

}
public void run(){ t.printTable(100);
}
}

public class TestSynchronizedBlock1{ public static void main(String args[]){ Table obj = new
Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();

t2.start();
}

Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.

Example 4.6
In this example we are applying synchronized keyword on the static method to perform static
synchronization.

class Table{
synchronized static void printTable(int n){ for(int i=1;i<=10;i++){ System.out.println(n*i);

try{
Thread.sleep(400);

}catch(Exception e){}

}
}

}
class MyThread1 extends Thread{ public void run(){ Table.printTable(1);
}

}
class MyThread2 extends Thread{ public void run(){ Table.printTable(10);

}
}

class MyThread3 extends Thread{ public void run(){ Table.printTable(100);


}
}
class MyThread4 extends Thread{ public void run(){ Table.printTable(1000);

}
}

public class TestSynchronization4


{ public static void main(String t[])

{
MyThread1 t1=new MyThread1();

MyThread2 t2=new MyThread2();


MyThread3 t3=new MyThread3();

MyThread4 t4=new MyThread4();


t1.start();
t2.start();

t3.start();
t4.start();

}
}

Java Thread suspend() method


The suspend() method of thread class puts the thread from running to waiting state. This
method is used if you want to stop the thread execution and start it again when a certain event
occurs. This method allows a thread to temporarily cease execution. The suspended thread can
be resumed using the resume() method.

Syntax
public final void suspend()

Return
This method does not return any value.

Exception
SecurityException:
If the current thread cannot modify the thread.

Example
public class JavaSuspendExp extends Thread
{

public void run()


{

for(int i=1; i<5; i++)


{

try
{

// thread to sleep for 500 milliseconds


sleep(500);
System.out.println(Thread.currentThread().getName());

}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);

}
}

public static void main(String args[])


{

// creating three threads


JavaSuspendExp t1=new JavaSuspendExp ();

JavaSuspendExp t2=new JavaSuspendExp ();


JavaSuspendExp t3=new JavaSuspendExp ();
// call run() method

t1.start();
t2.start();

// suspend t2 thread
t2.suspend();
// call run() method
t3.start();
}

Output
Thread-0
1

Thread-2
1

Thread-0
2

Thread-2
2
Thread-0

3
Thread-2

3
Thread-0

4
Thread-2

Java Thread resume() method


The resume() method of thread class is only used with suspend() method. This method is used
to resume a thread which was suspended using suspend() method. This method allows the
suspended thread to start again.

Syntax
public final void resume()

Return value
This method does not return any value.

Exception
SecurityException:
If the current thread cannot modify the thread.
Example

public class JavaResumeExp extends Thread


{

public void run()


{

for(int i=1; i<5; i++)


{

try
{

// thread to sleep for 500 milliseconds


sleep(500);
System.out.println(Thread.currentThread().getName());

}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);

}
}

public static void main(String args[])


{

// creating three threads


JavaResumeExp t1=new JavaResumeExp ();

JavaResumeExp t2=new JavaResumeExp ();


JavaResumeExp t3=new JavaResumeExp ();
// call run() method

t1.start();
t2.start();

t2.suspend(); // suspend t2 thread


// call run() method
t3.start();
t2.resume(); // resume t2 thread
}

}
Test it Now

Output:
Thread-0

1
Thread-2

1
Thread-1

1
Thread-0
2

Thread-2
2

Thread-1
2

Thread-0
3

Thread-2
3

Thread-1
3
Thread-0

4
Thread-2

4
Thread-1
4
Java Thread stop() method
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.

Syntax
public final void stop()

public final void stop(Throwable obj)


Parameter

obj : The Throwable object to be thrown.


Return

This method does not return any value.


Exception

SecurityException:
This exception throws if the current thread cannot modify the thread.

Play Videox
Example
public class JavaStopExp extends Thread

{
public void run()

{
for(int i=1; i<5; i++)

{
try

{
// thread to sleep for 500 milliseconds

sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}

System.out.println(i);
}
}
public static void main(String args[])

{
// creating three threads

JavaStopExp t1=new JavaStopExp ();


JavaStopExp t2=new JavaStopExp ();

JavaStopExp t3=new JavaStopExp ();


// call run() method

t1.start();
t2.start();

// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");

}
}

Test it Now

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :

 Extending the Thread class


 Implementing the Runnable Interface
Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object
of our new class and call start() method to start the execution of a thread. Start() invokes the
run() method on the Thread object.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{

try {
// Displaying the thread that is running

System.out.println("Thread " + Thread.currentThread().getId() + " is running");


}

catch (Exception e) {
// Throwing an exception

System.out.println("Exception is caught");
}

}
}

// Main Class
public class Multithread {

public static void main(String[] args)


{

int n = 8; // Number of threads


for (int i = 0; i < n; i++) {

MultithreadingDemo object = new MultithreadingDemo();


object.start();

}
}
}

Output
Thread 15 is running

Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running

Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

// Java code for thread creation by implementing


// the Runnable Interface

class MultithreadingDemo implements Runnable {


public void run()

{
try {

// Displaying the thread that is running


System.out.println(
"Thread " + Thread.currentThread().getId()

+ " is running");
}

catch (Exception e) {
// Throwing an exception

System.out.println("Exception is caught");
}

}
}

// Main Class
class Multithread {
public static void main(String[] args)

{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object

= new Thread(new MultithreadingDemo());


object.start();

}
}

}
Output

Thread 13 is running
Thread 11 is running

Thread 12 is running
Thread 15 is running
Thread 14 is running

Thread 18 is running
Thread 17 is running

Thread 16 is running

Thread Class vs Runnable Interface


If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
Using runnable will give you an object that can be shared amongst multiple threads.
This article is contributed by Mehak Narang. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value,
it will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.

Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.

java.util package: The java.util package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float float
Double double

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known
as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float
to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects

//Autoboxing example of int to Integer


public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer

int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly

Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally


System.out.println(a+" "+i+" "+j);

}}
Output:

20 20 20

INTER-THREAD COMMUNICATION IN JAVA


Inter-thread communication in Java is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.
Note: Inter-thread communication is also known as Cooperation in Java.

The process of testing a condition repeatedly till it becomes true is known as polling. Polling
is usually implemented with the help of loops to check whether a particular condition is true or
not. If it is true, a certain action is taken. This wastes many CPU cycles and makes the
implementation inefficient.
For example, in a classic queuing problem where one thread is producing data, and the other is
consuming it.
How Java multi-threading tackles this problem?

To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these
methods belong to object class as final so that all classes have them. They must be used within
a synchronized block only.
wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().

notify(): It wakes up one single thread called wait() on the same object. It should be noted that
calling notify() does not give up a lock on a resource.
notifyAll(): It wakes up all the threads called wait() on the same object.
import java.util.Scanner;

public class threadexample

{
public static void main(String[] args) throws InterruptedException
{

final PC pc = new PC();

// Create a thread object that calls pc.produce()


Thread t1 = new Thread(new Runnable()

{
@Override

public void run()


{

try
{
pc.produce();

}
catch(InterruptedException e)
{
e.printStackTrace();

}
}

});

// Create another thread object that calls


// pc.consume()

Thread t2 = new Thread(new Runnable()


{

@Override
public void run()
{

try
{

pc.consume();
}

catch(InterruptedException e)
{

e.printStackTrace();
}

}
});

// Start both threads


t1.start();

t2.start();

// t1 finishes before t2
t1.join();
t2.join();

// PC (Produce Consumer) class with produce() and


// consume() methods.

public static class PC


{

// Prints a string and waits for consume()


public void produce()throws InterruptedException

{
// synchronized block ensures only one thread
// running at a time.

synchronized(this)
{

System.out.println("producer thread running");

// releases the lock on shared resource


wait();

// and waits till some other method invokes notify().

System.out.println("Resumed");
}
}

// Sleeps for some time and waits for a key press. After key

// is pressed, it notifies produce().


public void consume()throws InterruptedException
{
// this makes the produce thread to run first.
Thread.sleep(1000);

Scanner s = new Scanner(System.in);

// synchronized block ensures only one thread


// running at a time.

synchronized(this)
{

System.out.println("Waiting for return key.");


s.nextLine();

System.out.println("Return key pressed");

// notifies the produce thread that it

// can wake up.


notify();

// Sleep

Thread.sleep(2000);
}

}
}

}
Output
producer thread running

Waiting for return key.


Return key pressed

Resumed
UNIT IV - I/O, GENERICS, STRING HANDLING
I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic
Programming – Generic classes – Generic Methods – Bounded Types – Restrictions and Limitations.
Strings: Basic String class, methods and String Buffer Class.
IO IN JAVA
Java I/O (Input and Output) is used to process the input and produce the output based on the input. Java uses
the concept of stream to make I/O operation fast. The java.io package contains all the classes required for
input and output operations.
Stream
A stream can be defined as a sequence of data. there are two kinds of Streams
• InputStream: The InputStream is used to read data from a source.
• OutputStream: The OutputStream is used for writing data to a destination.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytesFileInputStream, FileOutputStream.
Character Streams
Java Character streams are used to perform input and output for 16-bit unicode.FileReader ,FileWriter
Standard Streams

• Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.

• Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as System.out.

• Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and
represented as System.err.
Classification of Stream Class
Byte Stream Classes:

ByteStream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Since the streams are
unidirectional, they can transmit bytes in only one direction and therefore, Java provides two
kinds of byte stream classes: InputStream class andOutputStream class.
Input Stream Classes
Input stream classes that are used to read 8-bit bytes include a super class known as
InputStream and number of subclasses for supporting various input- related functions.
Hierarchy of Input Stream Classes
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:-
• Reading Bytes
• Closing Streams
• Marking position in Streams
• Skipping ahead in streams

• Finding the number of bytes in stream.

The following are the InputStream methods:

The DataInput interface contains the following methods

OutputStream Class
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:
• Writing Bytes
• Closing Streams
• Flushing Streams
Hierarchy of OutputStream Classes
OutputStream Methods

Character Stream Vs Byte Stream in JavaI/O


Stream
A stream is a method to sequentially access a file. I/O Stream means an input source or output
destination representing different types of sources e.g. disk files.The java.io package provides
classes that allow you to convert between Unicode character streams and byte streams of non-
Unicode text.

Stream: A sequence of data.


Input Stream: reads data from source.

Output Stream: writes data to destination.

Character Stream

In Java, characters are stored using Unicode conventions (Refer this for details). Character stream
automatically allows us to read/write data character by character. For example FileReader and
FileWriter are character streams used to read from source andwrite to destination.

// Java Program illustrating that we can read a file in


// a human readable format using FileReader
importjava.io.*;
// Accessing FileReader, FileWriter, IOExceptionpublicclassGfG
{
publicstaticvoidmain(String[] args) throwsIOException
{
FileReader sourceStream = null;try
{
sourceStream = newFileReader("test.txt");

// Reading sourcefile and writing content to


// target file character by character.
inttemp;
while((temp = sourceStream.read()) != -1)
System.out.println((char)temp);
}
finally
{
// Closing stream as no longer in use
if(sourceStream != null)
sourceStream.close();
}
}
}
Reading and Writing Files:
A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.
TheInputStream is used to read data from a source and the OutputStream is used for
writing data to a destination.The two important streams are FileInputStream
and FileOutputStream
Here is a hierarchy of classes to deal with Input and Output streams.
FileInputStream
This stream is used for reading data from the files. Objects can be created usingthe
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input streamobject to
read the file –
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object toread the file.
First we create a file object using File() method as follows −
File f = new File("C:/java/hello");

InputStream f= new FileInputStream(f);


importjava.io.*;
publicclassBStream
{
Public static void main(String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;try
{
sourceStream = newFileInputStream("sorcefile.txt");
targetStream = newFileOutputStream ("targetfile.txt");

// Reading source file and writing content to target


// file byte by byte
int temp;
while((temp = sourceStream.read()) != -1)targetStream.write((byte)temp);
}
finally
{
if(sourceStream != null)sourceStream.close();
if(targetStream != null) targetStream.close();
}
}}
Final Keyword In Java – Final variable, Method and Class
final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1) final variable
final variables are nothing but constants. We cannot change the value of a finalvariable once it is
initialized. Lets have a look at the below code:
classDemo{
finalint MAX_VALUE=99;void
myMethod(){
MAX_VALUE=101;
}
Public static void main(String args[]){Demo
obj=newDemo();
obj.myMethod();
}}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assignedat
beginnersbook.com.Demo.myMethod(Details.java:6) at
beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the value of a final
variable “MAX_VALUE”.
2) final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.Example:
class XYZ
{
finalvoid demo()

System.out.println("XYZ Class Method");


}}
class ABC extends XYZ{void
demo(){
System.out.println("ABC Class Method");
}
public static void main(String args[]){ABC
obj=new ABC(); obj.demo();
}}

The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: This program would run
fine as we are not overriding the final method. That shows that final methods are inherited but they
are not eligible for overriding.
class XYZ
{
Final void demo(){
System.out.println("XYZ Class Method");
}}
class ABC extends XYZ{
public static void main(String args[]){ABC
obj=new ABC(); obj.demo();
}}

Output:
XYZ ClassMethod
final class
We cannot extend a final class. Consider the below example:
finalclass XYZ{
}
class ABC extends XYZ
{
void demo()
{
System.out.println("My Method");
}
Public static void main(String args[]){ABC
obj=new ABC(); obj.demo();
}}
Output:
The type ABC cannot subclass the final class XYZ
Generic Programming
Generic programming enables the programmer to create classes,interfaces and methods that
automatically works with all types of data(Integer, String, Float etc). It has expanded the ability to
reuse the code safely and easily.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1. Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to
store other objects.
2. Type casting is not required: There is no need to typecast the object.
3. Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.
Generic class
• A class that can refer to any type is known as generic class.
• Generic class declaration defines set of parameterized type one for each
possible invocation of the type parameters

Example 4.10
class TwoGen<T, V>
{
T ob1; V ob2;
TwoGen(T o1, V o2)
{
ob1 = o1; ob2 = o2;
}
void showTypes() {
System.out.println("Type of T is " + ob1.getClass().getName());
System.out.println("Type of V is " + ob2.getClass().getName());
}
T getob1()
{

return ob1;
}

V getob2()
{
return ob2;
}
}
public class MainClass
{
public static void main(String args[])
{
TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88,"Generics");
tgObj.showTypes();
int v = tgObj.getob1(); System.out.println("value: " + v);
String str = tgObj.getob2(); System.out.println("value: " + str);
}
}
Generic Method
Like generic class, we can create generic method that can accept any type of argument. public
class TestGenerics4{
public static < E > void printArray(E[] elements)
{ for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A'};
System.out.println( "Printing Integer Array"
); printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}}
Bounded type
The type parameters could be replaced by any class type. This is fine for many purposes, but
sometimes it is useful to limit the types that can be passed to a type parameter
Syntax :
<T extends superclass>
Example 4.11
class Stats<T extends Number> { T[] nums;

Stats(T[] o) { nums = o; }
double average() { double sum = 0.0;
for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); return sum
/ nums.length;
}
}
public class MainClass {
public static void main(String args[]) { Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums); double w = dob.average();
System.out.println("dob average is " + w);
}}
Restrictions on Generics
To use Java generics effectively, you must consider the following restrictions:

Cannot Instantiate Generic Types with Primitive Types


Cannot Create Instances of Type Parameters
Cannot Declare Static Fields Whose Types are Type Parameters
Cannot Use Casts or instanceof With Parameterized Types
Cannot Create Arrays of Parameterized Types
Cannot Create, Catch, or Throw Objects of Parameterized Types
Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase
to the Same Raw Type
Java String
String is basically an object that represents sequence of char values. An array of characters
works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The
java.lang.String class implements Serializable, Comparable and CharSequence interface50

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by
using these three classes.
String in Java
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.

2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

Java String Example


StringExample.java

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:

Java
String
example
The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)

5 String substring(int beginIndex) It returns substring for given begin index.

6 String substring(int beginIndex, int It returns substring for given begin index and end
endIndex) index.

7 boolean contains(CharSequence s) It returns true or false after matching the sequence


of char value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the given
object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified char
value.

14 String replace(CharSequence old, It replaces all occurrences of the specified


CharSequence new) CharSequence.

15 static String equalsIgnoreCase(String It compares another string. It doesn't check case.


another)

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting
with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int It returns the specified substring index starting with
fromIndex) given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using specified


locale.
25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using specified


locale.

27 String trim() It removes beginning and ending spaces of this


string.

28 static String valueOf(int value) It converts given type into string. It is an


overloaded method.

Java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as
length.
Important methods of StringBuffer class

Modifier and Type Method Description

public synchronized append(String s) It is used to append the specified string with


StringBuffer this string. The append() method is
overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.

public synchronized insert(int offset, It is used to insert the specified string with
StringBuffer String s) this string at the specified position. The
insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public synchronized replace(int It is used to replace the string from specified


StringBuffer startIndex, int startIndex and endIndex.
endIndex, String
str)

public synchronized delete(int It is used to delete the string from specified


StringBuffer startIndex, int startIndex and endIndex.
endIndex)

public synchronized reverse() is used to reverse the string.


StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal


minimumCapacity) to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the string i.e.
total number of characters.

public String substring(int It is used to return the substring from the


beginIndex) specified beginIndex.

public String substring(int It is used to return the substring from the


beginIndex, int specified beginIndex and endIndex.
endIndex)

Mutable String
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method


The append() method concatenates the given argument with this String.

StringBufferExample.java

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:

Hello Java

2) StringBuffer insert() Method


The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:

HJavaello

3) StringBuffer replace() Method


The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:

HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.

StringBufferExample4.java

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:

Hlo

5) StringBuffer reverse() Method


The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:

olleH

The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.

StringBufferExample6.java

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:

16
16
34
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

StringBufferExample7.java

class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:

16
16
34
34
70
Unit-V

JavaFX Events and Conctrols : Event Basics –Handling Key and Mouse Events.
Controls: Checkbox, Toggle Button –Radio Button- List View- Combo box- Choice
Box –Text Controls- Scroll pane. Layouts- Flow Pane – Hbox and VBox- Border pane
– Grid Pane, Menus-Basics –Menu-Menu bars -Menu item

JavaFx Event handling:


Event handling is an important activity for the programs which use graphical
user interface. The event handling mechanism improves the interactivity of the
application program.
Events are included in the following packages:
1. java.util
2. java.awt
3. java.awt.event

3.6.1: BASICS OF EVENT HANDLING:


Event: Event means any activity that interrupts the current execution sequence. For
example, when the user clicks mouse or press some key from a keyboard during some
processing, then it generates an event.

DELEGATION EVENT MODEL:


Delegation Event Model is the modern approach to handle the event. It defines the
standard and consistent mechanism to generate and process events.
Its concept is quite simple: a source generates an event and sends it to one or more
listeners. Listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.

The Delegation Event Model is based on the concept of “Event source” and “Event
Listeners”
Any object that is interested in receiving messages (or events) is called an Event Listener.
Any object that generates the messages (or Events) is called an Event Source.

COMPONENTS OF DELEGATION EVENT MODEL:


There are three major components in the delegation event model:
1. Events
2. Event Sources
3. Event Listeners

1. Events
An event is an object that describes a state change in a source. Some of the
activities that cause events to be generated are pressing a button, entering a character via
the keyboard, selecting an item in a list, and clicking the mouse.

2. Event Sources
A Event Source is an object that generates an event. Sources may generate more
than one type of event. A source must register listeners in order for the listeners to re ceive
notifications about a specific type of event.

Event Source Description


Button Generates action events when the button is pressed.
Checkbox Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates
item

Mouse Generates Mouse events when Mouse input occurs.


Keyboard Generates Key events when keyboard input occurs.

3. Event Listeners

Listener is an object that is notified when an event occurs. It has two major requirements:
1. It must have been registered with one or more sources to receive notifications abo ut
specific types of events.
2. It must implement methods to receive and process these notifications.

The package java.awt.event defines several types of events that are generated by various
user interface elements.

WORKING OF EVENT HANDLING:


The following steps give an overview of how event handling in the AWT works:
1. A listener object is an instance of a class that implements a special interface
called (naturally enough) a listener interface.
2. An event source is an object that can register listener objects and send them
event objects.
3. The event source sends out event objects to all registered listeners when that
event occurs.
4. The listener objects will then use the information in the event object to
determine their reaction to the event.

You register the listener object with the source object by using lines of code that follow
the model:
eventSourceObject.addEventListener(eventListenerObject);
Example:
Button b1=new Button(―OK‖);
B1.addActionListener(this);
The listener object is notified whenever an ―action event‖ occurs on the button (when
the button is clicked).
Advantages of Event Delegation Model:
1. In event delegation model, the events are handled using objects. This allows a clear
separation between the usage of the components and the design.
2. It accelerates the performance of the application in which multiple events are used.
3.6.2: AWT EVENT HIERARCHY:
 all events descending from
Event handling in Java is object oriented, with

EventObject class in the java.util.package.

The 
EventObject class has a subclass AWTEvent, which is the parent of all AWT event
classes.

3.6.2.1: EVENT CLASSES:
Event classes are the classes responsible for handling events in the event handling
mechanism.

 EventObject class:

 The EventObject class is at the top of the event class hierarchy. 

It belongs to the java.util package and other event classes are present in java.awt.event
 package.

Constructor: 
o EventObject(Object source) – source is the object that generate an event

 Methods:
o Object getSource() – returns the source of the event.
o Stirng toString() - returns the string equivalent of the event.

 
AWT Event Classes:
 
 AWT Event is the subclass of EventObject class.
 
 The subclasses of AWTEvent class can be categorized into two:
1. Semantic Events
2. Low-level Events
1. Semantic Events:
A semantic event is one that expresses what the user is doing, such as ―clicking
the button‖. The following event classes are semantic event classes:
1. ActionEvent
2. AdjustmentEvent
3. ItemEvent
4. TextEvent
2. Low-level Events:
Low-level events are those that makes the semantic events possible. For example, a
semantic event ―button click‖ involves series of low level events such as mouse down,
mouse moves and a mouse up.
The following event classes are Low-level event classes:
1. ComponentEvent
2. ContainerEvent
3. FocusEvent
4. KeyEvent
5. MouseEvent
6. WindowEvent

The following table shows the description of various event classes:


Event
Event classes Description Source
ActionEvent Generated when a button is pressed, a Button, JButton
list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scrollbar is Scrollbar, JScrollbar
manipulated
ComponentEvent Generated when a component is hidden, Component
moved, resized or becomes visible.
ContainerEvent Generated when a component is added Component
to or removed from a container
FocusEvent Generated when a component gains or Component
loses keyboard focus
ItemEvent Generated when a checkbox or list item List, JList
is clicked; also occurs when a choice Choice, Checkbox
selection is made or a checkable menu
item is selected or deselected.
KeyEvent Generated when the input is received keyboard
from the keyboard
MouseEvent Generated when the mouse is dragged, Mouse
moved, clicked, pressed or released;
also generated when the mouse enters
or exits a component.
MouseWheelEvent Generated when the mouse wheel is Mouse
moved
TextField or
TextEvent Generated when the value of the text TextArea
field or text area is changed.
WindowEvent Generated when a window is activated, Window
closed, deactivated.

3.6.2.2: EVENT LISTENERS:

The task of handling an event is carried out by Event Listeners. When an event
occurs,
1. An event object of the appropriate type is created.
2. This object is then passed to a Listener.
3. A listener must implement the interface that has the methods for event
handling.
Source Event Class Class Methods Listener Interface Interface Methods
Button ActionEvent String ActionListener actionPerformed(ActionEvent ae)
getActionCommand( )

List, ItemEvent Object getItem( ) ItemListener itemStateChanged(ItemEvent ie)


Choice, ItemSelectable
Checkbox getItemSelectable( )

Keyboard KeyEvent char getKeyChar( ) KeyListener keyPressed(KeyEvent ke)


int getKeyCode( ) keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)

Mouse MouseEvent int getX( ) MouseListener mouseClicked(MouseEvent me)


int getY( ) mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)

MouseMotionListener mouseDragged(MouseEvent me)


mouseMoved(MouseEvent me)

Scrollbar AdjustmentEventAdjustable getAdjustable() AdjustmentListener adjustmentValueChanged(AdjustmentEve


int getAdjustmentType() nt ae)
int getValue()

Component FocusEvent Boolean isTemporary() FocusListener focusGained(FocusEvent fe)


focusLost(FocusEvent fe)

TextField TextEvent -- TextListener textValueChanged(TextEvent)


and
TextArea

Window WindowEvent Window getWindow() WindowListener windowActivated(WindowEvent we)


int getOldState()
windowClosed(WindowEvent we)
int getNewState()
windowClosing(WindowEvent we)
windowDeactivated(WindowEvent we)
windowDeiconified(WindowEvent we)
windowIconified(WindowEvent we)
windowOpened(WindowEvent we)

Component ComponentEventComponent getComponent() ComponentListener componentHidden(ComponentEvent ce)


componentMoved(ComponentEvent ce)
componentResized(ComponentEvent ce)
componentShown(ComponentEvent ce)

Container ContainerEvent Component getChild() ContainerListener componentAdded(ContainerEvent ce)


Container getContainer()
componentRemoved(ContainerEvent ce)

 
Registering Event Listeners: Steps:
1. Either create a class that implements a listener interface or extend a class that
implements a listener interface.
Example:
public class MyClass implements ActionListener {
----}
2. Register your listener with the source.
Example:
Component.addActionListener(instanceOfMyClass)
3. Implement the user actions by overriding the methods of listener interface
Example:
public void actionPerformed(ActionEvent e)
{
---
// code that reacts to the action or event
--
}
Example: Program to toggle the background color on every click of button
import java.awt.*;
import java.awt.event.*;
/* class implementing ActionListener interface and it
must override all the methods of the listener interface */
public class ToggleButton extends Frame implements
ActionListener {
boolean flag=true;
Button b1;
ToggleButton(String s)
{
super(s);
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
b1=new Button("change color");
add(b1); // placing the button control
b1.addActionListener(this); // b1=event source, registering event listener

}
public void actionPerformed(ActionEvent ae) // code to handle the
event {
String str=ae.getActionCommand();
if(str.equals("change color"))
{
flag=!flag;
repaint();
}
}
public void paint(Graphics g)
{
if(flag)
setBackground(Color.red);
else
setBackground(Color.yellow);
}
public static void main(String[] arg)
{
ToggleButton T=new ToggleButton("Handling Button Event");
}
}

Output:
3.6.3: HANDLIND MOUSE, KEYBOARD AND WINDOW
EVENTS HANDLING MOUSE EVENTS:

 Mouse  pressed or
events are generated when the mouse is dragged, moved, clicked,
released; also generated when the mouse enters or exits a component.

To handle Mouse events, class must implement the MouseListener &
 listener & mouse motion listener
MouseMotionListener interface. Register mouse
to receive notifications about MouseEvents.
Syntax:
addMouseListener(this);
addMouseMotionListener(this);

Description:
Source: Mouse Event
Class: java.awt.event.MouseEvent
Listener Interface: java.awt.event.MouseListener
java.awt.event.MouseMotionListener

Example:
The following program demonstrates Mouse event handling. When user drag the
mouse it draws a line along the motion path.

import java.awt.*;
import java.awt.event.*;
public class MouseHandler extends Frame
implements MouseListener,MouseMotionListener
{

int x1,y1,x2,y2;
String str;
MouseHandler(String s)
{
super(s);
setSize(300,300);
setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me)
{
x1=x2;y1=y2;
x2=me.getX();
y2=me.getY();
Graphics g=this.getGraphics();
g.drawLine(x1,y1,x2,y2);
}
public void mouseMoved(MouseEvent me)
{
x1=x2;y1=y2;
x2=me.getX();

y2=me.getY();
str="Mouse Moving at ("+x2+","+y2+")";
repaint();
}
public void mouseClicked(MouseEvent me)
{
x2=me.getX();
y2=me.getY();
str="Mouse Clicked at ("+x2+","+y2+")";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x2=200;y2=100;
str="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x2=200;y2=100;
str="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x1=x2=me.getX();
x1=y2=me.getY();
}
public void mouseReleased(MouseEvent me)
{
str="Mouse Released at ("+x2+","+y2+")";
Graphics g=this.getGraphics();
g.drawString(str,x2,y2);
}
public void paint(Graphics g)
{
g.drawString(str,x2,y2);
}

public static void main(String arg[])


{
MouseHandler ob=new MouseHandler("Mouse event Demo");

}
}

Program Explanation:
In the above program, the MouseHanlder class extends Frame and
implements both MouseListener and MouseMotionListener interfaces to handle
mouse events. These two interfaces contain methods to receive and process the
various types of mouse events. Here, ―me‖ is a reference to the object receiving
mouse events. The Frame then implements all the methods defined by the
MouseListener and MouseMotionListener interfaces. These are the event handlers
for the various mouse events. Each method handles its event and then returns.

Output:
HANDLING KEYBOARD EVENTS:

 
Keyboard events are generated when the input is received from the keyboard

To handle keyboard events, class must implement the KeyListener interface. Register
key listener to receive notifications about KeyEvents.
Syntax:
addKeyListener(this);

Description:
Source: KeyBoard
Event Class: java.awt.event.KeyEvent
Listener Interface: java.awt.event.KeyListener

Example:

The following program demonstrates keyboard input. When program receives keystrokes,
identifies the key and perform the corresponding actions specified by the program.

import java.awt.*;
import java.awt.event.*;
public class KeyboardHandler extends Frame implements
KeyListener {
int x=20,y=20;
String msg="";
KeyboardHandler(String s)
{
super(s);
setSize(300,300);
setVisible(true);
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
Font f=new Font("Monotype Corsiva",Font.BOLD,15);
msg+=ke.getKeyChar();
setFont(f);
}
public void keyTyped(KeyEvent ke){ }
public void keyReleased(KeyEvent ke)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,100);
}
public static void main(String arg[])
{
KeyboardHandler ob=new KeyboardHandler("Keyboard event Demo");
}
}

Output:

Program Explanation:
In the above program, the class extends Frame class and implements
KeyListener to handle the event generated through keyboard. When a key is pressed,
a KEY_PRESSED event is generated. This results in a call to the keyPressed() event
handler. This handler gets the key typed by the user through getKeyChar() method
and collects the character in the string variable msg. When the key is released, a
KEY_RELEASED event is generated. The keyReleased() event handler calls the
repaint() method to display the message on the frame window.

HANDLING WINDOW EVENTS:



 Window events are generated when a window is activated closed, deactivated. 

 To handle window events, class must implement the WindowListener interface. 

Register Window listener to receive notifications about WindowEvents. 
Syntax:
addWindowListener(this);
Description:
Source: Window (Applet or Frame)
Event Class: java.awt.event.WindowEvent
Listener Interface: java.awt.event.WindowListener

Example:

import java.awt.*;
import java.awt.event.*;
public class WindowHandler extends Frame implements
WindowListener {
String msg="";
WindowHandler(String s)
{
setSize(500,500);
setVisible(true);
addWindowListener(this);
}
public void windowClosing(WindowEvent we)
{
System.out.println("Window Closed");
System.exit(0);
}
public void windowClosed(WindowEvent we)
{System.out.println("Window Closed"); }

public void windowOpened(WindowEvent we)


{
System.out.println("Window Opened");
}
public void windowActivated(WindowEvent we)
{
msg="Window is activated";
repaint();
System.out.println("Window Activated");
}
public void windowDeactivated(WindowEvent we)
{
System.out.println("Window Deactivated");
}
public void windowIconified(WindowEvent we)
{
System.out.println("Window Iconified");
}
public void windowDeiconified(WindowEvent we)
{
System.out.println("Window DeIconified");
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
public static void main(String[] args)
{
WindowHandler obj=new WindowHandler("Window Event Demo");

}
}
Output:
Window Activated
Window Deactivated
Window Activated
Window Iconified
Window Deactivated
Window DeIconified
Window Activated
Window Deactivated
Window Activated
Window Closed

Frame

Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By
default, a frame has a size of 0 × 0 pixels and it is not visible.
Frames are examples of containers. It can contain other user interface components such as
buttons and text fields.

java.awt
Class hierarchy for Frame Component

Container

Window

Frame
Component & Window class Methods:
java.awt.Component

 void setVisible(boolean b) - shows or hides the component depending on


whether b is true or false.

 void setSize(int width, int height) - resizes the component to the specified
width and height.

 void setBounds(int x, int y, int width, int height) - moves and resizes this
component. The location of the top-left corner is given by x and y, and the
 new size is given by the width and height parameters.
  void setBackground(java.awt.Color) – set Background color to the window.
  void setForeground(java.awt.Color)- set Foreground color to the window.
 void repaint() - causes a repaint of the component ―as soon as possible.

java.awt.Window
 void setTitle(String s) - sets the text in the title bar for the frame to the
string s.

Frame’s constructors: (swing equivalent of Frame is JFrame)


  Frame( ) - creates a standard window that does not contain a title.
 Frame(String title) - creates a window with the title specified by title

Methods of Frame class:


 void setSize(int newWidth, int newHeight) - method is used to set the
 dimensions of the window. The dimensions are specified in terms of pixels.
 void setVisible(boolean visibleFlag)- The component is visible if the
 argument to this method is true. Otherwise, it is hidden.
 void setTitle(String newTitle)- change the title in a frame window.

Creating a Frame Window

Method 1: In main() method

  Create an instance of a Frame class.


  Frame f=new Frame(― frame name‖);
  Set the frame size
 
 f.setSize(500,500);
  Make the frame visible

 
f.setVisible(true);
Example:
The following java program creates a frame with the dimension as 600 x 400 and
makes it visible in the screen. Import java.awt package because Frame class is
available in that package.

import java.awt.*;
public class Demo{
public static void main(String arg[])
{
Frame f=new
Frame("Demo");
f.setSize(600,400);
f.setVisible(true);

}
}

Method :2
  Create a subclass of Frame.
 
In the Subclass constructor
o Change the frame title by calling superclass [Frame] constructor
using super(String) method call.
o Set the size of the window explicitly by calling the setSize( ) method.
o Make the frame visible by calling setVisible() method.

  In main() method
o Create an instance of subclass. Example:

The following java program creates a frame with the dimension as 600 x 400 and
makes it visible in the screen. Import java.awt package because Frame class is
available in that package.

import java.awt.*;
public class Demo extends Frame
{
Demo(String s)
{
super(s);
setSize(600,400);
setVisible(true);
}
public static void main(String arg[])
{
Demo ob=new Demo("Demo");
}
}

3.2: Displaying Information in a Component:

In Java, frames are really designed to be containers, called panels, for components
such as Menubar and other user interface elements to be added on to it.

The JFrame with four panes are layered as shown below:

3.2.1: Add Components to the the ContentPane:


When designing a frame, we can add components into the content pane,
using code such as the following:
Container contentPane = frame.getContentPane();
Component c = . . .;
contentPane.add(c);

getContentPane() – This method is available in javax.swing.JFrame package.


It returns the ContentPane object for the frmae.

3.2.2: Draw a component on the Panel:



  to add a single component to the frame onto which we will draw
In case, we want
our message.

  JComponent and
To draw on a component, you define a class that extends
override the paintComponent() method in that class.

The paintComponent method takes one parameter of type Graphics. A
Graphics object remembers a collection of settings for drawing images and
text, such as the font you set or the current color. All drawing in Java must go
through a Graphics object. It has methods that draw patterns, images, and text.

class MyComponent extends JComponent


{
public void paintComponent(Graphics g)
{
code for drawing
}
}
 
 The alternative for paintComponent() method:
 void paint(Graphics G) – this method is called whenever the window has
 to be painted with the specified component.
 void repaint() – causes the repaint of the component

 void repaint(int x, int y, int width, int height) – causes the repaint of a
part of the component

3.2.3: Displaying Text:


We can display text or string directly on to the Frame window by using the
drawstring() method available in java.awt.Graphics package.
Syntax:
void drawstring(String str, int x, int y) - this method renders the specified

string at the specified x and y coordinate position.

Example:

import java.awt.*;
import javax.swing.*;

public class DrawStringDemo


{
public static void main(String[] args)
{
JFrame frame=new JFrame("Draw String Dempo");
Container contentPane=frame.getContentPane();
contentPane.add(new HelloWorldPanel());
frame.setSize(200,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class HelloWorldPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setFont(new Font("Arial Black", Font.BOLD,15));
g.drawString("Java Demo for drawString()",30,75);

}
}
Example:
import java.awt.*;
import javax.swing.*;
class DemoFrame extends JFrame{
DemoFrame()
{
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ ON_CLOSE);
// get screen dimensions
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
int screenHeight=screenSize.height;
int screenWidth=screenSize.width;

// center frame in screen setSize(screenWidth/2,


screenHeight/2);
setLocation(screenWidth/4,screenHeight/4);

//set frame icon and title


setTitle("My First Frame");
Image img=kit.getImage("icon.gif");
setIconImage(img);
}
}
public class FrameDemo{
public static void main(String[] args) {
// TODO code application logic here
DemoFrame fr=new DemoFrame();
}
Output:
3.3: AWT COMPONENTS:
There are various graphical components that can be placed on the frame. These
 Classes have the corresponding methods. 
All components are subclass of Component class. Components allow the user to
interact with application. A layout manager arranges components within a container
(Frame/Applet/Panel).
Adding and Removing Controls”
 add(Component compObj)- add components to the conatainer. Once it is
added, it will automatically be visible whenever its parent window is displayed.
 Here, compObj is an instance of the control that you want to add.
  void remove(Component obj)- remove a control from a window
 removeAll( )- remove all controls from a window
Component Constructor Methods
Label Label( ) void setText(String str)
Label(String str) String getText( )
Label(String str, int how)
Button Button( ) void setLabel(String str)
Button(String str) String getLabel( )
List List( ) void add(String name)
List(int numRows) void add(String name, int
List(int numRows, boolean multipleSelect) index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )

Choice Choice( ) void add(String name)


String getSelectedItem( )
int getSelectedIndex( )
Checkbox Checkbox( ) boolean getState( )
Checkbox(String str) Checkbox(String str, boolean void setState(boolean on)
on) String getLabel( )
Checkbox(String str, boolean on, CheckboxGroup void setLabel(String str)
cbGroup)
Checkbox(String str, CheckboxGroup cbGroup,
boolean on)

TextField TextField( ) String getText( )


TextField(int numChars) void setText(String str)
TextField(String str) void setEditable(boolean
TextField(String str, int numChars) canEdit)

TextArea TextArea( ) void append(String str)


TextArea(int numLines, int numChars) void insert(String str, int
TextArea(String str) index)
TextArea(String str, int numLines, int numChars)

Scrollbars Scrollbar( ) int getMinimum( )


Scrollbar(int style) int getMaximum( )
Scrollbar(int style, int initialValue, int thumbSize, int void setValues(int initialValue, int
min, int max) thumbSize, int min, int max)

AWT supports the following types of controls:


1. Labels
2. Push buttons
3. Check Boxes
4. Choice Lists
5. Lists
6. Scroll bars
7. Text Components

1: Label:
The easiest control to use is a Label. 

A label is an object of type Label, and it contains string to display. 
Labels
 are passive controls that do not support any interaction with the user.
Constructors:

1. Label() - creates a blank label
2. Label(Stirng str) - creates a label that contains a string
3. label(String str, int style) - creates a label with specified string and
alignment. The value of style must be one of these three constants:
Label.LEFT, Label.RIGHT or Label.CENTER
Example:

import java.awt.*;
public class Use_Label {
public static void main(String[] args) {
Frame fr=new Frame(" This program is for displaying Label");
fr.setSize(400,200);
fr.setLayout(new FlowLayout());
fr.setVisible(true);
Label l1=new Label("OK");
Label l2=new Label("CANCEL");
fr.add(l1);
fr.add(l2); } }

2. Buttons:
  Most widely used control is Button or Push Buttons.
 
A Button is a component that contains a label and that generates an event when it is pressed.
Constructors:
1. Button() - creates an empty Button
2. Button(String str) - creates a button that contains str as label.

Example:

import java.awt.*;
public class Use_Button
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Buttons");
fr.setSize(400,200);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Button B1=new Button();
B1.setLabel("Ok");
Button B2=new Button("CANCEL");
Button button[]=new Button[3];
String colors[]={"Red","Blue","Green"};
for(int i=0;i<button.length;i++)
{
button[i]=new Button(""+colors[i]);
fr.add(button[i]);
}
fr.add(B1);
fr.add(B2);
}
}

3. Check Boxes:
  A check box is a control that is used to turn an option on or off.
 
 It consists of a small box that can either contain a check mark or not.

 the box
There is a label associated with each check box that describes what option
represents. We can change the state of the check box by clicking on it.
Constructors:
1. Checkbox() - creates a check box with blank label
2. Checkbox(String str) - creates a check box with specified string
3. Checkbox(String str, boolean on) - creates a checkbox with initial state as On
and with the specified string.
Example:
import java.awt.*;
public class Use_Checkbox
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Check Boxes");
fr.setLayout(new FlowLayout());
fr.setSize(500,300);
fr.setVisible(true);
Label l1=new Label("Select Your favourite games");
Checkbox chk1=new Checkbox("Cricket");
Checkbox chk2=new Checkbox("Foot Ball");
Checkbox chk3=new Checkbox("Hocky");
fr.add(l1);
fr.add(chk1);
fr.add(chk2);
fr.add(chk3);
}
}

Output:

4. Choice:

  class is used to create a pop-up list of items from which the user may
The choice
choose.

 When inactive, it shows up only the selected item. When theuser clicks on it, the whole
list of choices pops up and the new selection can be made.
 
It is single-choice selection list.
Constructors:
Choice only defines the default constructor, which creates an empty list.
Adding items to the list:
To add items to the list, use add() method.
void add(String str)
Example:
import java.awt.*;
public class Use_Choice
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Label l1=new Label("Choose your favourite Game:");
Choice ch=new Choice();
ch.add("Cricket");
ch.add("Foot Ball");
ch.add("Hocky");
ch.add("kabadi");
ch.add("kho-kho");
fr.add(l1);
fr.add(ch);
}
}

Output:

5. Lists:

 The list class provides a compact, multiple-choice, scrolling selection list.

Unlike the Choice object, which shows only the selected item in the menu, a List object
can be constructed to show any number of choices in the visible window.

It is created to allow multiple selections. 
Constructors:
1. List() - creates a List control that allows only one item to be selected at any one
time.
2. List(int numRows) - creates a list with the specified number of entries. The
numRows specifies the number of entries in the list that will always be visible (others can
be scrolled into view as needed).
3. List(int numRows, Boolean multipleSelect) - In this, if multipleselect is true,
then the user may select two or more items at a time. If it is false , then only one item may be
selected.

Example:
import java.awt.*;
public class Use_List
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Label l1=new Label("Choose your favourite Game:");
List ls=new List(7, true);
ls.add("Cricket");
ls.add("Foot Ball");
ls.add("Hocky");
ls.add("kabadi");
ls.add("kho-kho");
fr.add(l1);
fr.add(ls);
}

}
Output:

6. Scroll Bars:
  Scroll bars can be represented by the slider widgets. 

 Scroll bars
are used to select continuous values between a specified minimum and
maximum.
 
Two types: Horizontal scroll bar and Vertical Scroll bar
Constructors:
1. Scrollbar() - creates a vertical scroll bar
2. Scrollbar(int style)
3. Scrollbar(int style, int initialvalue, int thumbsize, int min, int max)
Example:
import java.awt.*;
public class Use_Scrollbar {
public static void main(String[] arg)
{
Frame fr=new Frame("Using Choice List");
fr.setVisible(true);
fr.setSize(300,300);
fr.setLayout(new FlowLayout());
Scrollbar horzSB=new Scrollbar(Scrollbar.HORIZONTAL,0,1,1,300);
Scrollbar vertSB=new Scrollbar();
fr.add(horzSB);
fr.add(vertSB);
}
}

Output:

7. Text Components:
There are two classes under Text Components:
1. TextField
2. TextArea

1. TextArea:
  The TextField is a slot in which one line text can be entered. 
 
 In the TextField, we can enter the string, modify it, copy, cut or paste it.
 
TextField is a subclass of TextComponent.
Constructors:
1. TextField() - creates a default text field.
2. TextField(int numChars) - creates a text field of specified characters
wide.
3. TextField(String str) - creates a text field with the default string str.
4. TextField(String str, int numChars)
2. TextArea:
  The TextArea control is used to handle multi-line text and it is called as

Multiline Editor.

Constructors:
1. TextArea()
2. TextArea(int numLines, int numChars)
3. TextArea(String str)
4. TextArea(String str, int numLines, int numChars, int sBars)
Here,
numLines – specifies the height, in lines, of the text area
numChars – specifies width of the text area
str – specifies the initial text
sBar – specifies the Scroll Bars. It must be one of the following values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_ VERTICAL_ONLY
Example: (TextField and TextArea)

import java.awt.*;
public class Use_TextComponent
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Text Components");
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label l1=new Label("Enter Your Name: ");
TextField tf=new TextField("AAA",30);
fr.add(l1);
fr.add(tf);
Label l2=new Label("Enter Your Address: ");
TextArea ta=new TextArea("Chennai",10,20);
fr.add(l2);
fr.add(ta);
}
}
Output:

3.12.2: GridLayout

The GridLayout layout manager divides the available space into a grid of cells, evenly
 the space among all the cells in the grid and placing one component in each
 allocating
cell.

 
Cells are always same size.

When you resize the window, the cells grow and shrink, but all the cells have
identical sizes.
Constructors:

 GridLayout(int rows, int cols) - construct a grid with specified rows and cols.

 GridLayout(int rows, int cols, int hspace, int vspace) - to specify the amount of
horizontal and vertical space that should appear between adjacent components.
Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridDemo extends JFrame
{
GridDemo()
{
JButton[] button=new JButton[15];
int j=0;
setSize(400,300);
setVisible(true);
Container cp=getContentPane(); cp.setLayout(new
GridLayout(5,5)); setDefaultCloseOperation(JFrame.EXIT_
ON_CLOSE);

for (int i=0;i<15; i++)


{
button[i]=new JButton(" "+i);
button[i].setBackground(Color.pink);
button[i].setFont(new Font("SanSerif",
Font.BOLD,12)); cp.add(button[i]);
}
}
public static void main(String[] arg)
{
GridDemo cd=new GridDemo();
} }
Output:

3.12.3: Border Layout:



 Border layout divides the container into five regions - North, West, East, South and
Center.
 
The five regions correspond to top, left, bottom, right and center of the container.

  Each region can have only one component. 



Constructors:

  BorderLayout()
 BorderLayout(int hspace, int vspace) – leave space between components.

Border layout grows all components to fill the available space.


You can add components by specifying a constraint as follows:
BorderLayout.CENTER|NORTH|SOUTH|EAST|WEST
Example:

import java.awt.*;
import javax.swing.*;
public class BorderDemo extends JFrame
{
BorderLayout grid=new BorderLayout();
Button b1=new Button("Niorth");
Button b2=new Button("South");
Button b3=new Button("Center");
Button b4=new Button("East");
Button b5=new Button("West");
BorderDemo(String s)
{
super(s);
setLayout(grid);
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.CENTER);
add(b4,BorderLayout.EAST);
add(b5,BorderLayout.WEST);
setSize(200,200);
setVisible(true);
}
public static void main(String arg[])
{
BorderDemo ob=new BorderDemo("BorderLayout Demo");
}
}
Output:

3.12.4: GridBag Layout - Gridlayout without limitations



 
In Grid bag layout, the rows and columns have variable sizes.

 It is possible 
to merge two adjacent cells and make a space for placing larger
components.
 
 To describe the layout to grid bag manager, you must follow the procedure:

1. Create an object of type GridBagLayout. No need to specify rows and column.
2. Set this GridBagLayout object to the container.
3. Create an object of type GridBagConstraints. This object will specify how the
components are laid out within the grid bag.
4. For each components, fill in the GridBagConstraints object.Finally add the
component with the constraint by using the call:
add(Component, constraint);

GridBagConstraints:

  Gridx – specify the column position of the component to be added


  Gridy - specify the row position of the component to be added
  Gridwidth- specify how many columns occupied by the component
 Gridheight - specify how many rows occupied by the component

 fill – used when the component’s display area is larger than the component’s requested
size to determine whether and how to resize the component.

 anchor – used when the component is smaller than its display area to determine
where to palce the component

 weightx – used to determine how to distribute space among columns, which is
important for specifying resizing behaviour.

 weighty - used to determine how to distribute space among rows, which is
important for specifying resizing behaviour.

 ipadx – specifies the component’s internal padding within the layout, how much to
add to the minimum width of the component. Default value=0.

 ipady - specifies the component’s internal padding within the layout, how much
to add to the minimum height of the component. Default value=0.

 insets – specifies the external padding of the component – the minimum amount of
space between the component and the edges of its display are. Default is (0,0,0,0)

Example:

import java.awt.*;
import javax.swing.*;
public class GridBagDemo extends JFrame
{
GridBagLayout gb=new GridBagLayout();
GridBagConstraints gc1= new
GridBagConstraints(); GridBagConstraints gc2=
new GridBagConstraints(); GridBagConstraints
gc3= new GridBagConstraints(); Button b1=new
Button("one"); Button b2=new Button("Two");
Button b3=new Button("Three");

GridBagDemo(String s)
{
super(s);
setLayout(gb);
gc1.gridx=0;
gc1.gridy=0;
gc1.gridwidth=2;
gc1.gridheight=1;
gc2.gridx=0;
gc2.gridy=1;
gc2.gridwidth=1;
gc2.gridheight=1;
gc3.gridx=1;
gc3.gridy=1;
gc3.gridwidth=1;
gc3.gridheight=1;
add(b1,gc1);
add(b2,gc2);
add(b3,gc3);
setSize(200,200);
setVisible(true);
}
public static void main(String arg[])
{
GridBagDemo ob=new GridBagDemo("GridBagLayout Demo");
}
}

Output:
JavaFX Menu
JavaFX provides a Menu class to implement menus. Menu is the main component of a any application. In
JavaFX, javafx.scene.control.Menu class provides all the methods to deal with menus. This class needs
to be instantiated to create a Menu.

The following sample of code shows the implementation of JavaFX menu.

ManuBar menubar = new MenuBar(); //creating MenuBar


Menu MenuName = new Menu("Menu Name"); //creating Menu
MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name"); //creating Menu Item
MenuName.getItems().add(MenuItem1); //adding Menu Item to the Menu
menubar.getMenus().add(MenuName); //adding Menu to the MenuBar

JavaFX Menu

Menu items:
EXAMPLE:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
} }

Output:

MenuBar
MenuBar is just like a navigation bar with a list of items. Usually, we can see this MenuBar at the top of
the screen which contains different menus. MenuBar class is available scene.control.MenuBar package.
MenuBar again contains several menus. Menu contains different menu items. Menu class is available in
javafx.scene.control.Menu package. We can also add sub menu items to the menu item.
Advantage:
 A structured way of data aligning.
 Easy to access the menu items.
Constructors of MenuBar:
 MenuBar(): Creates an instance non parameterized constructor with a new keyword.
 MenuBar(Menu m1,Menu m2, Menu m3……): Creates an instance set of Menus
parameterized constructor with a new keyword.

Frequently Used Methods


Frequently used methods in menubar in javafx:

1. hide(): hide() method hides the menu.


2. show(): show() method shows the menu.
3. getMenus(): The getMenus() method show all the menus inside the MenuBar.
4. getItems(): getItems() method returns items of the menu.
5. setUseSystemMenuBar(boolean b): setUseSystemMenuBar() method used to set the property to
System Menu Bar.
6. setOnShowing(EventHandler e): setOnShowing() method sets the property value showing.
7. setOnShown(EventHandler e): setOnShown() method sets the property value shown.
8. setOnHidden(EventHandler e): setOnHidden() method sets the property value hidden.
9. setOnHiding(EventHandler e): setOnHiding() method sets the property value hiding.

How to Create MenuBar in JavaFX?


 Accessing JavaFX features user-defined class must extend Application.
 In JavaFX creating MenuBar is the first step. MenuBar can instantiate by using new.

MenuBar menuBar =new MenuBar();

 creating Menu is the second step. A menu can instantiate by using new.

Menu menu =new Menu();

 creating MenuItem is the third step. MenuItem can instantiate by using new.

MenuItem menuItem =new MenuItem();

 Adding MenuItem to the Menu is the 4th.

menu.getItems.add(menuItems);

 Adding MenuItem to the Menu is the 5th.

MenuBar.getMenus.add(menu);

 Create VBox or any other display class to add the menuBar is 6th.

VBox vBox=new VBox(menuBar); //Gives vertical box

 Creating a scene means screen to display output is the 7th.

Scene screen = new Scene(vBox, length, width);

 Adding Scene reference screen to the Stage object reference is 8th Adding output screen to

Stage. We will get this stage object reference from the start predefined JavaFX method.
stage.setScene(screen);

 At last display output screen by showing stage reference with the show ().

stage.show();

Examples of MenuBar in JavaFX


1. Adding Menu Items to the MenuBar
package com.menubar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AddingMenuItemsToMenuBar extends Application {
public void start(Stage primaryStage) {
// setting the title of application
primaryStage.setTitle("Adding Items to Menu Bar");
//creating menu bar
MenuBar menuBar=new MenuBar();
//creating menu for adding menu items
Menu menu=new Menu("Show");
//creating menu items
MenuItem companyName=new MenuItem("EDUCBA");
MenuItem courses=new MenuItem("Courses");
MenuItem aboutEDUCBA=new MenuItem("About EDUCBA");
MenuItem feeStructure=new MenuItem("Fee Structure");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(courses);
menu.getItems().add(aboutEDUCBA);
menu.getItems().add(feeStructure);
//adding menu to the menu bar
menuBar.getMenus().add(menu);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args);
}}
Output:

Explanation:

 As you can see in the above output, we have added the first menu items to the menu and menu to

the menu bar respectively.

 Added MenuBar to the vBox and displayed the output.

2. Adding Menu Items and Sub Menu Items to the MenuBar


package com.menubar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AddingSubMenuItemsToMenuBar extends Application {
@Override
public void start(Stage primaryStage) {
// setting the title of application
primaryStage.setTitle("Adding Items to Menu Bar");
//creating menu bar
MenuBar menuBar=new MenuBar();
//creating menu for adding menu items
Menu menu=new Menu("Show");
//creating menu items
MenuItem companyName=new MenuItem("EDUCBA");
MenuItem aboutEDUCBA=new MenuItem("About EDUCBA");
MenuItem feeStructure=new MenuItem("Fee Structure");
//sub menu items for the courses
MenuItem javCourse=new MenuItem("Java");
MenuItem pythonCourse=new MenuItem("Python");
MenuItem cCourse=new MenuItem("C");
MenuItem angularCourse=new MenuItem("Angular JS");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(aboutEDUCBA);
menu.getItems().add(feeStructure);
//adding sub menu items to the course menu
Menu subMenuCourse=new Menu("All Courses");
subMenuCourse.getItems().add(javCourse);
subMenuCourse.getItems().add(pythonCourse);
subMenuCourse.getItems().add(cCourse);
subMenuCourse.getItems().add(angularCourse);
menu.getItems().add(subMenuCourse);
//adding menu to the menu bar
menuBar.getMenus().add(menu);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args);
}
}
Explanation:

 As you can see in the above output, we have added the first menu items to the menu, sub menu
items to the submenu, sub menu items to the menu and menu to the menu bar respectively.
 Added MenuBar to the vBox and displayed the output.
3. Adding Menu Items to the MenuBar
package com.menubar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AddingEventActionToMenuItems extends Application {
@Override
public void start(Stage primaryStage) {
// setting the title of application
primaryStage.setTitle("Adding Items to Menu Bar");
//creating menu bar
MenuBar menuBar=new MenuBar();
//creating menu for adding menu items
Menu menu=new Menu("Show");
//creating menu items
MenuItem companyName=new MenuItem("EDUCBA");
MenuItem courses=new MenuItem("Courses");
MenuItem aboutEDUCBA=new MenuItem("About EDUCBA");
MenuItem feeStructure=new MenuItem("Fee Structure");
//adding menu items to the menu
menu.getItems().add(companyName);
menu.getItems().add(courses);
menu.getItems().add(aboutEDUCBA);
menu.getItems().add(feeStructure);
//adding menu to the menu bar
menuBar.getMenus().add(menu);
//creating label for adding menu item selection
Label selectionLabel=new Label();
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
selectionLabel.setText("\t\t\t\t You have " +((MenuItem)e.getSource()).getText() +
" item selected");
}
};
//adding event to the menu items
companyName.setOnAction(event);
courses.setOnAction(event);
aboutEDUCBA.setOnAction(event);
feeStructure.setOnAction(event);
//creating VBox for adding all menu bar
VBox vBox=new VBox(menuBar, selectionLabel);
//adding scroll pane to the scene
Scene scene = new Scene(vBox, 401, 201);
primaryStage.setScene(scene);
//showing the output
primaryStage.show();
}
public static void main(String[] args) {
//invoking main method from JVM
launch(args);
}
}

Explanation:

 As you can see in the above output, we have added the first menu items to the menu and menu to
the menu bar respectively.
 Added MenuBar and label to the vBox and displayed the output.

Adding Menu Items


Set the functionality for the File menu by adding the following items:

 Shuffle – to load reference information about plants


 Clear – to remove the reference information and clear the scene
 Separator – to detach menu items
 Exit – to exit the application
Bold lines in Example 22-2 create a Shuffle menu by using the MenuItem class and add graphical
components to the application scene. The MenuItem class enables creating an actionable item with text
and graphics. The action performed on a user click is defined by the setOnAction method, similar to
the Button class.

Example 22-2 Adding the Shuffle Menu Item with Graphics


import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class MenuSample extends Application {

final PageData[] pages = new PageData[] {


new PageData("Apple",
"The apple is the pomaceous fruit of the apple tree, species Malus "
+"domestica in the rose family (Rosaceae). It is one of the most "
+"widely cultivated tree fruits, and the most widely known of "
+"the many members of genus Malus that are used by humans. "
+"The tree originated in Western Asia, where its wild ancestor, "
+"the Alma, is still found today.",
"Malus domestica"),
new PageData("Hawthorn",
"The hawthorn is a large genus of shrubs and trees in the rose "
+ "family, Rosaceae, native to temperate regions of the Northern "
+ "Hemisphere in Europe, Asia and North America. "
+ "The name hawthorn was "
+ "originally applied to the species native to northern Europe, "
+ "especially the Common Hawthorn C. monogyna, and the unmodified "
+ "name is often so used in Britain and Ireland.",
"Crataegus monogyna"),
new PageData("Ivy",
"The ivy is a flowering plant in the grape family (Vitaceae) native"
+" to eastern Asia in Japan, Korea, and northern and eastern China."
+" It is a deciduous woody vine growing to 30 m tall or more given "
+"suitable support, attaching itself by means of numerous small "
+"branched tendrils tipped with sticky disks.",
"Parthenocissus tricuspidata"),
new PageData("Quince",
"The quince is the sole member of the genus Cydonia and is native"
+" to warm-temperate southwest Asia in the Caucasus region. The "
+"immature fruit is green with dense grey-white pubescence, most "
+"of which rubs off before maturity in late autumn when the fruit "
+"changes color to yellow with hard, strongly perfumed flesh.",
"Cydonia oblonga")
};

final String[] viewOptions = new String[] {


"Title",
"Binomial name",
"Picture",
"Description"
};

final Entry<String, Effect>[] effects = new Entry[] {


new SimpleEntry<String, Effect>("Sepia Tone", new SepiaTone()),
new SimpleEntry<String, Effect>("Glow", new Glow()),
new SimpleEntry<String, Effect>("Shadow", new DropShadow())
};

final ImageView pic = new ImageView();


final Label name = new Label();
final Label binName = new Label();
final Label description = new Label();
private int currentIndex = -1;

public static void main(String[] args) {


launch(args);
}

public void start(Stage stage) {


stage.setTitle("Menu Sample");
Scene scene = new Scene(new VBox(), 400, 350);
scene.setFill(Color.OLDLACE);
name.setFont(new Font("Verdana Bold", 22));
binName.setFont(new Font("Arial Italic", 10));
pic.setFitHeight(150);
pic.setPreserveRatio(true);
description.setWrapText(true);
description.setTextAlignment(TextAlignment.JUSTIFY);

shuffle();

MenuBar menuBar = new MenuBar();

final VBox vbox = new VBox();


vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.setPadding(new Insets(0, 10, 0, 10));
vbox.getChildren().addAll(name, binName, pic, description);

// --- Menu File


Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Shuffle",
new ImageView(new Image("menusample/new.png")));
add.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
shuffle();
vbox.setVisible(true);
}
});

menuFile.getItems().addAll(add);

// --- Menu Edit


Menu menuEdit = new Menu("Edit");

// --- Menu View


Menu menuView = new Menu("View");

menuBar.getMenus().addAll(menuFile, menuEdit, menuView);


((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
stage.setScene(scene);
stage.show();
}
private void shuffle() {
int i = currentIndex;
while (i == currentIndex) {
i = (int) (Math.random() * pages.length);
}
pic.setImage(pages[i].image);
name.setText(pages[i].name);
binName.setText("(" + pages[i].binNames + ")");
description.setText(pages[i].description);
currentIndex = i;
}

private class PageData {


public String name;
public String description;
public String binNames;
public Image image;
public PageData(String name, String description, String binNames) {
this.name = name;
this.description = description;
this.binNames = binNames;
image = new Image(getClass().getResourceAsStream(name + ".jpg"));
}
}
}
When a user selects the Shuffle menu item, the shuffle method called within setOnAction specifies the
title, the binomial name, a picture of the plant, and its description by calculating the index of the elements
in the corresponding arrays.

The Clear menu item is used to erase the application scene. You can implement this by making
the VBox container with the GUI elements invisible as shown in Example 22-3.

Example 22-3 Creating the Clear Menu Item with Accelerator

MenuItem clear = new MenuItem("Clear");


clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
clear.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
vbox.setVisible(false);
}
});
Implementation of the MenuItem class enables developers to set a menu accelerator, a key combination
that performs the same action as the menu item. With the Clear menu, users can either select the action
from the File menu category or press Control Key and X key simultaneously.

The Exit menu closes the application window. Set System.exit(0) as an action for this menu item as
shown in Example 22-4.

Example 22-4 Creating the Exit Menu Item

MenuItem exit = new MenuItem("Exit");


exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
Use the getItems method shown in Example 22-5 to add the newly created menu items to the File menu.
You can create a separator menu item and add it within the getItems method to visually detach the Exit
menu item.

Example 22-5 Adding Menu Items

menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);


Add Example 22-2, Example 22-3, Example 22-4, and Example 22-5 to the Menu Sample application,
and then compile and run it. Select the Shuffle menu item to load reference information about different
plants. Then clear the scene (Clear), and close the application (Exit). Figure 22-3 shows selection of the
Clear menu item.

Figure 22-3 File Menu with Three Menu Items


Description of "Figure 22-3 File Menu with Three Menu Items"

With the View menu, you can hide and show elements of reference information. Implement
the createMenuItem method and call it within the start method to create four CheckMenuItem objects.
Then add newly created check menu items to the View menu to toggle visibility of the title, binomial
name, picture of the plant, and its description. Example 22-6 shows two code fragments that implement
these tasks.

Example 22-6 Applying the CheckMenuItem Class to Create Toggle Options

// --- Creating four check menu items within the start method
CheckMenuItem titleView = createMenuItem ("Title", name);
CheckMenuItem binNameView = createMenuItem ("Binomial name", binName);
CheckMenuItem picView = createMenuItem ("Picture", pic);
CheckMenuItem descriptionView = createMenuItem ("Description", description);
menuView.getItems().addAll(titleView, binNameView, picView, descriptionView);

...

// The createMenuItem method


private static CheckMenuItem createMenuItem (String title, final Node node){
CheckMenuItem cmi = new CheckMenuItem(title);
cmi.setSelected(true);
cmi.selectedProperty().addListener(new ChangeListener<Boolean>() {
public void changed(ObservableValue ov,
Boolean old_val, Boolean new_val) {
node.setVisible(new_val);
}
});
return cmi;
}
The CheckMenuItem class is an extension of the MenuItem class. It can be toggled between selected and
deselected states. When selected, a check menu item shows a check mark.

Example 22-6 creates four CheckMenuItem objects and processes the changing of
their selectedProperty property. When, for example, a user deselects the picView item,
the setVisible method receives the false value, the picture of the plant becomes invisible. When you add
this code fragment to the application, compile, and run the application, you can experiment with selecting
and deselecting the menu items. Figure 22-4 shows the application in the moment when the title and
picture of the plant are shown, but its binomial name and description are hidden.

Figure 22-4 Using Check Menu Items

Description of "Figure 22-4 Using Check Menu Items"

Creating Submenus
For the Edit menu, define two menu items: Picture Effect and No Effects. The Picture Effect menu item
is designed as a submenu with three items to set one of the three available visual effects. The No Effects
menu item removes the selected effect and restores the initial state of the image.

Use the RadioMenuItem class to create the items of the submenu. Add the radio menu buttons to a toggle
group to make the selection mutually exclusive. Example 22-7 implements these tasks.

Example 22-7 Creating a Submenu with Radio Menu Items


//Picture Effect menu
Menu menuEffect = new Menu("Picture Effect");
final ToggleGroup groupEffect = new ToggleGroup();
for (Entry<String, Effect> effect : effects) {
RadioMenuItem itemEffect = new RadioMenuItem(effect.getKey());
itemEffect.setUserData(effect.getValue());
itemEffect.setToggleGroup(groupEffect);
menuEffect.getItems().add(itemEffect);
}
//No Effects menu
final MenuItem noEffects = new MenuItem("No Effects");

noEffects.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
pic.setEffect(null);
groupEffect.getSelectedToggle().setSelected(false);
}
});

//Processing menu item selection


groupEffect.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (groupEffect.getSelectedToggle() != null) {
Effect effect =
(Effect) groupEffect.getSelectedToggle().getUserData();
pic.setEffect(effect);
}
}
});
//Adding items to the Edit menu
menuEdit.getItems().addAll(menuEffect, noEffects);
The setUserData method defines a visual effect for a particular radio menu item. When one of the items
in the toggle group is selected, the corresponding effect is applied to the picture. When the No Effects
menu item is selected, the setEffect method specifies the null value and no effects are applied to the
picture.

Figure 22-5 captures a moment when a user is selecting a Shadow menu item.

Figure 22-5 Submenu with Three Radio Menu Items


Description of "Figure 22-5 Submenu with Three Radio Menu Items"

When the DropShadow effect is applied to the picture, it looks as shown in Figure 22-6.

Figure 22-6 Picture of Quince with a DropShadow Effect Applied

Description of "Figure 22-6 Picture of Quince with a DropShadow Effect Applied"

You can use the setDisable method of the MenuItem class to disable the No Effects menu when none of
the effects are selected in the Picture Effect submenu. Modify Example 22-7 as shown in Example 22-8.
Example 22-8 Disabling a Menu Item

Menu menuEffect = new Menu("Picture Effect");


final ToggleGroup groupEffect = new ToggleGroup();
for (Entry<String, Effect> effect : effects) {
RadioMenuItem itemEffect = new RadioMenuItem(effect.getKey());
itemEffect.setUserData(effect.getValue());
itemEffect.setToggleGroup(groupEffect);
menuEffect.getItems().add(itemEffect);
}
final MenuItem noEffects = new MenuItem("No Effects");
noEffects.setDisable(true);
noEffects.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
pic.setEffect(null);
groupEffect.getSelectedToggle().setSelected(false);
noEffects.setDisable(true);
}
});

groupEffect.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (groupEffect.getSelectedToggle() != null) {
Effect effect =
(Effect) groupEffect.getSelectedToggle().getUserData();
pic.setEffect(effect);
noEffects.setDisable(false);
} else {
noEffects.setDisable(true);
}
}
});
menuEdit.getItems().addAll(menuEffect, noEffects);
When none of the RadioMenuItem options are selected, the No Effect menu item is disabled as shown
in Figure 22-7. When a user selects one of the visual effects, the No Effects menu item is enabled.

Figure 22-7 Effect Menu Item Is Disabled


Description of "Figure 22-7 Effect Menu Item Is Disabled"

Adding Context Menus


When you cannot allocate any space of your user interface for a required functionality, you can use a
context menu. A context menu is a pop-up window that appears in response to a mouse click. A context
menu can contain one or more menu items.

In the Menu Sample application, set a context menu for the picture of the plant, so that users can copy the
image.

Use the ContextMenu class to define the context menu as shown in Example 22-9.

Example 22-9 Defining a Context Menu

final ContextMenu cm = new ContextMenu();


MenuItem cmItem1 = new MenuItem("Copy Image");
cmItem1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putImage(pic.getImage());
clipboard.setContent(content);
}
});

cm.getItems().add(cmItem1);
pic.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
public void handle(MouseEvent e) {
if (e.getButton() == MouseButton.SECONDARY)
cm.show(pic, e.getScreenX(), e.getScreenY());
}
});
When a user right clicks the ImageView object, the show method is called for the context menu to enable
its showing.

The setOnAction method defined for the Copy Image item of the context menu creates a Clipboard object
and adds the image as its content. Figure 22-8 captures a moment when a user is selecting the Copy
Image context menu item.

Figure 22-8 Using the Context Menu

Description of "Figure 22-8 Using the Context Menu"

You can try to copy the image and paste it into in a graphical editor.

For further enhancements, you can add more menu items to the context menu and specify different
actions. You can also create a custom menu by using the CustomMenuItem class. With this class you can
embed an arbitrary node within a menu and specify, for example, a button or a slider as a menu item.

You might also like