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

Java Notes

Uploaded by

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

Java Notes

Uploaded by

Abhisek Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 728

Object Oriented

Programming using Java


Programming Paradigm
• Paradigm means methodology
• A Programming Paradigm is a fundamental style of
computer programming technique that defines how
the structure and basic elements of a computer
program is built
• While some programming languages strictly follow a
single paradigm, others may draw concepts from
more than one

By Jagadish Sahoo
Types of Programming Paradigm
• Monolithic Programming – emphasizes on finding a solution
• Structures Programming – focus on modules
• Procedure-oriented Programming – lays stress on algorithm
• Object-oriented Programming – emphasizes on class and
objects

By Jagadish Sahoo
Monolithic Programming
• It indicates the program which contains a single function for a large
program.
• A program is not divided into parts and hence is the name.
• When the program size increases it leads inconvenience and difficult
to maintain.
• The program contains jump statements such as goto that transfer
control to any statement as specified in it.
• The global data can be accessed and modified from any part of the
program and hence posing a serious threat.
• It is suitable to develop simple and small application.
• Example : Basic
By Jagadish Sahoo
Structured Programming
• Programming tasks can be split into smaller sections
known as functions or subroutines, which can be
called whenever they are required.
• It is often associated with “Top-down” approach to
design.
• It attempts to divide the problem into smaller blocks
or procedures which interact with each other.
• Example : Pascal,Ada,C
By Jagadish Sahoo
Procedure-oriented Programming
• It basically consists of writing a list of instructions for
the computer to follow and organizing these
instructions into groups known as functions.
• The primary focus is on function rather than data.
• Examples : COBOL, Fortran

By Jagadish Sahoo
Structure of Procedure-oriented Programming

By Jagadish Sahoo
Characteristics of POP
• Emphasis is on doing things(Algorithms).
• Larger programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design

By Jagadish Sahoo
Relationship of Data and Functions in POP

By Jagadish Sahoo
Object-oriented Programming
• It treats data as a critical element in program development and does
not allow it to flow freely around the system.
• It ties data more closely to the functions that operate on it and
protects it from accidental modification from outside functions.
• OOP allows decomposition of a problem into number of entities
called objects and then build data and functions around these
objects.
• The data of an object can be accessed only by the functions
associated with that object.
• Functions of one object can access the functions of another object.

By Jagadish Sahoo
Organization of data and function in OOP

By Jagadish Sahoo
Characteristics of OOP
• Emphasis is on data rather than procedure.
• Programs are divided into objects.
• Data Structures are designed such that they characterize the objects.
• Functions that operate on data of an object are tied together in the
data structure.
• Data is hidden and can not be accessed by external functions.
• Objects may communicate with each other through functions.
• New data and functions can be added easily whenever necessary.
• Follows bottom-up approach in program design.

By Jagadish Sahoo
Basic concepts of OOP
• Classes
• Objects
• Data abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Message Passing

By Jagadish Sahoo
Classes
• Classes are user-defined datatypes
• A class is a collection of Data member and member functions.
• Variables declared in a class are called data member and functions
declared in class are called member functions or methods.
• Objects are variable of type class. Once a class has been defined, we
can create any number of objects belonging to that class.
• Each object is associated with the data of type class with which they
are created.
• If Fruit is a class, then apple, orange, banana etc. are the objects of
the class Fruit.
• Class is a logical structure.
By Jagadish Sahoo
Object
• Basic run-time entities in an object-oriented system i.e. fundamental
building blocks for designing a software.
• It is a collection of data members and associated member
function(method).
• An object represents a particular instance of a class.
• An object has 3 characteristics:
1. Name
2. State
3. Behavior
• Objects take up space in the memory and have associated address.
• When a program is executed, objects interact by sending messages to one
another.
• Example : Book, Bank, Customer,ByAccount
Jagadish Sahoo
etc.
By Jagadish Sahoo
Data Abstraction
• Abstraction refers to the act of representing essential features
without including the background details or explanation.
• Data abstraction is an encapsulation of object’s state and behavior.
• Data abstraction increases the power of programming languages by
creating user-defined data types.
• Classes uses the concept of abstraction and are defined as a list of
abstract attributes(data members) and functions(methods).
• Since classes use the concept of data abstraction, they are also used
as Abstract Data Type(ADT).

By Jagadish Sahoo
Encapsulation
• Data encapsulation combines data and functions into a single unit
called class.
• When using data encapsulation, data is not accessed directly, it is only
accessible through the methods present inside the class.
• Data encapsulation enables data hiding, which is an important
concept of OOP.
• Example : Capsule is wrapped with different medicines.

By Jagadish Sahoo
Inheritance
• It is the process by which one object can acquire the properties of
another.
• It allows the declaration and implementation of new class/classes
from existing class.
• The existing class is known as base class/parent class/super class and
the new class/classes is/are known as derived class/child class/sub
class.
• It uses the concept of Reusability.

By Jagadish Sahoo
By Jagadish Sahoo
Types of Inheritance
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

By Jagadish Sahoo
By Jagadish Sahoo
Benefits of Inheritance
• It helps to reuse an existing part rather than hardcoding every time.
• It increases reliability and decreases maintenance cost.
• Development time is less & product can be generated more quickly.

By Jagadish Sahoo
Polymorphism
• The ability to take more than one form is known as Polymorphism.
• An operation may exhibit different behaviors in different instances.
The behavior depends upon the types of data used in the operation.
• + operator can be used to add 2 numbers and the result is sum of two
numbers.
• Same + operators can be used to add 2 strings and the result is
concatenation of 2 strings.
• This process of making an operator to exhibit different behaviors in
different instances is known as operator overloading.

By Jagadish Sahoo
Polymorphism(Function Overloading)
• A single function name can be used to handle different number and
different types of arguments.
• Using a single function name to perform different types of tasks is
known as function overloading.

By Jagadish Sahoo
Message Passing
• Any processing is accomplished by sending messages to objects.
• A message for an object is a request for execution of a
procedure/function.
• It invoke a function on the receiving object that generates the desired
result.
• Message passing involves specifying the name of the object, name of
the function(message) and information to be sent.

By Jagadish Sahoo
By Jagadish Sahoo
What is Java
• Java is a programming language and a platform.
• Java was developed by Sun Microsystems (which is now
the subsidiary of Oracle) in the year 1995.
• James Gosling is known as the father of Java.
• Before Java, its name was Oak.
• Since Oak was already a registered company, so James
Gosling and his team changed the Oak name to Java.
• Platform: Any hardware or software environment in
which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is
called a platform
By Jagadish Sahoo
Application
• Desktop Applications such as acrobat reader, media player, antivirus,
etc.
• Web Applications such as irctc.co.in.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games, etc.

By Jagadish Sahoo
Types of Java Applications
1) Standalone Application
• Standalone applications are also known as desktop
applications or window-based applications. These are
traditional software that we need to install on every
machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java
for creating standalone applications.
2) Web Application
• An application that runs on the server side and creates
a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF,
etc. technologies are used for creating web applications
in Java.
By Jagadish Sahoo
3) Enterprise Application
• An application that is distributed in nature, such as
banking applications, etc. is called enterprise
application. In Java, EJB is used for creating enterprise
applications.
4) Mobile Application
• An application which is created for mobile devices is
called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.

By Jagadish Sahoo
Java Platforms / Editions
1) Java SE (Java Standard Edition)
• It is a Java programming platform. It includes Java programming APIs
such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It
includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, etc.
2) Java EE (Java Enterprise Edition)
• It is an enterprise platform which is mainly used to develop web and
enterprise applications. It is built on the top of the Java SE platform. It
includes topics like Servlet, JSP, Web Services, EJB etc.

By Jagadish Sahoo
3) Java ME (Java Micro Edition)
• It is a micro platform which is mainly used to develop
mobile applications.
4) JavaFX
• It is used to develop rich internet applications. It uses a
light-weight user interface AP

By Jagadish Sahoo
History
1) James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green
Team.
2) Initially designed for small, embedded systems in
electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling,
and the file extension was .gt.
4) After that, it was called Oak and was developed as a
part of the Green project.

By Jagadish Sahoo
Why Java named "Oak"?
• Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
• In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.

By Jagadish Sahoo
Why Java Programming named "Java"?
• The team gathered to choose a new name. The suggested
words were "dynamic", "revolutionary", "Silk", "jolt", "DNA",
etc. They wanted something that reflected the essence of
the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.
• According to James Gosling, "Java was one of the top
choices along with Silk". Since Java was so unique, most of
the team members preferred Java than other names.
• Java is an island of Indonesia where the first coffee was
produced (called java coffee). It is a kind of espresso bean.
Java name was chosen by James Gosling while having
coffee near his office.

By Jagadish Sahoo
• Java is just a name, not an acronym.
• Initially developed by James Gosling at Sun
Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
• In 1995, Time magazine called Java one of the Ten
Best Products of 1995.
• JDK 1.0 released in(January 23, 1996). After the first
release of Java, there have been many additional
features added to the language. Now Java is being used
in Windows applications, Web applications, enterprise
applications, mobile applications etc. Each new version
adds the new features in Java.

By Jagadish Sahoo
Features of Java
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic

By Jagadish Sahoo
Simple
• Java syntax is based on C++ (so easier for
programmers to learn it after C++).
• Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
• There is no need to remove unreferenced objects
because there is an Automatic Garbage Collection in
Java.

By Jagadish Sahoo
Object-oriented

• Java is an 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 behavior.

By Jagadish Sahoo
Platform Independent
• Java is platform independent because it is different
from other languages like C, C++, etc. which are
compiled into platform specific machines
• Java is a write once, run anywhere language.

By Jagadish Sahoo
• A platform is the hardware or software environment in
which a program runs.
• There are two types of platforms 1) software-based and
2) hardware-based.
• Java provides a 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)

By Jagadish Sahoo
• Java code can be run on multiple platforms, for
example, 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).

By Jagadish Sahoo
Secured
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java
Runtime Environment(JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. 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.

By Jagadish Sahoo
By Jagadish Sahoo
Robust(Strong)

• It uses strong memory management.


• There is a 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 are exception handling and the type checking
mechanism in Java. All these points make Java robust.

By Jagadish Sahoo
Architecture-neutral

• Java is architecture neutral because there are no


implementation dependent features, for example, the
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.
• It occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

By Jagadish Sahoo
Portable
• Java is portable because it facilitates you to carry the
Java bytecode to any platform. It doesn't require any
implementation.

By Jagadish Sahoo
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.

By Jagadish Sahoo
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.

By Jagadish Sahoo
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.

By Jagadish Sahoo
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).

By Jagadish Sahoo
Features C++ Java
Platform Independence Platform-dependent Platform-independent
Interpreter and Compiler Compiled programming language Compiled and interpreted language

Portability Not portable Portable


Memory Management Manual System-controlled
Multiple Inheritance Supports single inheritance and multiple Only supports single inheritance
inheritance

Overloading Both operators and methods can be Allows only method overloading
overloaded

Compatibility with Other Programming Compatible with C Not compatible with any language
Languages

Pointers Supports pointers Supports pointers with restrictions

Documentation Comment Does not support documentation comments Has built-in documentation comments support
(/**…**/), allowing Java files to have their own
documentation

Thread Support Does not support thread Has built-in thread support via the “thread”
class

By Jagadish Sahoo
Requirements to write a java program
• Install the JDK
• Set path of the jdk/bin directory.
• Create the java program
• Compile and run the java program
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
• save this file as Simple.java
To compile: javac Simple.java
To execute: java Simple

By Jagadish Sahoo
Compilation Flow
• When we compile Java program using javac tool, java compiler
converts the source code into byte code

By Jagadish Sahoo
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
• 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
the static method. The core advantage of the static method is that
there is no need to create an object to invoke the static method. The
main method is executed by the JVM, so it doesn't require to create
an object to invoke the main method. So it saves memory.

By Jagadish Sahoo
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

• 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 to print statement. Here, System is a
class, out is the object of PrintStream class, println() is the method of
PrintStream class.

By Jagadish Sahoo
How many ways can we write a Java program
• By changing the sequence of the modifiers, method prototype is not
changed in Java.
static public void main(String args[])
• The subscript notation in Java array can be used after type, before
the variable or after the variable.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])

By Jagadish Sahoo
• You can provide var-args support to the main method by passing 3
ellipses (dots)
public static void main(String... args)

• Having a semicolon at the end of class is optional in Java.


class A{
static public void main(String... args){
System.out.println("hello java4");
}
};

By Jagadish Sahoo
Valid java main method signature
• public static void main(String[] args)
• public static void main(String []args)
• public static void main(String args[])
• public static void main(String... args)
• static public void main(String[] args)
• public static final void main(String[] args)
• final public static void main(String[] args)
• final strictfp public static void main(String[] args)

By Jagadish Sahoo
Invalid java main method signature
• public void main(String[] args)
• static void main(String[] args)
• public void static main(String[] args)
• abstract public static void main(String[] args)

By Jagadish Sahoo
What happens at compile time?
• At compile time, java file is compiled by Java Compiler (It does not
interact with OS) and converts the java code into bytecode.

By Jagadish Sahoo
What happens at runtime?
• At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
Interpreter: read bytecode stream then execute the instructions.

By Jagadish Sahoo
Can we save a java source file by other name than
the class name?
• Yes, if the class is not public.

To compile: javac Hard.java


To execute: java Simple
By Jagadish Sahoo
Can we have multiple classes in a java source file?
• Yes

By Jagadish Sahoo
JVM
• JVM (Java Virtual Machine) is an abstract machine. It is called a virtual
machine because it doesn't physically exist.
• It is a specification that provides a runtime environment in which Java
bytecode can be executed.
• It can also run those programs which are written in other languages
and compiled to Java bytecode.
• JVMs are available for many hardware and software platforms. JVM,
JRE, and JDK are platform dependent because the configuration of
each OS is different from each other.
• However, Java is platform independent.

By Jagadish Sahoo
The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment

By Jagadish Sahoo
JRE

• JRE is an acronym for Java Runtime Environment.


• The Java Runtime Environment is a set of software tools which are
used for developing Java applications.
• It is used to provide the runtime environment.
• It is the implementation of JVM.
• It physically exists. It contains a set of libraries + other files that JVM
uses at runtime.

By Jagadish Sahoo
By Jagadish Sahoo
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.
• 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.

By Jagadish Sahoo
By Jagadish Sahoo
JVM (Java Virtual Machine) Architecture
• VM (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).

By Jagadish Sahoo
What it does
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment

By Jagadish Sahoo
JVM Architecture

By Jagadish Sahoo
Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever
we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.
• Bootstrap ClassLoader: This is the first classloader which is the super class
of Extension classloader. It loads the jar file which contains all class files of
Java Standard Edition like java.lang package classes, java.net package
classes, java.util package classes, java.io package classes, java.sql package
classes etc.
• Extension ClassLoader: This is the child classloader of Bootstrap and
parent classloader of System classloader. It loads the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
• System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set
to current directory. It is also known as Application classloader.
By Jagadish Sahoo
• Class(Method) Area
Class(Method) Area stores per-class structures such as the field and
method data, the code for methods.
• Heap
It is the runtime data area in which objects are allocated.
• Stack
1. Java Stack stores frames. It holds local variables and partial results,
and plays a part in method invocation and return.
2. Each thread has a private JVM stack, created at the same time as
thread.
3. A new frame is created each time a method is invoked. A frame is
destroyed when its method invocation completes.

By Jagadish Sahoo
• Program Counter Register
PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed.
• Native Method Stack
It contains all the native methods used in the application.
• Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It 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.

By Jagadish Sahoo
• Java Native Interface
1. Java Native Interface (JNI) is a framework which provides an
interface to communicate with another application written in
another language like C, C++, Assembly etc.
2. Java uses JNI framework to send output to the Console or interact
with OS libraries.

By Jagadish Sahoo
Java Variables
• A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
• Variable is name of reserved area allocated in memory.
• Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
• There are two types of data types in Java:
1. primitive
2. non-primitive.

By Jagadish Sahoo
Beginning Java programming
The process of Java programming can be simplified in three steps:
• Create the program by typing it into a text editor and saving it to a file
– HelloWorld.java.
• Compile it by typing “javac HelloWorld.java” in the terminal window.
• Execute (or run) it by typing “java HelloWorld” in the terminal
window.

By Jagadish Sahoo
/* This is a simple Java program.
FileName : "HelloWorld.java". */
class HelloWorld
{
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
System.out.println("Hello, World");
}
}

Class definition:This line uses the keyword class to declare that a new class is being defined.
class HelloWorld

HelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will
be between the opening curly brace { and the closing curly brace } .

By Jagadish Sahoo
main method: In Java programming language, every
application must contain a main method whose signature is:

public static void main(String[] args)

public: So that JVM can execute the method from anywhere.


static: Main method is to be called without object.
The modifiers public and static can be written in either order.
void: The main method doesn't return anything.
main(): Name configured in the JVM.
String[]: The main method accepts a single argument:
an array of elements of type String.

By Jagadish Sahoo
System.out.println("Hello, World");
This line outputs the string “Hello, World” followed by a new line on the
screen. Output is actually accomplished by the built-in
println( ) method. System is a predefined class that provides access to
the system, and out is the variable of type output stream that is
connected to the console.

Comments: They can either be multi-line or single line comments.


/* This is a simple Java program.
Call this file "HelloWorld.java". */
This is a multiline comment. This type of comment must begin with /*
and end with */. For single line you may directly use // as in C/C++.
By Jagadish Sahoo
Important Points
•The name of the class defined by the program is HelloWorld,
which is same as name of file(HelloWorld.java). This is not a
coincidence. In Java, all codes must reside inside a class and
there is at most one public class which contain main() method.
•By convention, the name of the main class(class which contain
main method) should match the name of the file that holds the
program.

By Jagadish Sahoo
Compiling the program
After successfully setting up the environment, we can open terminal in both
Windows/Unix and can go to directory where the file – HelloWorld.java is
present.
Now, to compile the HelloWorld program, execute the compiler – javac ,
specifying the name of the source file on the command line, as shown:
javac HelloWorld.java
The compiler creates a file called HelloWorld.class (in present working
directory) that contains the bytecode version of the program. Now, to
execute our program, JVM(Java Virtual Machine) needs to be called using
java, specifying the name of the class file on the command line, as shown:
java HelloWorld
This will print “Hello World” to the terminal screen.
By Jagadish Sahoo
Java Identifiers
• In programming languages, identifiers are used for identification
purposes. In Java, an identifier can be a class name, method name,
variable name, or label.

By Jagadish Sahoo
Rules for defining Java Identifiers
• The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For
example “roll@” is not a valid java identifier as it contain ‘@’ special
character.
• Identifiers should not start with digits([0-9]). For example “123name” is a
not a valid java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier. For example “int while =
20;” is an invalid statement as while is a reserved word. There
are 53 reserved words in Java.

By Jagadish Sahoo
Reserved Words
• Any programming language reserves some words to represent
functionalities defined by that language. These words are called
reserved words.
• They can be briefly categorized into two parts : keywords(50)
and literals(3).
• Keywords define functionalities and literals define a value.

By Jagadish Sahoo
Data types in Java
There are majorly two types of languages.
• Statically typed language where each variable and expression type is
already known at compile time. Once a variable is declared to be of a
certain data type, it cannot hold values of other data types.
Example: C, C++, Java.
• The other is Dynamically typed languages. These languages can
receive different data types over time.
Example: Ruby, Python

By Jagadish Sahoo
• Java is statically typed and also a strongly typed language because,
in Java, each type of data (such as integer, character, hexadecimal,
packed decimal, and so forth) is predefined as part of the
programming language and all constants or variables defined for a
given program must be described with one of the data types.

By Jagadish Sahoo
By Jagadish Sahoo
Primitive Data Type
• Primitive data are only single values and have no special capabilities.

By Jagadish Sahoo
boolean
• boolean data type represents only one bit of information either true
or false, but the size of the boolean data type is virtual machine-
dependent.
• Values of type boolean are not converted implicitly or explicitly (with
casts) to any other type.
• Syntax : boolean booleanvariable;
• Size : Virtual Machine dependent
• Values: true or false
• Default Value: false

By Jagadish Sahoo
byte
• The byte data type is an 8-bit signed integer. The byte data type is
useful for saving memory in large arrays.
• Syntax: byte variablename;
• Size: 1 byte(8 bits)
• Values: -128 to +127
• Default Value: 0

By Jagadish Sahoo
short
• The short data type is a 16-bit signed integer.
• Similar to byte, use a short to save memory in large arrays, in
situations where the memory savings actually matters.
• Syntax: short variablename;
• Size: 2 bytes(16 bits)
• Values: -32, 768 to 32, 767 (inclusive)
• Default Value: 0

By Jagadish Sahoo
int
• It is a 32-bit signed integer.
• Syntax: int variablename;
• Size: 4 byte ( 32 bits )
• Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)
• Default Value: 0

By Jagadish Sahoo
long
• The long data type is a 64-bit signed integer.
• Syntax: long variablename;
• Size: 8 byte ( 64 bits )
• Values: -9, 223, 372, 036, 854, 775, 808
to
9, 223, 372, 036, 854, 775, 807(inclusive)
Default Value: 0

By Jagadish Sahoo
float
• The float data type is a 32-bit floating-point. Use a float (instead of
double) if you need to save memory in large arrays of floating-point
numbers.
• Syntax: float variablename;
• Size: 4 byte ( 32 bits )
• Values: upto 7 decimal digits
• Default Value: 0.0

By Jagadish Sahoo
double
• The double data type is a 64-bit floating-point. For decimal values,
this data type is generally the default choice.
• Syntax: double variablename;
• Size: 8 byte ( 64 bits )
• Values: upto 16 decimal digits
• Default Value: 0.0

By Jagadish Sahoo
char
• The char data type is a single 16-bit Unicode character.
• Syntax: char variablename;
• Size: 2 byte ( 16 bits )
• Values: '\u0000' (0) to '\uffff' (65535)
• Default Value: '\u0000‘
• Unicode defines a fully international character set that can represent
most of the world’s written languages. It is a unification of dozens of
character sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and
many more.

By Jagadish Sahoo
Why is the size of char is 2 byte in java..?
• In other languages like C/C++ uses only ASCII characters and to
represent all ASCII characters 8-bits is enough,
But java uses the Unicode system not the ASCII code system and to
represent Unicode system 8 bit is not enough to represent all
characters so java uses 2 bytes for characters.

By Jagadish Sahoo
Operators
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator

By Jagadish Sahoo
Arithmetic Operators
They are used to perform simple arithmetic operations on primitive
data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction

By Jagadish Sahoo
Unary Operators
Unary operators need only one operand. They are used to increment,
decrement or negate a value.
• – :Unary minus, used for negating the values.
• + :Unary plus, indicates positive value (numbers are positive without
this, however). It performs an automatic conversion to int when the
type of its operand is byte, char, or short. This is called unary numeric
promotion.
• ++ :Increment operator, used for incrementing the value by 1.
• -- : Decrement operator, used for decrementing the value by 1.

By Jagadish Sahoo
There are two varieties of increment operator.
• Post-Increment : Value is first used for computing the result and then
incremented.
• Pre-Increment : Value is incremented first and then result is
computed.
There are two varieties of decrement operator.
• Post-decrement : Value is first used for computing the result and then
decremented.
• Pre-Decrement : Value is decremented first and then result is
computed.

• ! : Logical not operator, used for inverting a boolean value.

By Jagadish Sahoo
Assignment Operator
• =’ Assignment operator is used to assign a value to any variable.
• It has a right to left associativity, i.e value given on right hand side of
operator is assigned to the variable on the left and therefore right
hand side value must be declared before using it or should be a
constant.
• Syntax :
variable = value;

By Jagadish Sahoo
• In many cases assignment operator can be combined with other
operators to build a shorter version of statement called Compound
Statement.
• For example, instead of a = a+5, we can write a += 5.
• +=, for adding left operand with right operand and then assigning it to
variable on the left.
• -=, for subtracting left operand with right operand and then assigning
it to variable on the left.
• *=, for multiplying left operand with right operand and then assigning
it to variable on the left.
• /=, for dividing left operand with right operand and then assigning it
to variable on the left.
• %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.

By Jagadish Sahoo
Relational Operators
• These operators are used to check for relations like equality, greater
than, less than.
• They return boolean result after the comparison and are extensively
used in looping statements as well as conditional if else statements.
• Syntax :
variable relation_operator value

By Jagadish Sahoo
• ==, Equal to : returns true if left hand side is equal to right hand side.
• !=, Not Equal to : returns true if left hand side is not equal to right
hand side.
• <, less than : returns true if left hand side is less than right hand side.
• <=, less than or equal to : returns true if left hand side is less than or
equal to right hand side.
• >, Greater than : returns true if left hand side is greater than right
hand side.
• >=, Greater than or equal to: returns true if left hand side is greater
than or equal to right hand side.

By Jagadish Sahoo
Logical Operators
• These operators are used to perform “logical AND” and “logical OR”
operation, i.e. the function similar to AND gate and OR gate in digital
electronics.
• The second condition is not evaluated if the first one is false, i.e. it has
a short-circuiting effect. Used extensively to test for several
conditions for making a decision.
• Conditional operators are-
1. &&, Logical AND : returns true when both conditions are true.
2. ||, Logical OR : returns true if at least one condition is true.

By Jagadish Sahoo
Ternary operator
• Ternary operator is a shorthand version of if-else statement. It has
three operands and hence the name ternary.
• Syntax :
condition ? if true : if false

By Jagadish Sahoo
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b)? (a > c)? a:c (b > c)? b: c);
System.out.println("Max of three numbers = "
+ result);
}
}

By Jagadish Sahoo
Bitwise Operators
These operators are used to perform manipulation of individual bits of
a number. They can be used with any of the integer types
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit by bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which
returns the one’s compliment representation of the input value, i.e.
with all bits inversed.

By Jagadish Sahoo
Shift Operators
• These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively.
• They can be used when we have to multiply or divide a number by
two.
• Syntax
number shift_op number_of_places_to_shift;

By Jagadish Sahoo
• <<, Left shift operator: shifts the bits of the number to the left and
fills 0 on voids left as a result. Similar effect as of multiplying the
number with some power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit depends on
the sign of initial number. Similar effect as of dividing the number
with some power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to
the right and fills 0 on voids left as a result. The leftmost bit is set to
0.

By Jagadish Sahoo
instance of operator
• Instance of operator is used for type checking. It can be used to test if
an object is an instance of a class, a subclass or an interface.
• Syntax :
object instance of class/subclass/interface

By Jagadish Sahoo
class operators {
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

By Jagadish Sahoo
class Person {
}

class Boy extends Person implements MyInterface {


}

interface MyInterface {
}

By Jagadish Sahoo
Non-Primitive Data Type or Reference Data
Types
• The Reference Data Types will contain a memory address of variable
value because the reference types won’t store the variable value
directly in memory.
• Example: strings, objects, arrays, etc.
• String: Strings are defined as an array of characters. The difference
between a character array and a string in Java is, the string is
designed to hold a sequence of characters in a single variable
whereas, a character array is a collection of separate char type
entities.
• Unlike C/C++, Java strings are not terminated with a null character.
By Jagadish Sahoo
• Syntax :
<String_Type> <string_variable> = “<sequence_of_string>”;
Example :
// Declare String without using new operator
String s = “Jagadish";

// Declare String using new operator


String s1 = new String(“Jagadish");

By Jagadish Sahoo
• Class: A class is a user-defined blueprint or prototype from which
objects are created. It represents the set of properties or methods
that are common to all objects of one type. In general, class
declarations can include these components, in order:
• Modifiers: A class can be public or has default access
• Class name: The name should begin with a initial letter (capitalized by
convention).
• Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass)
one parent.
• Interfaces(if any): A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
• Body: The class body surrounded by braces, { }.
By Jagadish Sahoo
• Object: It is a basic unit of Object-Oriented Programming and
represents the real-life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. An object
consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects
the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object
to interact with other objects.

By Jagadish Sahoo
• Interface: Like a class, an interface can have methods and variables,
but the methods declared in an interface are by default abstract (only
method signature, nobody).
• Interfaces specify what a class must do and not how. It is the
blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and
any class implementing Player must be able to (or must implement)
move(). So it specifies a set of methods that the class has to
implement.
• If a class implements an interface and does not provide method
bodies for all functions specified in the interface, then the class must
be declared abstract.

By Jagadish Sahoo
• Array: An array is a group of like-typed variables that are referred to by a
common name. Arrays in Java work differently than they do in C/C++. The
following are some important points about Java arrays. In Java, all arrays
are dynamically allocated.

• Since arrays are objects in Java, we can find their length using function
length. This is different from C/C++ where we find length using size.
• 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 has 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.

By Jagadish Sahoo
Ways to read input from console in Java
• In Java, there are four different ways for reading input from the user
in the command line environment(console).

1.Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
4. Using Command line argument

By Jagadish Sahoo
Using Buffered Reader Class
• This is the Java classical method to take input, Introduced in JDK1.0.
This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the command
line.
• The input is buffered for efficient reading.
• The wrapping code is hard to remember.
• To read other types, we use functions like Integer.parseInt(),
Double.parseDouble(). To read multiple values, we use split().

By Jagadish Sahoo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// Reading data using readLine


String name = reader.readLine();

// Printing the read line


System.out.println(name);
}
}

By Jagadish Sahoo
Using Scanner Class
• This is probably the most preferred method to take input. The main
purpose of the Scanner class is to parse primitive types and strings
using regular expressions, however, it is also can be used to read
input from the user in the command line.
• Convenient methods for parsing primitives (nextInt(), nextFloat(), …)
from the tokenized input.
• Regular expressions can be used to find tokens.

By Jagadish Sahoo
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
// closing scanner
in.close();
}
}

By Jagadish Sahoo
Difference between Scanner and BufferReader
Class in Java
java.util.Scanner class is a simple text Java.io.BufferedReader class reads text
scanner which can parse primitive types from a character-input stream,
and strings. It internally uses regular buffering characters so as to provide for
expressions to read different types. the efficient reading of sequence of
characters

Issue with Scanner when nextLine() is used after nextXXX()

By Jagadish Sahoo
import java.util.Scanner;
class Differ
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer");
int a = scn.nextInt();
System.out.println("Enter a String");
String b = scn.nextLine();
System.out.printf("You have entered:- "
+ a + " " + "and name as " + b);
}
}

By Jagadish Sahoo
import java.io.*;
class Differ
{
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a +
" and name as " + b);
}
}

By Jagadish Sahoo
• In Scanner class if we call nextLine() method after any one of the
seven nextXXX() method then the nextLine() does not read values
from console and cursor will not come into console it will skip that
step. The nextXXX() methods are nextInt(), nextFloat(), nextByte(),
nextShort(), nextDouble(), nextLong(), next().
• In BufferReader class there is no such type of problem. This problem
occurs only for Scanner class, due to nextXXX() methods ignore
newline character and nextLine() only reads till first newline
character. If we use one more call of nextLine() method between
nextXXX() and nextLine(), then this problem will not occur because
nextLine() will consume the newline character. This problem is same
as scanf() followed by gets() in C/C++.

By Jagadish Sahoo
• This problem can also be solved by using next() instead of nextLine() for taking input of
strings
import java.util.Scanner;
class Differ {
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter an integer");
int a = scn.nextInt();
scn.nextLine();
System.out.println("Enter a String");
String b = scn.next();
String c = scn.next();
int d = scn.nextInt();
System.out.printf("You have entered:- " + a + " " + "and name as " + b + " and " + c + d);
}
}
By Jagadish Sahoo
• BufferedReader is synchronous while Scanner is not. BufferedReader
should be used if we are working with multiple threads.
• BufferedReader has significantly larger buffer memory than Scanner.
• The Scanner has a little buffer (1KB char buffer) as opposed to the
BufferedReader (8KB byte buffer), but it’s more than enough.
• BufferedReader is a bit faster as compared to scanner because
scanner does parsing of input data and BufferedReader simply reads
sequence of characters.

By Jagadish Sahoo
Using Console Class
• It has been becoming a preferred way for reading user’s input from
the command line. In addition, it can be used for reading password-
like input without echoing the characters entered by the user; the
format string syntax can also be used (like System.out.printf()).
• Reading password without echoing the entered characters.
• Format string syntax can be used.
• Does not work in non-interactive environment (such as in an IDE)

By Jagadish Sahoo
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println("You entered string " + name);


}
}

By Jagadish Sahoo
Using Command line argument
• Most used user input for competitive coding. The command-line
arguments are stored in the String format. The parseInt method of
the Integer class converts string argument into Integer.
• Similarly, for float and others during execution.
• The usage of args[] comes into existence in this input form. The
passing of information takes place during the program run.
• The command line is given to args[]. These programs have to be run
on cmd.

By Jagadish Sahoo
class Hello {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if (args.length > 0) {
System.out.println(
"The command line arguments are:");

// iterating the args array and printing


// the command line arguments
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line "
+ "arguments found.");
}
}

By Jagadish Sahoo
// Java program to demonstrate working of split(regex,
// limit) with small limit.
public class GFG {
public static void main(String args[])
{
String str = “jagadish@kumar@sahoo";
String[] arrOfStr = str.split("@", 2);

for (String a : arrOfStr)


System.out.println(a);
}
}

By Jagadish Sahoo
Flow Control
• Decision Making in Java
• Decision Making in programming is similar to decision making in real
life. In programming also we face some situations where we want a
certain block of code to be executed when some condition is fulfilled.
• A programming language uses control statements to control the flow
of execution of program based on certain conditions. These are used
to cause the flow of execution to advance and branch based on
changes to the state of a program.

By Jagadish Sahoo
Java’s Selection statements:
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return

By Jagadish Sahoo
if: 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 i.e 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
}

By Jagadish Sahoo
• Here, condition after evaluation will be either true or false. if
statement accepts boolean values – if the value is true then it will
execute the block of statements under it.
• If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition )
then by default if statement will consider the immediate one
statement to be inside its block.
• Example :
if(condition)
statement1;
statement2;

By Jagadish Sahoo
• if-else: The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t. But
what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

By Jagadish Sahoo
• nested-if: A nested if is an if statement that is the target of another if
or else. Nested if statements means an if statement inside an if
statement. Java allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

By Jagadish Sahoo
• if-else-if ladder: Here, a user can decide among multiple options.The
if statements are executed from the top down. As soon as one of 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.
if (condition1)
statement;
else if (condition2)
statement;
.
.
else
statement;

By Jagadish Sahoo
• switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

By Jagadish Sahoo
• Expression can be of type byte, short, int char or an enumeration.
Beginning with JDK7, expression can also be of type String.
• Dulplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a
statement sequence.
• The break statement is optional. If omitted, execution will continue
on into the next case.

By Jagadish Sahoo
• jump: Java supports three jump statement: break, continue and
return. These three statements transfer control to other part of the
program.
• Break: In Java, break is majorly used for:
1. Terminate a sequence in a switch statement
2. To exit a loop.
3. Used as a “civilized” form of goto.
Using break, we can force immediate termination of a loop, bypassing
the conditional expression and any remaining code in the body of the
loop.
Note: Break, when used inside a set of nested loops, will only break out
of the innermost loop.

By Jagadish Sahoo
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;

System.out.println("i: " + i);


}
System.out.println("Loop complete.");
}
}

By Jagadish Sahoo
• Java does not have a goto statement because it provides a way to
branch in an arbitrary and unstructured manner. Java uses label. A
Label is use to identifies a block of code.
label:
{
statement1;
statement2;
statement3;
.
.
}

By Jagadish Sahoo
• break statement can be use to jump out of target block.
• Note: You cannot break to any label which is not defined for an
enclosing block.
break label;

By Jagadish Sahoo
Continue
• Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.

By Jagadish Sahoo
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}
By Jagadish Sahoo
Return
• The return statement is used to explicitly return from a method. That is, it causes a program control to
transfer back to the caller of the method.
• class Return
• {
• public static void main(String args[])
• {
• boolean t = true;
• System.out.println("Before the return.");

• if (t)
• return;

• // Compiler will bypass every statement
• // after return
• System.out.println("This won't execute.");
• }
• }
By Jagadish Sahoo
Loops in Java
• Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true.
• Java provides three ways for executing the loops. While all the ways
provide similar basic functionality, they differ in their syntax and
condition checking time.
• 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.

By Jagadish Sahoo
while (boolean condition)
{
loop statements...
}
• 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. For this reason it is also
called Entry control loop
• Once the condition is evaluated to true, the statements in the loop
body are executed. 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.

By Jagadish Sahoo
for loop
• for loop: for loop provides a concise way of writing the loop structure.
Unlike a while loop, a for statement consumes the initialization,
condition and increment/decrement in one line thereby providing a
shorter, easy to debug structure of looping.
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}

By Jagadish Sahoo
• 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.

By Jagadish Sahoo
Enhanced For loop
• Java also includes another version of for loop introduced in Java 5.
Enhanced for loop provides a simpler way to iterate through the
elements of a collection or array. It is inflexible and should be used
only when there is a need to iterate through the elements in
sequential manner without knowing the index of currently processed
element.
• The object/variable is immutable when enhanced for loop is used i.e
it ensures that the values in the array can not be modified, so it can
be said as read only loop where you can’t update the values as
opposite to other loops where values can be modified.

By Jagadish Sahoo
for (T element:Collection obj/array)
{
statement(s)
}

By Jagadish Sahoo
public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};

//enhanced for loop


for (String x:array)
{
System.out.println(x);
}

/* for loop for same function


for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
By Jagadish Sahoo
do-while
• do while loop is similar to while loop with only difference that it
checks for condition after executing the statements, and therefore is
an example of Exit Control Loop.
do
{
statements..
}
while (condition);

By Jagadish Sahoo
• 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.

By Jagadish Sahoo
Pitfalls of Loops
• Infinite loop: One of the most common mistakes while implementing
any sort of looping is that that it may not ever exit, that is the loop
runs for infinite time. This happens when the condition fails for some
reason.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}

By Jagadish Sahoo
• Another pitfall is that you might be adding something into you collection object
through loop and you can run out of memory. If you try and execute the below
program, after some time, out of memory exception will be thrown.
import java.util.ArrayList;
public class Integer1
{
public static void main(String[] args)
{
ArrayList<Integer> ar = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++)
{
ar.add(i);
}
}
• }

By Jagadish Sahoo
Arrays in Java
• An array is a group of like-typed variables that are referred to by a
common name.
• Arrays in Java work differently than they do in C/C++.
• Following are some important points about Java arrays.

By Jagadish Sahoo
• In Java all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using the
object property length. This is different from C/C++ where we find
length using sizeof.
• 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 or short value and not
long.
• The direct superclass of an array type is Object.

By Jagadish Sahoo
• Array can contain primitives (int, char, etc.) as well as object (or non-
primitive) references of a class depending on the definition of the
array.
• In case of primitive data types, the actual values are stored in
contiguous memory locations.

By Jagadish Sahoo
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-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.
Like an array of integers, we can also create an array of other primitive
data types like char, float, double, etc. or user-defined data types
(objects of a class). Thus, the element type for the array determines
what type of data the array will hold.

By Jagadish Sahoo
int intArray[]; or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object

By Jagadish Sahoo
• Although the first declaration above establishes the fact that intArray
is an array variable, no actual array exists. It merely tells the compiler
that this variable (intArray) will hold an array of the integer type. To
link intArray with an actual, physical array of integers, you must
allocate one using new and assign it to intArray.

By Jagadish Sahoo
Instantiating an Array in Java
• When an array is declared, only a reference of array is created. To
actually create or give memory to array, you create an array in the
following manner
The general form of new as it applies to one-dimensional arrays
appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the
number of elements in the array, and var-name is the name of array
variable that is linked to the array. That is, to use new to allocate an
array, you must specify the type and number of elements to allocate.

By Jagadish Sahoo
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
The elements in the array allocated by new will automatically be
initialized to zero (for numeric types), false (for boolean), or null (for
reference types).
Obtaining an array is a two-step process. First, you must declare a
variable of the desired array type. Second, you must allocate the
memory that will hold the array, using new, and assign it to the array
variable. Thus, in Java all arrays are dynamically allocated.

By Jagadish Sahoo
Array Literal
• In a situation, where the size of the array and variables of array are
already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of
Java

By Jagadish Sahoo
Accessing Java Array Elements using for Loop
• Each element in the array is accessed via its index. The index begins
with 0 and ends at (total array size)-1. All the elements of array can be
accessed using Java for Loop.
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);

By Jagadish Sahoo
Arrays of Objects
• An array of objects is created just like an array of primitive type data
items in the following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of
student class in which the address of seven Student objects can be
stored.The Student objects have to be instantiated using the
constructor of the Student class and their references should be
assigned to the array elements in the following way.

By Jagadish Sahoo
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
public class GFG
{
public static void main (String[] args)
{
Student[] arr;
arr = new Student[5];
arr[0] = new Student(1,"aman");
arr[1] = new Student(2,"vaibhav");
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");

By Jagadish Sahoo
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}

By Jagadish Sahoo
What happens if we try to access element outside the array size?
• JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed
with an illegal index. The index is either negative or greater than or equal to size of array.
class GFG
{
public static void main (String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

for (int i = 0; i <= arr.length; i++)


System.out.println(arr[i]);
}
}

By Jagadish Sahoo
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.
Example
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

By Jagadish Sahoo
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

By Jagadish Sahoo
By Jagadish Sahoo
Passing Arrays to Methods
• Like variables, we can also pass arrays to methods.For example, below
program pass array to method sum for calculating sum of array’s
values.

By Jagadish Sahoo
class Test
{
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
sum(arr);
}

public static void sum(int[] arr)


{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}

By Jagadish Sahoo
Returning Arrays from Methods
• As usual, a method can also return an array. For example, below program returns
an array from method m1.
class Test
{
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{
return new int[]{1,2,3};
}
} By Jagadish Sahoo
Class Objects for Arrays
• Every array has an associated Class object, shared with all other arrays with the same component type.
class Test
{
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];

// array of Strings
String[] strArray = new String[3];

System.out.println(intArray.getClass());
System.out.println(intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}

By Jagadish Sahoo
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;

By Jagadish Sahoo
• The string “[I” is the run-time type signature for the class object
“array with component type int“.
• The only direct superclass of any array type is java.lang.Object.
• The string “[B” is the run-time type signature for the class object
“array with component type byte“.
• The string “[S” is the run-time type signature for the class object
“array with component type short“.
• The string “[L” is the run-time type signature for the class object
“array with component type of a Class”. The Class name is then
followed.

By Jagadish Sahoo
Array Members
• arrays are object of a class and direct superclass of arrays is class
Object.The members of an array type are all of the following:
1. The public final field length, which contains the number of
components of the array. length may be positive or zero.
2. All the members inherited from class Object; the only method of
Object that is not inherited is its clone method.
3. The public method clone(), which overrides clone method in class
Object and throws no checked exceptions.

By Jagadish Sahoo
Cloning of arrays
• When you clone a single dimensional array, such as Object[], a “deep copy” is performed with the new array
containing copies of the original array’s elements as opposed to references.
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
int cloneArray[] = intArray.clone();
// will print false as deep copy is created
// for one-dimensional array
System.out.println(intArray == cloneArray);
for (int i = 0; i < cloneArray.length; i++) {
System.out.print(cloneArray[i]+" ");
}
}
}

By Jagadish Sahoo
By Jagadish Sahoo
• A clone of a multi-dimensional array (like Object[][]) is a “shallow copy” however, which
is to say that it creates only a single new array with each element array a reference to an
original element array, but subarrays are shared.
class Test
{
public static void main(String args[])
{
int intArray[][] = {{1,2,3},{4,5}};
int cloneArray[][] = intArray.clone();
/ / will print false
System.out.println(intArray == cloneArray);
// will print true as shallow copy is created
// i.e. sub-arrays are shared
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}

By Jagadish Sahoo
By Jagadish Sahoo
Classes and Objects in Java
• A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common
to all objects of one type. In general, class declarations can include these
components, in order:
• Modifiers: A class can be public or has default access.
• class keyword: class keyword is used to create a class.
• Class name: The name should begin with an initial letter (capitalized by
convention).
• Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
• Interfaces(if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
• Body: The class body surrounded by braces, { }.
By Jagadish Sahoo
Access specifiers for classes or interfaces in Java
• In Java, methods and data members of a class/interface can have one
of the following four access specifiers. The access specifiers are listed
according to their restrictiveness order.
1) private (accessible within the class where defined)
2) default or package private (when no access specifier is specified)
3) protected
4) public (accessible from any class)

By Jagadish Sahoo
The classes and interfaces themselves can have only two access
specifiers when declared outside any other class.
1) Public
2) default (when no access specifier is specified)
We cannot declare class/interface with private or protected access
specifiers. For example, following program fails in compilation.
protected class Test {}

public class Main {


public static void main(String args[]) {
}
}
Note : Nested interfaces and classes
By Jagadishcan
Sahoo have all access specifiers.
Object
• It is a basic unit of Object-Oriented Programming and represents the
real life entities. A typical Java program creates many objects,
interact by invoking methods. An object consists of :
• State: It is represented by attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by methods of an object. It also reflects
the response of an object with other objects.
• Identity: It gives a unique name to an object and enables one object
to interact with other objects.

By Jagadish Sahoo
Example of an object: dog

By Jagadish Sahoo
• Objects correspond to things found in the real world.
• For example, a graphics program may have objects such as “circle”,
“square”, “menu”.
• An online shopping system might have objects such as “shopping
cart”, “customer”, and “product”.

By Jagadish Sahoo
Declaring Objects (Also called instantiating a class)
• When an object of a class is created, the class is said to be
instantiated.
• All the instances share the attributes and the behavior of the class.
• But the values of those attributes, i.e. the state are unique for each
object.
• A single class may have any number of instances.

By Jagadish Sahoo
By Jagadish Sahoo
• As we declare variables like (type name;). This notifies the compiler
that we will use name to refer to data whose type is type.
• With a primitive variable, this declaration also reserves the proper
amount of memory for the variable.
• So for reference variable, type must be strictly a concrete class name.
• In general, we can’t create objects of an abstract class or an interface.

By Jagadish Sahoo
Example
Dog tuffy;

• if we declare reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to
it. Simply declaring a reference variable does not create an object.

By Jagadish Sahoo
Initializing an object
• The new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator
also invokes the class constructor.

By Jagadish Sahoo
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed, int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

By Jagadish Sahoo
public String getName()
{
return name;
}
public String getBreed()
{
return breed;
}
public int getAge()
{
return age;
}
public String getColor()
{
return color;
}

By Jagadish Sahoo
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}
public static void main(String[] args)
{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

By Jagadish Sahoo
• This class contains a single constructor. We can recognize a
constructor because its declaration uses the same name as the class
and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments.
The constructor in the Dog class takes four arguments. The following
statement provides “tuffy”,”papillon”,5,”white” as values for those
arguments:
Dog tuffy = new Dog("tuffy","papillon",5, "white");

By Jagadish Sahoo
By Jagadish Sahoo
• All classes have at least one constructor. If a class does not explicitly
declare any, the Java compiler automatically provides a no-argument
constructor, also called the default constructor.
• This default constructor calls the class parent’s no-argument
constructor (as it contain only one statement i.e super();), or the
Object class constructor if the class has no other parent (as Object
class is parent of all classes either directly or indirectly).

By Jagadish Sahoo
Ways to create object of a class
• There are four ways to create objects in java.
• Strictly speaking there is only one way(by using new keyword),and
the rest internally use new keyword.

By Jagadish Sahoo
Using new keyword
• It is the most common and general way to create object in java.
Example:
// creating object of class Test
Test t = new Test();

By Jagadish Sahoo
Using Class.forName(String className) method:
• There is a pre-defined class in java.lang package with name Class. The
forName(String className) method returns the Class object
associated with the class with the given string name.
• We have to give the fully qualified name for a class.
• On calling new Instance() method on this Class object returns new
instance of the class with the given string name.
• // creating object of public class Test
• // consider class Test present in com.p1 package
• Test obj = (Test)Class.forName("com.p1.Test").newInstance();

By Jagadish Sahoo
Using clone() method
• clone() method is present in Object class. It creates and returns a
copy of the object.
// creating object of class Test
Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();

By Jagadish Sahoo
Deserialization
• De-serialization is technique of reading an object from the saved state
in a file.
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

By Jagadish Sahoo
Creating multiple objects by one type only
• In real-time, we need different objects of a class in different methods.
Creating a number of references for storing them is not a good
practice and therefore we declare a static reference variable and use
it whenever required. In this case, wastage of memory is less. The
objects that are not referenced anymore will be destroyed by
Garbage Collector of java.
• Example:
Test test = new Test();
test = new Test();

By Jagadish Sahoo
• In inheritance system, we use parent class reference variable to store a sub-class
object. In this case, we can switch into different subclass objects using same
referenced variable. Example:
class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{
// using Dog object
Animal obj = new Dog();

// using Cat object


obj = new Cat();
}
By Jagadish Sahoo
Anonymous objects
• Anonymous objects are the objects that are instantiated but are not
stored in a reference variable.
1. They are used for immediate method calling.
2. They will be destroyed after method calling.
3. They are widely used in different libraries. For example, in AWT
libraries, they are used to perform some action on capturing an
event(eg a key press).

By Jagadish Sahoo
Methods in Java
• A method is a collection of statements that perform some specific
task and return the result to the caller.
• A method can perform some specific task without returning anything.
• Methods allow us to reuse the code without retyping the code.
• In Java, every method must be part of some class which is different
from languages like C, C++, and Python.

By Jagadish Sahoo
Method Declaration
• In general, method declarations has six components :
1. Modifier-: Defines access type of the method i.e. from where it can
be accessed in your application. In Java, there 4 type of the access
specifiers.
• public: accessible in all class in your application.
• protected: accessible within the class in which it is defined and in its
subclass(es)
• private: accessible only within the class in which it is defined.
• default (declared/defined without using any modifier) : accessible
within same class and package within which its class is defined.

By Jagadish Sahoo
2. The return type : The data type of the value returned by the
method or void if does not return a value.
3. Method Name : the rules for field names apply to method names as
well, but the convention is a little different.
4. Parameter list : Comma separated list of the input parameters are
defined, preceded with their data type, within the enclosed
parenthesis. If there are no parameters, you must use empty
parentheses ().
5. Exception list : The exceptions you expect by the method can throw,
you can specify these exception(s).
6. Method body : it is enclosed between braces. The code you need to
be executed to perform your intended operations.

By Jagadish Sahoo
By Jagadish Sahoo
• Method signature: It consists of the method name and a parameter
list (number of parameters, type of the parameters and order of the
parameters). The return type and exceptions are not considered as
part of it.
max(int x, int y)
How to name a Method?: A method name is typically a single word
that should be a verb in lowercase or multi-word, that begins with
a verb in lowercase followed by adjective, noun….. After the first word,
first letter of each word should be capitalized. For example, findSum,
computeMax, setX and getX

By Jagadish Sahoo
Calling a method
• The method needs to be called for using its functionality.
• A method returns to the code that invoked it when:

1. It completes all the statements in the method


2. It reaches a return statement
3. Throws an exception

By Jagadish Sahoo
Call by Value
• Pass By Value: Changes made to formal parameter do not get
transmitted back to the caller. Any modifications to the formal
parameter variable inside the called function or method affect only
the separate storage location and will not be reflected in the actual
parameter in the calling environment. This method is also called as
call by value.
• Java in fact is strictly call by value.

By Jagadish Sahoo
class CallByValue {
public static void Example(int x, int y)
{
x++;
y++;
}
}
public class Main {
public static void main(String[] args)
{
int a = 10;
int b = 20;
CallByValue object = new CallByValue();
System.out.println("Value of a: " + a + " & b: " + b);
object.Example(a, b);
System.out.println("Value of a: “ + a + " & b: " + b);
}
}

By Jagadish Sahoo
Call by reference(aliasing)
• Changes made to formal parameter do get transmitted back to the
caller through parameter passing.
• Any changes to the formal parameter are reflected in the actual
parameter in the calling environment as formal parameter receives a
reference (or pointer) to the actual data.
• This method is also called as call by reference. This method is efficient
in both time and space.

By Jagadish Sahoo
class CallByReference {
int a, b;
CallByReference(int x, int y)
{
a = x;
b = y;
}
void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20;
}
}

By Jagadish Sahoo
public class Main {
public static void main(String[] args)
{
CallByReference object = new CallByReference(10, 20);
System.out.println("Value of a: “ + object.a + " & b: “ + object.b);
object.ChangeValue(object);
System.out.println("Value of a: “ + object.a + " & b: “ + object.b);
}
}

By Jagadish Sahoo
• when we pass a reference, a new reference variable to the same
object is created.
• So we can only change members of the object whose reference is
passed.
• We cannot change the reference to refer to some other object as the
received reference is a copy of the original reference.

By Jagadish Sahoo
• Methods calls are implemented through stack.
• Whenever a method is called a stack frame is created within the stack
area and after that the arguments passed to and the local variables
and value to be returned by this calling method are stored in this
stack frame and when execution of the called method is finished, the
allocated stack frame would be deleted.
• There is a stack pointer register that tracks the top of the stack which
is adjusted accordingly.

By Jagadish Sahoo
Returning Multiple values in Java
class Test {
static int[] getSumAndSub(int a, int b)
{
int[] ans = new int[2];
ans[0] = a + b;
ans[1] = a - b;
return ans;
}
public static void main(String[] args)
{
int[] ans = getSumAndSub(100, 50);
System.out.println("Sum = " + ans[0]);
System.out.println("Sub = " + ans[1]);
}
}
By Jagadish Sahoo
If returned elements are of different types
• Using Pair (If there are only two returned values)
import javafx.util.Pair;
class GfG {
public static Pair<Integer, String> getTwo()
{
return new Pair<Integer, String>(10, “Jagadish Sahoo");
}
// Return multiple values from a method in Java 8
public static void main(String[] args)
{
Pair<Integer, String> p = getTwo();
System.out.println(p.getKey() + " " + p.getValue());
}
}

By Jagadish Sahoo
If there are more than two returned values
• We can encapsulate all returned types into a class and then return an
object of that class.
class MultiDivAdd {
int mul; // To store multiplication
double div; // To store division
int add; // To store addition
MultiDivAdd(int m, double d, int a)
{
mul = m;
div = d;
add = a;
}
}
By Jagadish Sahoo
class Test {
static MultiDivAdd getMultDivAdd(int a, int b)
{
// Returning multiple values of different
// types by returning an object
return new MultiDivAdd(a * b, (double)a / b, (a + b));
}
public static void main(String[] args)
{
MultiDivAdd ans = getMultDivAdd(10, 20);
System.out.println("Multiplication = " + ans.mul);
System.out.println("Division = " + ans.div);
System.out.println("Addition = " + ans.add);
}
}

By Jagadish Sahoo
Returning list of Object Class
import java.util.*;
class GfG {
public static List<Object> getDetails()
{
String name = "Geek";
int age = 35;
char gender = 'M';
return Arrays.asList(name, age, gender);
}
public static void main(String[] args)
{
List<Object> person = getDetails();
System.out.println(person);
}
}
By Jagadish Sahoo
Method Overloading in Java
• Java can distinguish the methods with different method signatures.
i.e. the methods can have the same name but with different
parameters list (i.e. the number of the parameters, the order of the
parameters, and data types of the parameters) within the same class.
• Overloaded methods are differentiated based on the number and
type of the parameters passed as an argument to the methods.
• You can not define more than one method with the same name,
Order and the type of the arguments. It would be a compiler error.
• The compiler does not consider the return type while differentiating
the overloaded method. But you cannot declare two methods with
the same signature and different return type. It will throw a compile-
time error.

By Jagadish Sahoo
Why do we need Method Overloading?
• if we need to do some kind of the operation with different ways i.e.
for different inputs.
• For example , we are doing the addition operation for different
inputs. It is hard to find many meaningful names for a single action.

By Jagadish Sahoo
Different ways of doing overloading methods
Method overloading can be done by changing:
• The number of parameters in methods.
• The data types of the parameters of methods.
• The Order of the parameters of methods.

By Jagadish Sahoo
Method 1: By changing the number of parameters.
import java.io.*;
class Addition {
public int add(int a, int b)
{
int sum = a + b;
return sum;
}
public int add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
}
class GFG {
public static void main(String[] args)
{
Addition ob = new Addition();
int sum1 = ob.add(1, 2);
System.out.println("sum of the two integer value :" + sum1);
int sum2 = ob.add(1, 2, 3);
System.out.println( "sum of the three integer value :" + sum2);
}
}

By Jagadish Sahoo
Method 2: By changing the Data types of the parameters
import java.io.*;
class Addition {
public int add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}
public double add(double a, double b, double c)
{
double sum = a + b + c;
return sum;
}
}
class GFG {
public static void main(String[] args)
{
Addition ob = new Addition();
int sum2 = ob.add(1, 2, 3);
System.out.println( "sum of the three integer value :" + sum2);
double sum3 = ob.add(1.0, 2.0, 3.0);
System.out.println("sum of the three double value :“ + sum3);
}
}

By Jagadish Sahoo
Method 3: By changing the Order of the parameters
import java.io.*;
class Para {
public void getIdentity(String name, int id)
{
System.out.println(“Name :" + name + " " + "Id :" + id);
}
public void getIdentity(int id, String name)
{
System.out.println("Id :" + id + " " + “Name :" + name);
}
}
class GFG {
public static void main(String[] args)
{
Para p = new Para();
p.getIdentity("Mohit", 1);
p.getIdentity(2, "shubham");
}
}

By Jagadish Sahoo
What happens when method signature is the
same and the return type is different?
• The compiler will give an error as the return value alone is not
sufficient for the compiler to figure out which function it has to call.
• Only if both methods have different parameter types (so, they have a
different signature), then Method overloading is possible.

By Jagadish Sahoo
import java.io.*;
class Addition {
public int add(int a, int b)
{
int sum = a + b;
return sum;
}
public double add(int a, int b)
{
double sum = a + b + 0.0;
return sum;
}
}
class GFG {
public static void main(String[] args)
{
try {
Addition ob = new Addition();
int sum1 = ob.add(1, 2);
System.out.println("sum of the two integer value :" + sum1);
int sum2 = ob.add(1, 2);
System.out.println("sum of the three integer value :" + sum2);
}
catch (Exception e) {
System.out.println(e);
}
}
}

By Jagadish Sahoo
Scope of Variables In Java
• Scope of a variable is the part of the program where the variable is
accessible. Like C/C++, in Java, all identifiers are lexically (or statically)
scoped, i.e.scope of a variable can determined at compile time.
• Java programs are organized in the form of classes. Every class is part
of some package.

By Jagadish Sahoo
Scope rules
• Member Variables (Class Level Scope)
• Local Variables (Method Level Scope)
• Loop Variables (Block Scope)

By Jagadish Sahoo
Member Variables (Class Level Scope)
• These variables must be declared inside class (outside any function). They
can be directly accessed anywhere in class.
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}

By Jagadish Sahoo
• We can declare class variables anywhere in class, but outside
methods.
• Access specified of member variables doesn’t affect scope of them
within a class.
• Member variables can be accessed outside a class with following
rules

By Jagadish Sahoo
Local Variables (Method Level Scope)
• Variables declared inside a method have method level scope and
can’t be accessed outside the method.
• Local variables don’t exist after method’s execution is over.
public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}

By Jagadish Sahoo
class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}
this keyword to differentiate between the local and class variables.

By Jagadish Sahoo
public class Test
{
static int x = 11;
private int y = 33;
public void method1(int x)
{
Test t = new Test();
this.x = 22;
y = 44;
System.out.println("Test.x: " + Test.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}

By Jagadish Sahoo
Loop Variables (Block Scope)
• A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets
only.
public class Test
{
public static void main(String args[])
{
{
int x = 10;
System.out.println(x);
}
// Uncommenting below line would produce error since variable x is out of scope.

// System.out.println(x);
}
}

By Jagadish Sahoo
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}

// Will produce error


System.out.println(x);
}
}
By Jagadish Sahoo
Predict the O/P
class Test
{
public static void main(String args[])
{
int a = 5;
for (int a = 0; a < 5; a++)
{
System.out.println(a);
}
}
}
In C++, it will run. But in java it is an error because in java, the name of
the variable of inner and outer loop must be different.
By Jagadish Sahoo
Important Points about Variable scope in Java
• In general, a set of curly brackets { } defines a scope.
• In Java we can usually access a variable as long as it was defined
within the same set of brackets as the code we are writing or within
any curly brackets inside of the curly brackets where the variable was
defined.
• Any variable defined in a class outside of any method can be used by
all member methods.
• When a method has the same local variable as a member, “this”
keyword can be used to reference the current class variable.
• For a variable to be read after the termination of a loop, It must be
declared before the body of the loop.

By Jagadish Sahoo
Constructors in Java
• Constructors are used to initialize the object’s state. Like methods, a
constructor also contains a collection of statements(i.e. instructions)
that are executed at the time of Object creation.
Need of Constructor
Suppose there is a class with the name Box. If we talk about a box class
then it will have some class variables (say length, breadth, and height).
But when it comes to creating its object(i.e Box will now exist in the
computer’s memory), then can a box be there with no value defined for
its dimensions. The answer is no.
So constructors are used to assign values to the class variables at the
time of object creation, either explicitly done by the programmer or by
Java itself (default constructor).

By Jagadish Sahoo
When is a Constructor called?
• Each time an object is created using a new() keyword, at least one
constructor (it could be the default constructor) is invoked to assign
initial values to the data members of the same class.
• A constructor is invoked at the time of object or instance creation. For
Example:

By Jagadish Sahoo
class Hello
{
.......
// A Constructor
Hello() {}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Hello obj = new Hello();

By Jagadish Sahoo
Rules for writing Constructor:
• Constructor(s) of a class must have the same name as the class name
in which it resides.
• A constructor in Java can not be abstract, final, static and
Synchronized.
• Access modifiers can be used in constructor declaration to control its
access i.e which other class can call the constructor.

By Jagadish Sahoo
Types of constructor
1. No-argument constructor(Default constructor)
• A constructor that has no parameter is known as the default
constructor.
• If we don’t define a constructor in a class, then the compiler creates
default constructor(with no arguments) for the class. And if we write
a constructor with arguments or no-arguments then the compiler
does not create a default constructor.
• Default constructor provides the default values to the object like 0,
null, etc. depending on the type.

By Jagadish Sahoo
import java.io.*;
class Myclass
{
int num;
String name;
// this would be invoked while an object
// of that class is created.
Myclass()
{
System.out.println("Constructor called");
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Myclass obj = new Myclass();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(obj.name);
System.out.println(obj.num);
}
}
By Jagadish Sahoo
2. Parameterized Constructor:
• A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with your own
values, then use a parameterized constructor.

By Jagadish Sahoo
import java.io.*;
class Student
{
// data members of the class.
String name;
int id;
// constructor would initialize data members
// with the values of passed arguments while
// object of that class created.
Student(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Student obj = new Student("adam", 1);
System.out.println("Name :" + obj.name +" and Id :" + obj.id);
}
} By Jagadish Sahoo
Does constructor return any value?
• There are no “return value” statements in the constructor, but the
constructor returns the current class instance. We can write ‘return’
inside a constructor.

By Jagadish Sahoo
Constructor Overloading
• Like methods, we can overload constructors for creating objects in
different ways.
• Compiler differentiates constructors on the basis of numbers of
parameters, types of the parameters and order of the parameters.

By Jagadish Sahoo
import java.io.*;
class Paracon
{
Paracon(String name)
{
System.out.println("Constructor with one " +"argument - String : " + name);
}
Paracon(String name, int age)
{
System.out.println("Constructor with two arguments : " + " String and Integer
: " + name + " "+ age);
}
Paracon(long id)
{
System.out.println("Constructor with one argument : " + "Long : " + id);
}
}

By Jagadish Sahoo
class GFG
{
public static void main(String[] args)
{
Paracon obj1 = new Paracon(“Jagadish");
Paracon obj2 = new Paracon(“Aditya", 15);
Paracon obj3 = new Paracon(325114552);
}
}

By Jagadish Sahoo
How constructors are different from methods in Java?
• Constructor(s) must have the same name as the class within which it
defined while it is not necessary for the method in java.
• Constructor(s) do not return any type while method(s) have the
return type or void if does not return any value.
• Constructor is called only once at the time of Object creation while
method(s) can be called any numbers of time.

By Jagadish Sahoo
Copy Constructor in Java
• Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
class Complex {

private double re, im;

// A normal parameterized constructor


public Complex(double re, double im) {
this.re = re;
this.im = im;
}

// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}

// Overriding the toString of Object class


@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}

By Jagadish Sahoo
Constructor Overloading in Java
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box()
{
width = height = depth = 0;
}
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}

By Jagadish Sahoo
public class Test
{
public static void main(String args[])
{
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);
}
}

By Jagadish Sahoo
Using this() in constructor overloading
• this() reference can be used during constructor overloading to call
default constructor implicitly from parameterized constructor.
• this() should be the first statement inside a constructor.

By Jagadish Sahoo
public class Main {

public static void main(String[] args) {


Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call


Complex c2 = new Complex(c1);

// Note that following doesn't involve a copy constructor call as


// non-primitive variables are just references.
Complex c3 = c2;

System.out.println( c2.re + " + " + c2.im );


System.out.println( c2.re + " + " + c2.im );
}
}

By Jagadish Sahoo
class Box
{
double width, height, depth;
int boxNo;
Box(double w, double h, double d, int num)
{
width = w;
height = h;
depth = d;
boxNo = num;
}
Box()
{
width = height = depth = 0;
}
Box(int num)
{
this();
boxNo = num;
}
By Jagadish Sahoo
public static void main(String[] args)
{
Box box1 = new Box(1);
System.out.println(box1.width);
}
}

• we called Box(int num) constructor during object creation using only


box number. By using this() statement inside it, the default
constructor(Box()) is implicitly called from it which will initialize
dimension of Box with 0.

By Jagadish Sahoo
Important points to be taken care while doing
Constructor Overloading
• Constructor calling must be the first statement of constructor in Java.
• If we have defined any parameterized constructor, then compiler will
not create default constructor. and vice versa if we don’t define any
constructor, the compiler creates the default constructor(also known
as no-arg constructor) by default during compilation
• Recursive constructor calling is invalid in java.

By Jagadish Sahoo
Constructors overloading vs Method overloading
• constructor overloading is somewhat similar to method overloading.
If we want to have different ways of initializing an object using
different number of parameters, then we must do constructor
overloading as we do method overloading when we want different
definitions of a method based on different parameters.

By Jagadish Sahoo
Constructor Chaining
• Constructor chaining is the process of calling one constructor from
another constructor with respect to current object.
Constructor chaining can be done in two ways:
• Within same class: It can be done using this() keyword for
constructors in same class
• From base class: by using super() keyword to call constructor from
the base class.

By Jagadish Sahoo
• Constructor chaining occurs through inheritance.
• A sub class constructor’s task is to call super class’s constructor first.
• This ensures that creation of sub class’s object starts with the
initialization of the data members of the super class.
• There could be any numbers of classes in inheritance chain.
• Every constructor calls up the chain till class at the top is reached.

By Jagadish Sahoo
Why do we need constructor chaining ?
• This process is used when we want to perform multiple tasks in a
single constructor rather than creating a code for each task in a single
constructor we create a separate constructor for each task and make
their chain which makes the program more readable.

By Jagadish Sahoo
Constructor Chaining within same class using this() keyword

By Jagadish Sahoo
class Temp
{
Temp()
{
this(5);
System.out.println("The Default constructor");
}
Temp(int x)
{
this(5, 15);
System.out.println(x);
}
Temp(int x, int y)
{
System.out.println(x * y);
}
public static void main(String args[])
{
new Temp();
}
}
By Jagadish Sahoo
Rules of constructor chaining :
• The this() expression should always be the first line of the constructor.
• There should be at-least be one constructor without the this()
keyword (Temp(int x, int y) in previous example).
• Constructor chaining can be achieved in any order.
What happens if we change the order of constructors?
Nothing, Constructor chaining can be achieved in any order

By Jagadish Sahoo
Constructor Chaining to other class using super() keyword
class Base
{
String name;
Base()
{
this("");
System.out.println("No-argument constructor of" + " base class");
}
Base(String name)
{
this.name = name;
System.out.println("Calling parameterized constructor“ + " of base");
}
}
class Derived extends Base
{
Derived()
{
System.out.println("No-argument constructor " + "of derived");
}

Derived(String name)
{
super(name);
System.out.println("Calling parameterized " + "constructor of derived");
}

By Jagadish Sahoo
public static void main(String args[])
{
Derived obj = new Derived("test");
}
}

By Jagadish Sahoo
Strings in Java
• Strings in Java are Objects that are backed internally by a char array.
• Since arrays are immutable(cannot grow), Strings are immutable as
well.
• Whenever a change to a String is made, an entirely new String is
created.
Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";
Example:
String str = “Jagadish";

By Jagadish Sahoo
Memory allotment of String
• Whenever a String Object is created as a literal, the object will be
created in String constant pool. This allows JVM to optimize the
initialization of String literal.
For example:
String str = “Jagadish";
• The string can also be declared using new operator i.e. dynamically
allocated. In case of String are dynamically allocated they are assigned
a new memory location in heap. This string will not be added to String
constant pool.
For example:
String str = new String(“Jagadish");
By Jagadish Sahoo
import java.io.*;
import java.lang.*;

class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = “Jagadish";

// Prints the String.


System.out.println("String s = " + s);

// Declare String using new operator


String s1 = new String(“Jagadish");

// Prints the String.


System.out.println("String s1 = " + s1);
}
}

By Jagadish Sahoo
StringBuffer
• StringBuffer is a peer class of String that provides much of the
functionality of strings.
• The string represents fixed-length, immutable character sequences
while StringBuffer represents growable and writable character
sequences.
Syntax:
StringBuffer s = new StringBuffer(“Jagadish");

By Jagadish Sahoo
StringBuilder
• The StringBuilder in Java represents a mutable sequence of
characters. Since the String Class in Java creates an immutable
sequence of characters, the StringBuilder class provides an alternate
to String Class, as it creates a mutable sequence of characters.
Syntax:
StringBuilder str = new StringBuilder();
str.append(“Hello");

By Jagadish Sahoo
StringTokenizer
• StringTokenizer class in Java is used to break a string into tokens.

By Jagadish Sahoo
class StringStorage {
public static void main(String args[])
{
String s1 = "TAT";
String s2 = "TAT";
String s3 = new String("TAT");
String s4 = new String("TAT");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}

By Jagadish Sahoo
Note: All objects in Java are stored in a heap. The reference
variable is to the object stored in the stack area or they can be
contained in other objects which puts them in the heap area
also.
By Jagadish Sahoo
String class in Java
• String is a sequence of characters. In java, objects of String are
immutable which means a constant and cannot be changed once
created.

By Jagadish Sahoo
Creating a String
• There are two ways to create string in Java:

• String literal
String s = “Jagadish”;
• Using new keyword
String s = new String (“Jagadish”);

By Jagadish Sahoo
Constructors
1. String(byte[] byte_arr) – Construct a new String by decoding
the byte array. It uses the platform’s default character set for decoding.
• Example:
byte[] b_arr = {72, 102, 102, 108, 115};
String s_byte =new String(b_arr);

By Jagadish Sahoo
2. String(byte[] byte_arr, Charset char_set)
• Construct a new String by decoding the byte array. It uses the
char_set for decoding.
Example:
byte[] b_arr = {72, 102, 102, 108, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs);

By Jagadish Sahoo
3. String(byte[] byte_arr, String char_set_name)
• Construct a new String by decoding the byte array. It uses the
char_set_name for decoding.
• It looks similar to the previous constructs and they appear before
similar functions but it takes the String(which contains
char_set_name) as parameter while the previous constructor takes
CharSet.
Example:
byte[] b_arr = {72, 102, 102, 108, 115};
String s = new String(b_arr, "US-ASCII");

By Jagadish Sahoo
4. String(byte[] byte_arr, int start_index, int length)
• Construct a new string from the bytes array depending on the
start_index(Starting location) and length(number of characters from
starting location).
Example:
byte[] b_arr = {72, 102, 102, 108, 115};
String s = new String(b_arr, 1, 3);

By Jagadish Sahoo
5. String(byte[] byte_arr, int start_index, int length, Charset char_set)
• Construct a new string from the bytes array depending on the
start_index(Starting location) and length(number of characters from
starting location).
• Uses char_set_name for decoding.
Example:
byte[] b_arr = {72, 102, 102, 108, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs);

By Jagadish Sahoo
6. String(byte[] byte_arr, int start_index, int length, String
char_set_name)
• Construct a new string from the bytes array depending on the
start_index(Starting location) and length(number of characters from
starting location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {72, 102, 102, 108, 115};
String s = new String(b_arr, 1, 4, "US-ASCII");

By Jagadish Sahoo
7. String(char[] char_arr)
• Allocates a new String from the given Character array
Example:
char char_arr[] = {‘H', 'e', ‘l', ‘l', ‘o'};
String s = new String(char_arr); //Hello
8. String(char[] char_array, int start_index, int count)
• Allocates a String from a given character array but choose count
characters from the start_index.
Example:
char char_arr[] = {‘H', 'e', ‘l', ‘l', ‘o'};
String s = new String(char_arr , 1, 3); //ell

By Jagadish Sahoo
9. String(int[] uni_code_points, int offset, int count)
Allocates a String from a uni_code_array but choose count characters
from the start_index.
Example:
int[] uni_code = {72, 102, 102, 108, 115};
String s = new String(uni_code, 1, 3);

By Jagadish Sahoo
10. String(StringBuffer s_buffer)
Allocates a new string from the string in s_buffer
Example:
StringBuffer s_buffer = new StringBuffer(“Jagadish");
String s = new String(s_buffer);
11. String(StringBuilder s_builder)
Allocates a new string from the string in s_builder
• Example:
• StringBuilder s_builder = new StringBuilder(“Jagadish");
• String s = new String(s_builder);

By Jagadish Sahoo
String Methods
1. int length(); Returns the number of characters in the String.
“jagadish".length(); // returns 13
2. Char charAt(int i); Returns the character at ith index.
" jagadish".charAt(3); // returns ‘a’
3. String substring (int i); Return the substring from the ith index
character to end.
" jagadish".substring(3); // returns “adish”
4. String substring (int i, int j): Returns the substring from i to j-1
index.
"jagadish".substring(2, 5); // returns “gad”

By Jagadish Sahoo
5. String concat( String str); Concatenates specified string to the end of
this string.
String s1 = ”Jagadish”;
String s2 = ”Sahoo”;
String output = s1.concat(s2); // returns “JagadishSahoo”
6. int indexOf (String s); Returns the index within the string of the first
occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
7. int indexOf (String s, int i); Returns the index within the string of the
first occurrence of the specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13

By Jagadish Sahoo
8. Int lastIndexOf( String s); Returns the index within the string of the
last occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
9. boolean equals( Object otherObj); Compares this string to the
specified object.
Boolean out = “Jagadish”.equals(“Jagadish”); // returns true
Boolean out = “Jagadish”.equals(“jagadish”); // returns false
10. boolean equalsIgnoreCase (String anotherString); Compares string
to another string, ignoring case considerations.
Boolean out = “Jagadish”.equals(“Jagadish”); // returns true
Boolean out = “Jagadish”.equals(“jagadish”); // returns true
By Jagadish Sahoo
11. int compareTo( String anotherString); Compares two string lexicographically.
int out = s1.compareTo(s2); // where s1 and s2 are strings to be compared

This returns difference s1-s2. If :


out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12. int compareToIgnoreCase( String anotherString); Compares two string
lexicographically, ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 and s2 are strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.

By Jagadish Sahoo
13. String toLowerCase();
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14. String toUpperCase();
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”

By Jagadish Sahoo
15. String trim();
Returns the copy of the String, by removing whitespaces at both ends. It does
not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar);
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “Hello“;
String s2 = s1.replace(‘l’ ,’g’); // returns “Heggo”

By Jagadish Sahoo
StringBuffer class in Java
• StringBuffer is a peer class of String that provides much of the
functionality of strings. String represents fixed-length, immutable
character sequences while StringBuffer represents growable and
writable character sequences.
• StringBuffer may have characters and substrings inserted in the
middle or appended to the end. It will automatically grow to make
room for such additions and often has more characters preallocated
than are actually needed, to allow room for growth.

By Jagadish Sahoo
StringBuffer Constructors
• StringBuffer( ): It reserves room for 16 characters without
reallocation.
StringBuffer s=new StringBuffer();

• StringBuffer( int size)It accepts an integer argument that explicitly sets


the size of the buffer.
StringBuffer s=new StringBuffer(20);
• StringBuffer(String str): It accepts a String argument that sets the
initial contents of the StringBuffer object and reserves room for 16
more characters without reallocation.
StringBuffer s=new StringBuffer(“Jagadish");

By Jagadish Sahoo
Methods
• length( ) and capacity( ): The length of a StringBuffer can be found by the length( )
method, while the total allocated capacity can be found by the capacity( ) method.
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“Jagadish");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string GeeksforGeeks=" + p);
System.out.println("Capacity of string GeeksforGeeks=" + q);
}
}

By Jagadish Sahoo
• append( ): It is used to add text at the end of the existence text. Here are a
few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“Jagadish");
s.append(“Sahoo");
System.out.println(s); // returns JagadishSahoo
s.append(123);
System.out.println(s); // returns JagadishSahoo123
}
}
By Jagadish Sahoo
• insert( ): It is used to insert text at the specified index position.

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted
into the invoking StringBuffer object.

By Jagadish Sahoo
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“JagadishSahoo");
s.insert(8, "for");
System.out.println(s); // returns JagadishforSahoo
s.insert(0, 5);
System.out.println(s); // returns 5JagadishforSahoo
s.insert(3, true);
System.out.println(s);
s.insert(5, 41.35d);
System.out.println(s);
s.insert(8, 41.35f);
System.out.println(s);
char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };
// insert character array at offset 9
s.insert(2, geeks_arr);
System.out.println(s);
}
}

By Jagadish Sahoo
• reverse( ): It can reverse the characters within a StringBuffer object
using reverse( ).This method returns the reversed object on which it
was called.
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“Jagadish");
s.reverse();
System.out.println(s);
}
}
By Jagadish Sahoo
• delete( ) and deleteCharAt( ): It can delete characters within a
StringBuffer by using the methods delete( ) and deleteCharAt( ).The
delete( ) method deletes a sequence of characters from the invoking
object. Here, start Index specifies the index of the first character to
remove, and end Index specifies an index one past the last character
to remove. Thus, the substring deleted runs from start Index to
endIndex–1. The resulting StringBuffer object is returned. The
deleteCharAt( ) method deletes the character at the index specified
by loc. It returns the resulting StringBuffer object.These methods are
shown here:
• StringBuffer delete(int startIndex, int endIndex)
• StringBuffer deleteCharAt(int loc)

By Jagadish Sahoo
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“JagadishSahoo");
s.delete(0, 5);
System.out.println(s);
s.deleteCharAt(7);
System.out.println(s);
}
}

By Jagadish Sahoo
• replace( ): It can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). The substring being replaced is
specified by the indexes start Index and endIndex. Thus, the substring at
start Index through endIndex–1 is replaced. The replacement string is
passed in str. The resulting StringBuffer object is returned.
• StringBuffer replace(int startIndex, int endIndex, String str)
import java.io.*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“JagadishSahoo");
s.replace(5, 8, "are");
System.out.println(s);
}
}

By Jagadish Sahoo
ensureCapacity( ): It is used to increase the capacity of a StringBuffer
object. The new capacity will be set to either the value we specify or
twice the current capacity plus two (i.e. capacity+2), whichever is
larger. Here, capacity specifies the size of the buffer.
• void ensureCapacity(int capacity)
void setCharAt(int index, char ch): In this method, the character at
the specified index is set to ch.
Syntax:
public void setCharAt(int index, char ch)

By Jagadish Sahoo
• String substring(int start): This method returns a new String that
contains a subsequence of characters currently contained in this
character sequence.
Syntax:
public String substring(int start)
public String substring(int start, int end)

• String toString(): This method returns a string representing the data in


this sequence.
Syntax:
public String toString()

By Jagadish Sahoo
StringBuilder Class in Java
• The StringBuilder in Java represents a mutable sequence of
characters. Since the String Class in Java creates an immutable
sequence of characters, the StringBuilder class provides an alternative
to String Class, as it creates a mutable sequence of characters.
• The function of StringBuilder is very much similar to the StringBuffer
class, as both of them provide an alternative to String Class by making
a mutable sequence of characters.
• However the StringBuilder class differs from the StringBuffer class on
the basis of synchronization.
• The StringBuilder class provides no guarantee of synchronization
whereas the StringBuffer class does.

By Jagadish Sahoo
• Therefore this class is designed for use as a drop-in replacement for
StringBuffer in places where the StringBuffer was being used by a
single thread (as is generally the case).
• Where possible, it is recommended that this class be used in
preference to StringBuffer as it will be faster under most
implementations.
• Instances of StringBuilder are not safe for use by multiple threads. If
such synchronization is required then it is recommended that
StringBuffer be used.

By Jagadish Sahoo
Access Modifiers in Java
• There are two types of modifiers in Java: access modifiers and non-
access modifiers.
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class.
• We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

By Jagadish Sahoo
• There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the
package and outside the package.
Note : There are many non-access modifiers, such as static, abstract,
synchronized, native, volatile, transient, etc.
By Jagadish Sahoo
By Jagadish Sahoo
Private
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
}
}
By Jagadish Sahoo
• 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
}
}

By Jagadish Sahoo
Default
• If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. 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
}
}
By Jagadish Sahoo
Protected
• The protected access modifier is accessible within package and outside the package but through
inheritance only.
//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();
}
} By Jagadish Sahoo
Public
• The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//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();
}
}

By Jagadish Sahoo
Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object.
• The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and
fields of the parent class.
• Moreover, you can add new methods and fields in your current class
also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

By Jagadish Sahoo
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.

By Jagadish Sahoo
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 the previous class.

By Jagadish Sahoo
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.
• In the terminology of Java, a class which is inherited is called a parent
or superclass, and the new class is called child or subclass.

By Jagadish Sahoo
Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A
Employee. It means that Programmer is a type of Employee.

By Jagadish Sahoo
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

By Jagadish Sahoo
Types of inheritance in java

By Jagadish Sahoo
• In java programming, multiple and hybrid inheritance is supported
through interface only.

By Jagadish Sahoo
Single Inheritance
• When a class inherits another class, it is known as a single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
By Jagadish Sahoo
Multilevel Inheritance
• When there is a chain of inheritance, it is known as multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
By Jagadish Sahoo
Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

By Jagadish Sahoo
Why multiple inheritance is not supported in java?
• To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method and
you call it from child class object, there will be ambiguity to call the
method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.

By Jagadish Sahoo
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

By Jagadish Sahoo
Java Package
• 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.

By Jagadish Sahoo
By Jagadish Sahoo
Advantage of Java Package
• Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
• Java package provides access protection.
• Java package removes naming collision.

By Jagadish Sahoo
Creating Package
• The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

By Jagadish Sahoo
Compiling a Package
Syntax
javac -d directory javafilename
javac -d . Simple.java
The -d is a switch that tells the compiler where to put the class file i.e.
it represents destination. The . represents the current folder.

How to run java package program


To Compile: javac -d . Simple.java
To Run: java mypack.Simple

By Jagadish Sahoo
How to access package from another package?
• There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

By Jagadish Sahoo
Using packagename.*
• If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
• The import keyword is used to make the classes and interface of
another package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

By Jagadish Sahoo
//save by B.java
package mypack;
import pack1.*;

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

By Jagadish Sahoo
Using packagename.classname
• If you import package.classname then only declared class of this
package will be accessible.
//save by A.java

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

By Jagadish Sahoo
//save by B.java
package mypack;
import pack.A;

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

By Jagadish Sahoo
Using fully qualified name
• If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing
the class or interface.
• It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

By Jagadish Sahoo
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

By Jagadish Sahoo
• If you import a package, all the classes and interface of that package
will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
• Note: Sequence of the program must be package then import then
class.

By Jagadish Sahoo
Subpackage in java
• Package inside the package is called the subpackage. It should be
created to categorize the package further.
package pack1.pack2;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
• To Compile: javac -d . Simple.java
• To Run: java pack1.pack2.Simple

By Jagadish Sahoo
How to put two public classes in a package?
• If you want to put two public classes in a package, have two java
source files containing one public class, but keep the package name
same. For example:
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}

By Jagadish Sahoo
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. There can
be only abstract methods in the Java interface, not method body.
• It is used to achieve abstraction and multiple inheritance in Java.
• Interfaces can have abstract methods and variables. It cannot have a
method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.

By Jagadish Sahoo
Why use Java interface?
• There are mainly three reasons to use interface.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

By Jagadish Sahoo
How to declare an interface?
• An interface is declared by using the interface keyword.
• It provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static and final
by default.
• A class that implements an interface must implement all the methods
declared in the interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract by default.
}

By Jagadish Sahoo
• The Java compiler adds public and abstract keywords before the
interface method. Moreover, it adds public, static and final keywords
before data members.
• In other words, Interface fields are public, static and final by default,
and the methods are public and abstract.

By Jagadish Sahoo
The relationship between classes and interfaces

By Jagadish Sahoo
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();
}
}

By Jagadish Sahoo
• In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes.
• In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers.
• Moreover, it is used by someone else. The implementation part is
hidden by the user who uses the interface.

By Jagadish Sahoo
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
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();
}}

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

By Jagadish Sahoo
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.

By Jagadish Sahoo
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();
}
}

By Jagadish Sahoo
Multiple inheritance is not supported through class in
java, but it is possible by an interface, why?
• Multiple inheritance is not supported in the case of class because of
ambiguity.
• However, it is supported in case of an interface because there is no
ambiguity. It is because its implementation is provided by the
implementation class.

By Jagadish Sahoo
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

By Jagadish Sahoo
Interface inheritance
• A class implements an interface, but one interface extends another interface.
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();
}
}
By Jagadish Sahoo
Java 8 Default Method in Interface
• Since Java 8, we can have method body in interface. But we need to make it default method.
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
By Jagadish Sahoo
Java 8 Static Method in Interface
• Since Java 8, we can have static method in interface.
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}} By Jagadish Sahoo
What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface.
They are used to provide some essential information to the JVM so that JVM
may perform some useful operation.
Nested Interface in Java
An interface can have another interface which is known as a nested interface.
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
By Jagadish Sahoo
Difference between abstract class and interface

By Jagadish Sahoo
By Jagadish Sahoo
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.

By Jagadish Sahoo
Use of Wrapper classes in Java
• 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.

By Jagadish Sahoo
• The eight classes of the java.lang package are known as wrapper
classes in Java.

By Jagadish Sahoo
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.

By Jagadish Sahoo
//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) int
ernally

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


}}

By Jagadish Sahoo
Unboxing
• The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not
need to use the intValue() method of wrapper classes to convert the wrapper type
into primitives.
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

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


}}
By Jagadish Sahoo
Utility methods of Wrapper classes
• The objective of Wrapper class is to define several utility methods
which are required for the primitive types.
• There are 4 utility methods for primitive type which is defined by
Wrapper class:
1. valueOf() method
2. xxxValue() method
3. parseXxx() method
4. toString() method

By Jagadish Sahoo
valueOf() method
• We can use valueOf() method to create Wrapper object for given
primitive or String.
• There are 3 types of valueOf() methods:
1. Wrapper valueOf(String s)
2. Wrapper valueOf(String s, int radix)
3. Wrapper valueOf(primitive p)

By Jagadish Sahoo
Wrapper valueOf(String s)
• Every wrapper class except Character class contains a static valueOf() method to create Wrapper class object
for given String.
Syntax:
public static Wrapper valueOf(String s);
class GFG {
public static void main(String[] args)
{
Integer I = Integer.valueOf("10");
System.out.println(I);
Double D = Double.valueOf("10.0");
System.out.println(D);
Boolean B = Boolean.valueOf("true");
System.out.println(B);

// Here we will get RuntimeException


Integer I1 = Integer.valueOf("ten");
}
} By Jagadish Sahoo
Wrapper valueOf(String s, int radix)
• Every Integral Wrapper class Byte, Short, Integer, Long) contains the following
valueOf() method to create a Wrapper object for the given String with specified
radix. The range of the radix is 2 to 36.
Syntax:
public static Wrapper valueOf(String s, int radix)
class GFG {
public static void main(String[] args)
{
Integer I = Integer.valueOf("1111", 2);
System.out.println(I);
Integer I1 = Integer.valueOf("1111", 4);
System.out.println(I1);
}
}
By Jagadish Sahoo
Wrapper valueOf(primitive p)
Every Wrapper class including Character class contains the following method to create a
Wrapper object for the given primitive type.
Syntax:
public static Wrapper valueOf(primitive p);
class GFG {
public static void main(String[] args)
{
Integer I = Integer.valueOf(10);
Double D = Double.valueOf(10.5);
Character C = Character.valueOf('a');
System.out.println(I);
System.out.println(D);
System.out.println(C);
}
}
By Jagadish Sahoo
xxxValue() method
• We can use xxxValue() methods to get the primitive for the given Wrapper
Object. Every number type Wrapper class( Byte, Short, Integer, Long, Float,
Double) contains the following 6 methods to get primitive for the given
Wrapper object:
1. public byte byteValue()
2. public short shortValue()
3. public int intValue()
4. public long longValue()
5. public float floatValue()
6. public float doubleValue()

By Jagadish Sahoo
class GFG {
public static void main(String[] args)
{
Integer I = new Integer(130);
System.out.println(I.byteValue());
System.out.println(I.shortValue());
System.out.println(I.intValue());
System.out.println(I.longValue());
System.out.println(I.floatValue());
System.out.println(I.doubleValue());
}
}

By Jagadish Sahoo
parseXxx() method
• We can use parseXxx() methods to convert String to primitive.
• There are two types of parseXxx() methods:
1. primitive parseXxx(String s)
2. parseXxx(String s, int radix)

By Jagadish Sahoo
• primitive parseXxx(String s) : Every Wrapper class except character class contains
the following parseXxx() method to find primitive for the given String object.
Syntax:
public static primitive parseXxx(String s);
class GFG {
public static void main(String[] args)
{
int i = Integer.parseInt("10");
double d = Double.parseDouble("10.5");
boolean b = Boolean.parseBoolean("true");
System.out.println(i);
System.out.println(d);
System.out.println(b);
}
}
By Jagadish Sahoo
• parseXxx(String s, int radix) : Every Integral type Wrapper class (Byte, Short,
Integer, Long) contains the following parseXxx() method to convert specified radix
String to primitive.
Syntax:
public static primitive parseXxx(String s, int radix);
class GFG {
public static void main(String[] args)
{
int i = Integer.parseInt("1000", 2);
long l = Long.parseLong("1111", 4);
System.out.println(i);
System.out.println(l);
}
}
By Jagadish Sahoo
toString() method
• We can use toString() method to convert Wrapper object or primitive to String.
There are few forms of toString() method:
• public String toString() : Every wrapper class contains the following toString()
method to convert Wrapper Object to String type.
Syntax:
public String toString();
class GFG {
public static void main(String[] args)
{
Integer I = new Integer(10);
String s = I.toString();
System.out.println(s);
}
}

By Jagadish Sahoo
• toString(primitive p) : Every Wrapper class including Character class
contains the following static toString() method to convert primitive to
String.
Syntax:
public static String toString(primitive p);
class GFG {
public static void main(String[] args)
{
String s = Integer.toString(10);
System.out.println(s);
String s1 = Character.toString('a');
System.out.println(s1);
}
}

By Jagadish Sahoo
• toString(primitive p, int radix) : Integer and Long classes contains the
following toString() method to convert primitve to specified radix String.
Syntax:
public static String toString(primitive p, int radix);
class GFG {
public static void main(String[] args)
{
String s = Integer.toString(15, 2);
System.out.println(s);
String s1 = Long.toString(11110000, 4);
System.out.println(s1);
}
}

By Jagadish Sahoo
Method Overriding in Java
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
• If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method
overriding.

By Jagadish Sahoo
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism

By Jagadish Sahoo
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).

By Jagadish Sahoo
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

By Jagadish Sahoo
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
By Jagadish Sahoo
A real example of Java Method Overriding
• Consider a scenario where Bank is a class that provides functionality
to get the rate of interest. However, the rate of interest varies
according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7%, and 9% rate of interest.

By Jagadish Sahoo
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
By Jagadish Sahoo
• Can we override static method?
No, a static method cannot be overridden.

• Why can we not override static method?


It is because the static method is bound with class whereas instance method
is bound with an object. Static belongs to the class area, and an instance
belongs to the heap area.

Can we override java main method?


• No, because the main is a static method.

By Jagadish Sahoo
Difference between method overloading and
method overriding in java

By Jagadish Sahoo
Abstract class in Java
• A class which is declared with the abstract keyword is known as an
abstract class.
• It can have abstract and non-abstract methods (method with the
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.

By Jagadish Sahoo
Ways to achieve Abstraction

• There are two ways to achieve abstraction in java


1. Abstract class (0 to 100%)
2. Interface (100%)

By Jagadish Sahoo
Abstract class in Java
• A class which is declared as abstract is known as an abstract class. It
can have abstract and non-abstract methods.
• It needs to be extended and its method implemented. It cannot be
instantiated.

By Jagadish Sahoo
Rules for Java Abstract class

• An abstract class must be declared with an abstract keyword.


• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
• If there is an abstract method in a class, that class must be abstract.

By Jagadish Sahoo
Super Keyword in Java
• The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference
variable.

By Jagadish Sahoo
Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.

By Jagadish Sahoo
super is used to refer immediate parent class
instance variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}} By Jagadish Sahoo
super can be used to invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
By Jagadish Sahoo
super is used to invoke parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

By Jagadish Sahoo
• Example of abstract class
abstract class A{}

• Abstract Method in Java


A method which is declared as abstract and does not have
implementation is known as an abstract method.

• Example of abstract method


abstract void printStatus();//no method body and abstract

By Jagadish Sahoo
Example of Abstract class that has an abstract
method
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
By Jagadish Sahoo
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 a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}

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

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

By Jagadish Sahoo
Abstract class having constructor, data member and methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

By Jagadish Sahoo
Note: super() is added in each class constructor automatically by
compiler if there is no super() or this().

By Jagadish Sahoo
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

By Jagadish Sahoo
Emp class inherits Person class so all the properties of Person will be inherited to
Emp by default. To initialize all the property, we are using parent class
constructor from child class. In such way, we are reusing the parent class
constructor.
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
} By Jagadish Sahoo
Final Keyword In Java
• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
1. variable
2. method
3. class

By Jagadish Sahoo
• The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in
the static block only.

By Jagadish Sahoo
Java final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Output:Compile Time Error
By Jagadish Sahoo
Java final method
• If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

By Jagadish Sahoo
Java final class
• If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error
By Jagadish Sahoo
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}

By Jagadish Sahoo
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known
as blank final variable.
If you want to create a variable that is initialized at the time of creating
object and once initialized may not be changed, it is useful. For
example PAN CARD number of an employee.
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
By Jagadish Sahoo
Que) Can we initialize blank final variable?
Yes, but only in constructor.
class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}

By Jagadish Sahoo
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
By Jagadish Sahoo
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}

By Jagadish Sahoo
Exception Handling in Java
• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
• Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
• Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
• The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions.
By Jagadish Sahoo
Hierarchy of Java Exception classes
• The java.lang.Throwable class is the root class of Java
Exception hierarchy inherited by two subclasses:
• Exception and Error.

By Jagadish Sahoo
By Jagadish Sahoo
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

By Jagadish Sahoo
• Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed.
• However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling
in Java.

By Jagadish Sahoo
Types of Java Exceptions
• There are mainly two types of exceptions: checked and unchecked.
• An error is considered as the unchecked exception.
• However, according to Oracle, there are three types of exceptions
namely:
1. Checked Exception
2. Unchecked Exception
3. Error

By Jagadish Sahoo
Difference between Checked and Unchecked Exceptions
• 1) Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
• 2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
• 3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

By Jagadish Sahoo
Java Exception Keywords

By Jagadish Sahoo
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

By Jagadish Sahoo
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException

By Jagadish Sahoo
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

By Jagadish Sahoo
Java try-catch block
• Java try block is used to enclose the code that might throw an
exception. It must be used within the method.

• If an exception occurs at the particular statement in the try block, the


rest of the block code will not execute. So, it is recommended not to
keep the code in try block that will not throw an exception.

• Java try block must be followed by either catch or finally block.

By Jagadish Sahoo
Syntax of Java try-catch
try{
//code that may throw an exception
}
catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}
finally{}

By Jagadish Sahoo
Java catch block
• Java catch block is used to handle the Exception by declaring the type
of exception within the parameter. The declared exception must be
the parent class exception ( i.e., Exception) or the generated
exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use
multiple catch block with a single try block.

By Jagadish Sahoo
Internal Working of Java try-catch block

By Jagadish Sahoo
• The JVM firstly checks whether the exception is handled or not. If
exception is not handled, JVM provides a default exception handler
that performs the following tasks:
1. Prints out exception description.
2. Prints the stack trace (Hierarchy of methods where the exception
occurred).
3. Causes the program to terminate.
• But if the application programmer handles the exception, the normal
flow of the application is maintained, i.e., rest of the code is executed.

By Jagadish Sahoo
Problem without exception handling
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}

the rest of the code is not executed (in such case, the rest of the code statement is not printed).

By Jagadish Sahoo
Solution by exception handling
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}

By Jagadish Sahoo
Handle the exception using the parent class
exception.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
Print a custom message on exception
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
By Jagadish Sahoo
Resolve the exception in a catch block
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
By Jagadish Sahoo
public class TryCatchExample9 {
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
Java Catch Multiple Exceptions
• A try block can be followed by one or more catch blocks.
• Each catch block must contain a different exception handler.
• So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
• At a time only one exception occurs and at a time only one catch
block is executed.
• All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.

By Jagadish Sahoo
Flowchart of Multi-catch Block

By Jagadish Sahoo
public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
By Jagadish Sahoo
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2
completed");}
System.out.println("rest of the code...");
}
}

By Jagadish Sahoo
Java Nested try block
• In Java, using a try block inside another try block is permitted. It is
called as nested try block.
• For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try
block can handle the ArithemeticException (division by zero).
• Sometimes a situation may arise where a part of a block may cause
one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.

By Jagadish Sahoo
try
{
statement 1;
statement 2;
try
{
statement 3;
statement 4;
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
}

}
catch(Exception e1)
{
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
}
....

By Jagadish Sahoo
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

By Jagadish Sahoo
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
By Jagadish Sahoo
• When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are
checked for that exception, and if it matches, the catch block of outer
try block is executed.
• If none of the catch block specified in the code is unable to handle
the exception, then the Java runtime system will handle the
exception. Then it displays the system generated message for that
exception.

By Jagadish Sahoo
Example
• Here the try block within nested try block (inner try block 2) do not handle the exception. The control is then
transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is
transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is
termed as nesting.
public class NestedTryBlock2 {
public static void main(String args[])
{
// outer (main) try block
try {
//inner try block 1
try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };

//printing the array element out of its bounds


System.out.println(arr[10]);
}
By Jagadish Sahoo
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}

By Jagadish Sahoo
Java finally block
• Java finally block is a block used to execute important code such as
closing the connection, etc.
• Java finally block is always executed whether an exception is handled
or not. Therefore, it contains all the necessary statements that need
to be printed regardless of the exception occurs or not.
• The finally block follows the try-catch block.

By Jagadish Sahoo
By Jagadish Sahoo
Why use Java finally block?
• finally block in Java can be used to put "cleanup" code such as closing
a file, closing connection, etc.
• The important statements to be printed can be placed in the finally
block.

By Jagadish Sahoo
Case 1: When an exception does not occur
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}
By Jagadish Sahoo
Case 2: When an exception occurr but not handled by the
catch block
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
By Jagadish Sahoo
Case 3: When an exception occurs and is handled by the
catch block
public class TestFinallyBlock2{
public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
By Jagadish Sahoo
Java throw Exception
• In Java, exceptions allows us to write good quality codes where the
errors are checked at the compile time instead of runtime and we can
create custom exceptions making the code recovery and debugging
easier.
• The Java throw keyword is used to throw an exception explicitly.
• We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by
throw keyword. It is mainly used to throw a custom exception.

By Jagadish Sahoo
• We can also define our own set of conditions and throw an exception
explicitly using throw keyword.
• For example, we can throw ArithmeticException if we divide a
number by another number. Here, we just need to set the condition
and throw exception using throw keyword.
• The syntax of the Java throw keyword is
throw new exception_class("error message");
throw new IOException("sorry device error");

By Jagadish Sahoo
Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
By Jagadish Sahoo
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

By Jagadish Sahoo
Example 2: Throwing Checked Exception
import java.io.*;
public class TestThrow2 {
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
} By Jagadish Sahoo
Example 3: Throwing User-defined Exception
• // class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
By Jagadish Sahoo
Java throws keyword
• The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling
code so that the normal flow of the program can be maintained.
• Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as
NullPointerException, it is programmers' fault that he is not checking
the code before it being used.

By Jagadish Sahoo
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared?
Ans: Checked exception only, because:
unchecked exception: under our control so we can correct our code.
error: beyond our control. For example, we are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.

By Jagadish Sahoo
2 cases of throws
Case 1: We have caught the exception i.e. we have handled the
exception using try/catch block.
Case 2: We have declared the exception i.e. specified throws keyword
with the method.

By Jagadish Sahoo
Case 1: Handle Exception Using try-catch block
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow...");
}
}
By Jagadish Sahoo
Case 2: Declare Exception
• In case we declare the exception, if exception does not occur, the
code will be executed fine.
• In case we declare the exception and the exception occurs, it will be
thrown at runtime because throws does not handle the exception.

By Jagadish Sahoo
A) If exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
By Jagadish Sahoo
B) If exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
By Jagadish Sahoo
Difference between throw and throws

By Jagadish Sahoo
By Jagadish Sahoo
Java throw Example
public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}
By Jagadish Sahoo
Java throws Example
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}

By Jagadish Sahoo
Java throw and throws Example
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
By Jagadish Sahoo
Difference between final, finally and finalize

By Jagadish Sahoo
By Jagadish Sahoo
Java finalize Example
public class FinalizeExample {
public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
System.out.println("Hashcode is: " + obj.hashCode());
obj = null;
// calling the garbage collector using gc()
System.gc();
System.out.println("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
System.out.println("Called the finalize() method");
}
}
By Jagadish Sahoo
Java Custom Exception
• In Java, we can create our own exceptions that are derived classes of
the Exception class.
• Creating our own Exception is known as custom exception or user-
defined exception.
• Basically, Java custom exceptions are used to customize the exception
according to user need.
• Using the custom exception, we can have your own exception and
message. Here, we have passed a string to the constructor of
superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.

By Jagadish Sahoo
Why use custom exceptions?
• Java exceptions cover almost all the general type of exceptions that
may occur in the programming.
• However, we sometimes need to create custom exceptions.
1. To catch and provide specific treatment to a subset of existing Java
exceptions.
2. Business logic exceptions: These are the exceptions related to
business logic and workflow. It is useful for the application users or
the developers to understand the exact problem.
• In order to create custom exception, we need to extend Exception
class that belongs to java.lang package.

By Jagadish Sahoo
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}

Note: We need to write the constructor that takes the String as the
error message and it is called parent class constructor.

By Jagadish Sahoo
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
By Jagadish Sahoo
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

By Jagadish Sahoo
// class representing custom exception
class MyCustomException extends Exception
{
}
// class that uses custom exception MyCustomException
public class TestCustomException2 The constructor of Exception class can be called without using
{ a parameter and calling super() method is not mandatory.
// main method
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
System.out.println("rest of the code...");
}
}

By Jagadish Sahoo
Multithreading in Java
• Multithreading in Java is a process of executing multiple threads
simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
• However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between the
threads takes less time than process.
• Java Multithreading is mostly used in games, animation, etc.

By Jagadish Sahoo
Advantages of Java Multithreading
• It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
• You can perform many operations together, so it saves time.
• Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.

By Jagadish Sahoo
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.
We use multitasking to utilize the CPU. Multitasking can be achieved
in two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)

By Jagadish Sahoo
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process
allocates a separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

By Jagadish Sahoo
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

By Jagadish Sahoo
What is Thread in java
• A thread is a lightweight subprocess, the smallest unit of processing.
It is a separate path of execution.
• Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.

By Jagadish Sahoo
A thread is executed inside the process. There is context-switching between the threads. There can be multiple processes
inside the OS, and one process can have multiple threads.
By Jagadish Sahoo
Java Thread class
• Java provides Thread class to achieve thread programming.
• Thread class provides constructors and methods to create and
perform operations on a thread.
• Thread class extends Object class and implements Runnable
interface.

By Jagadish Sahoo
Java Thread Methods

By Jagadish Sahoo
By Jagadish Sahoo
By Jagadish Sahoo
By Jagadish Sahoo
Life cycle of a Thread (Thread States)
• A thread can be in one of the five states.
• According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There is no
running state.
• The life cycle of the thread in java is controlled by JVM. The java
thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

By Jagadish Sahoo
By Jagadish Sahoo
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.
By Jagadish Sahoo
How to create thread
• There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

By Jagadish Sahoo
Thread class:
• Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and
implements Runnable interface.
• Commonly used Constructors of Thread class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)

By Jagadish Sahoo
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the run() method
on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing
thread.

By Jagadish Sahoo
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been
interrupted.

By Jagadish Sahoo
Runnable interface:
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface
have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
 A new thread starts.
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method
will run.
By Jagadish Sahoo
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

By Jagadish Sahoo
Java Thread Example by implementing Runnable
interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
By Jagadish Sahoo
Thread Scheduler in Java
• Thread scheduler in java is the part of the JVM that decides which
thread should run.
• There is no guarantee that which runnable thread will be chosen to
run by the thread scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.

By Jagadish Sahoo
Difference between preemptive scheduling and
time slicing
• Under preemptive scheduling, the highest priority task executes until
it enters the waiting or dead states or a higher priority task comes
into existence.
• Under time slicing, a task executes for a predefined slice of time and
then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.

By Jagadish Sahoo
Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
Syntax of sleep() method
The Thread class provides two methods for sleeping a thread:
1. public static void sleep(long miliseconds)throws
InterruptedException
2. public static void sleep(long miliseconds, int nanos)throws
InterruptedException

By Jagadish Sahoo
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}
Note : At a time only one thread is executed. If you sleep a thread for the specified time, the
thread scheduler picks up another thread and so on.
By Jagadish Sahoo
Can we start a thread twice
• No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once
but for second time, it will throw exception.
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
} By Jagadish Sahoo
What if we call run() method directly instead
start() method?
• Each thread starts in a separate call stack.
• Invoking the run() method from main thread, the run() method goes onto
the current call stack rather than at the beginning of a new call stack.
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}

By Jagadish Sahoo
Problem if you direct call run() method
class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();

t1.run();
t2.run();
} There is no context-switching because here t1 and t2 will be
} treated as normal object not thread object.
By Jagadish Sahoo
Naming Thread and Current Thread
• The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name i.e. thread-0, thread-1 and
so on.
• We can change the name of the thread by using setName() method.
The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a
thread.

By Jagadish Sahoo
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());

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

t1.setName(“Jagadish");
System.out.println("After changing name of t1:"+t1.getName());
}
} By Jagadish Sahoo
Current Thread
• The currentThread() method returns a reference of currently executing thread.
Syntax : public static Thread currentThread()
class TestMultiNaming2 extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();

t1.start();
t2.start();
}
}
By Jagadish Sahoo
Priority of a Thread (Thread Priority)
• Each thread have a priority.
• Priorities are represented by a number between 1 and 10. I
• n most cases, thread scheduler 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:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. 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.
By Jagadish Sahoo
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
By Jagadish Sahoo
Synchronization in Java
• 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.

By Jagadish Sahoo
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

By Jagadish Sahoo
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

By Jagadish Sahoo
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)

By Jagadish Sahoo
Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one
another while sharing data. It can be achieved by using the following
three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization

By Jagadish Sahoo
Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or
monitor. Every object has a lock associated with it. By convention, a
thread that needs consistent access to an object's fields has to
acquire the object's lock before accessing them, and then release the
lock when it's done with them.
• From Java 5 the package java.util.concurrent.locks contains several
lock implementations.

By Jagadish Sahoo
Problem without Synchronization
• There is no synchronization, so output is inconsistent.

By Jagadish Sahoo
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.

By Jagadish Sahoo
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}

By Jagadish Sahoo
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
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();
}
} By Jagadish Sahoo
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any
specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to
synchronize only 5 lines, in such cases, we can use synchronized block.
• If we put all the codes of the method in the synchronized block, it will
work same as the synchronized method.
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
• Java synchronized block is more efficient than Java synchronized
method.

By Jagadish Sahoo
Syntax
synchronized (object reference expression) {
//code block
}
• Example of Synchronized Block
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
} By Jagadish Sahoo
class MyThread1 extends Thread{ public class TestSynchronizedBlock1{
Table t; public static void main(String args[]){
MyThread1(Table t){ Table obj = new Table();//only one
this.t=t; object
} MyThread1 t1=new MyThread1(obj);
public void run(){ MyThread2 t2=new MyThread2(obj);
t.printTable(5); t1.start();
} t2.start();
} }
class MyThread2 extends Thread{ }
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
By Jagadish Sahoo
}
Static Synchronization
• If you make any static method as synchronized, the lock will be on the
class not on object.

By Jagadish Sahoo
Problem without static synchronization
• Suppose there are two objects of a shared class(e.g. Table) named
object1 and object2.In case of synchronized method and
synchronized block there cannot be interference between t1 and t2 or
t3 and t4 because t1 and t2 both refers to a common object that have
a single lock.But there can be interference between t1 and t3 or t2
and t4 because t1 acquires another lock and t3 acquires another
lock.I want no interference between t1 and t3 or t2 and t4.Static
synchronization solves this problem.

By Jagadish Sahoo
Example of static synchronization
class MyThread3 extends Thread{
class Table{ public void run(){
synchronized static void printTable(int n){ Table.printTable(100);
for(int i=1;i<=10;i++){ }
System.out.println(n*i); }
try{ class MyThread4 extends Thread{
Thread.sleep(400); public void run(){
}catch(Exception e){} Table.printTable(1000);
} }
} }
} public class TestSynchronization4{
class MyThread1 extends Thread{ public static void main(String t[]){
public void run(){ MyThread1 t1=new MyThread1();
Table.printTable(1); MyThread2 t2=new MyThread2();
} MyThread3 t3=new MyThread3();
} MyThread4 t4=new MyThread4();
class MyThread2 extends Thread{ t1.start();
public void run(){ t2.start();
Table.printTable(10); t3.start();
} t4.start();
} } By Jagadish Sahoo
}
Deadlock in Java
• Deadlock in Java is a part of multithreading. Deadlock can occur in a
situation when a thread is waiting for an object lock, that is acquired
by another thread and second thread is waiting for an object lock that
is acquired by first thread. Since, both threads are waiting for each
other to release the lock, the condition is called deadlock.

By Jagadish Sahoo
Inter-thread communication in Java
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• Cooperation (Inter-thread communication) 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.It
is implemented by following methods of Object class:
1. wait()
2. notify()
3. notifyAll()

By Jagadish Sahoo
wait() method
• Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
• The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.
notify() method
• Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
public final void notify()

By Jagadish Sahoo
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:

public final void notifyAll()

By Jagadish Sahoo
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.

By Jagadish Sahoo
Difference between wait and sleep?

By Jagadish Sahoo
Example of inter thread communication in java
class Customer{
int amount=10000; class Test{
public static void main(String args[]){
synchronized void withdraw(int amount){ final Customer c=new Customer();
System.out.println("going to withdraw..."); new Thread(){
public void run(){c.withdraw(15000);}
if(this.amount<amount){ }.start();
System.out.println("Less balance; waiting for deposit..."); new Thread(){
try{wait();}catch(Exception e){} public void run(){c.deposit(10000);}
} }.start();
this.amount-=amount;
System.out.println("withdraw completed..."); }}
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
By Jagadish Sahoo
Java Applet
• Applet is a special type of program that is embedded in the webpage
to generate the dynamic content.
• It runs inside the browser and works at client side.

By Jagadish Sahoo
Advantage of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.

By Jagadish Sahoo
Hierarchy of Applet

By Jagadish Sahoo
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

By Jagadish Sahoo
Lifecycle methods for Applet
• The java.applet.Applet class 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an applet.
java.applet.Applet class
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked
only once.
By Jagadish Sahoo
java.awt.Component class
• public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc
etc.

By Jagadish Sahoo
How to run an Applet?
• There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).

By Jagadish Sahoo
Simple example of Applet by html file
• To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file. myapplet.html

//First.java <html>
<body>
import java.applet.Applet; <applet code="First.class" width="300" height="300">
</applet>
import java.awt.Graphics; </body>
public class First extends Applet{ </html>
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
By Jagadish Sahoo
Simple example of Applet by appletviewer tool:
• To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer First.java. Now Html
file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
By Jagadish Sahoo
Displaying Graphics in Applet
• public abstract void drawString(String str, int x, int y): is used to draw the specified string.
• public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and
height.
• public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default
color and specified width and height.
• public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified
width and height.
• public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color
and specified width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1,
y1) and (x2, y2).
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
the specified image.
• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
draw a circular or elliptical arc.
• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill
a circular or elliptical arc.
• public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
• public abstract void setFont(Font font): is used BytoJagadish
set the
Sahoo
graphics current font to the specified font.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300); myapplet.html
g.drawRect(70,100,30,30); <html>
g.fillRect(170,100,30,30); <body>
g.drawOval(70,200,30,30); <applet code="GraphicsDemo.class" width="300" height="300">
g.setColor(Color.pink); </applet>
</body>
g.fillOval(170,200,30,30);
</html>
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
} By Jagadish Sahoo
Displaying Image in Applet
• Applet is mostly used in games and animation. For this purpose image
is required to be displayed. The java.awt.Graphics class provide a
method drawImage() to display the image.

Syntax of drawImage() method:


• public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

By Jagadish Sahoo
How to get the object of Image
• The java.applet.Applet class provides getImage() method that returns
the object of Image. Syntax:
Public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
• public URL getDocumentBase(): is used to return the URL of the
document in which applet is embedded.
• public URL getCodeBase(): is used to return the base URL.

By Jagadish Sahoo
Example of displaying image in applet:
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),“mypic.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
} By Jagadish Sahoo
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

By Jagadish Sahoo
Animation in Applet
import java.awt.*;
myapplet.html
import java.applet.*;
<html>
public class AnimationExample extends Applet { <body>
<applet code="DisplayImage.class" width="300" height="300">
Image picture;
</applet>
public void init() { </body>
</html>
picture =getImage(getDocumentBase(),"bike_1.gif");
}

public void paint(Graphics g) {


for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);

try{Thread.sleep(100);}catch(Exception e){}
}
}
} By Jagadish Sahoo
EventHandling in Applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
} By Jagadish Sahoo
Painting in Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
} By Jagadish Sahoo
Parameter in Applet
• We can get any information from the HTML file as a parameter. For
this purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)

By Jagadish Sahoo
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
myapplet.html
String str=getParameter("msg"); <html>
<body>
g.drawString(str,50, 50); <applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
} </applet>
} </body>
</html>

By Jagadish Sahoo
Java AWT
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical
User Interface (GUI) or windows-based applications in Java.

• Java AWT components are platform-dependent i.e. components are


displayed according to the view of operating system. AWT is heavy
weight i.e. its components are using the resources of underlying
operating system (OS).

• The java.awt package provides classes for AWT API such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.

By Jagadish Sahoo
Java AWT Hierarchy

By Jagadish Sahoo
Components
• All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component. In order
to place every component in a particular position on a screen, we need to
add them to a container.

Container
• The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc. The classes that extends
Container class are known as container such as Frame, Dialog and Panel.

• It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.

By Jagadish Sahoo
Types of containers:
• There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog

By Jagadish Sahoo
Window
• The window is the container that have no borders and menu bars. You
must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.

Panel
• The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components.

Frame
• The Frame is the container that contain title bar and border and can have
menu bars. It can have other components like button, text field, scrollbar
etc. Frame is most widely used container while developing an AWT
application.

By Jagadish Sahoo
Useful Methods of Component Class

By Jagadish Sahoo
Java AWT Example
• To create simple AWT example, you need a frame. There are two ways
to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

By Jagadish Sahoo
AWT Example by Inheritance
public class AWTExample1 extends Frame {
AWTExample1() {
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
AWTExample1 f = new AWTExample1();
}
}
By Jagadish Sahoo
AWT
import java.awt.*;
Example by Association
class AWTExample2 {
AWTExample2() {
public static void main(String args[]) {
Frame f = new Frame();
AWTExample2 awt_obj = new AWTExample2();
Label l = new Label("Employee id:"); }
Button b = new Button("Submit"); }
TextField t = new TextField();
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b);
f.add(l);
f.add(t);
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
By Jagadish Sahoo
Event and Listener (Java Event Handling)
• Changing the state of an object is known as an event. For example,
click on button, dragging mouse etc. The java.awt.event package
provides many event classes and Listener interfaces for event
handling.

By Jagadish Sahoo
Java Event classes and Listener interfaces

By Jagadish Sahoo
Steps to perform Event Handling
• Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
• public void addActionListener(ActionListener a){}
MenuItem
• public void addActionListener(ActionListener a){}
TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
TextArea
• public void addTextListener(TextListener a){}

By Jagadish Sahoo
Checkbox
• public void addItemListener(ItemListener a){}
Choice
• public void addItemListener(ItemListener a){}
List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}

By Jagadish Sahoo
Java Event Handling Code
• We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class

By Jagadish Sahoo
Java event handling by implementing
ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{ public void actionPerformed(ActionEvent e){
TextField tf; tf.setText("Welcome");
AEvent(){ }
//create components public static void main(String args[]){
tf=new TextField(); new AEvent();
tf.setBounds(60,50,170,20); }
Button b=new Button("click me"); }
b.setBounds(100,120,80,30);
//register listener public void setBounds(int xaxis, int yaxis, int width, int
b.addActionListener(this);//passing current instance height); have been used in the above example that sets the
//add components and set size, layout and visibility position of the component it may be button, textfield etc.
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
By Jagadish Sahoo
Java event handling by outer class
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
import java.awt.event.*;
AEvent2(){
class Outer implements ActionListener{
tf=new TextField(); AEvent2 obj;
tf.setBounds(60,50,170,20); Outer(AEvent2 obj){
Button b=new Button("click me"); this.obj=obj;
b.setBounds(100,120,80,30); }
Outer o=new Outer(this); public void actionPerformed(ActionEvent e){
b.addActionListener(o);//passing outer class instance obj.tf.setText("welcome");
add(b);add(tf); }
setSize(300,300); }
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

By Jagadish Sahoo
Java event handling by anonymous class
import java.awt.*;
add(b);add(tf);
import java.awt.event.*; setSize(300,300);
class AEvent3 extends Frame{ setLayout(null);
TextField tf; setVisible(true);
}
AEvent3(){ public static void main(String args[]){
tf=new TextField(); new AEvent3();
}
tf.setBounds(60,50,170,20); }
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
By Jagadish Sahoo
Java AWT Button
• A button is basically a control component with a label that generates an
event when pushed.
• The Button class is used to create a labeled button that has platform
independent implementation.
• The application result in some action when the button is pushed.
• When we press a button and release it, AWT sends an instance
of ActionEvent to that button by calling processEvent on the button.
• The processEvent method of the button receives all the events, then it
passes an action event by calling its own method processActionEvent.
• This method passes the action event on to action listeners that are
interested in the action events generated by the button.

By Jagadish Sahoo
• To perform an action on a button being pressed and released, the
ActionListener interface needs to be implemented.
• The registered new listener can receive events from the button by
calling addActionListener method of the button.
• The Java application can use the button's action command as a
messaging protocol.
AWT Button Class Declaration
public class Button extends Component implements Accessible

By Jagadish Sahoo
Button Class Constructors

By Jagadish Sahoo
Button Class Methods

By Jagadish Sahoo
Java AWT Button Example
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");

// create instance of button with label


Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
} By Jagadish Sahoo
Java AWT Button Example
import javax.swing.*;
import java.awt.*;
// main method
import java.awt.event.*; public static void main (String args[])
public class ButtonExample2 {
{ new ButtonExample2();
Frame fObj; }
Button button1, button2, button3; }
// instantiating using the constructor
ButtonExample2() {
fObj = new Frame ("Frame to display buttons");
button1 = new Button();
button2 = new Button ("Click here");
button3 = new Button();
button3.setLabel("Button 3");
fObj.add(button1);
fObj.add(button2);
fObj.add(button3);
fObj.setLayout(new FlowLayout());
fObj.setSize(300,400);
fObj.setVisible(true);
}
By Jagadish Sahoo
Java AWT Button Example with ActionListener
// importing necessary libraries
import java.awt.*; // adding button the frame
import java.awt.event.*; f.add(b);
public class ButtonExample3 { // adding textfield the frame
f.add(tf);
public static void main(String[] args) {
// setting size, layout and visibility
// create instance of frame with the label f.setSize(400,400);
Frame f = new Frame("Button Example"); f.setLayout(null);
final TextField tf=new TextField(); f.setVisible(true);
tf.setBounds(50,50, 150,20); }
// create instance of button with label }
Button b=new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
By Jagadish Sahoo
Java AWT Label
• The object of the Label class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by a programmer but a user cannot edit it directly.
• It is called a passive control as it does not create any event when it is
accessed. To create a label, we need to create the object
of Label class.

By Jagadish Sahoo
AWT Label Fields
• The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in
center.

By Jagadish Sahoo
Label class Constructors

By Jagadish Sahoo
Label Class Methods

By Jagadish Sahoo
Java AWT Label Example
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
// initializing the labels
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
By Jagadish Sahoo
Java AWT TextField
• The object of a TextField class is a text component that allows a user
to enter a single line text and edit it. It inherits TextComponent class,
which further inherits Component class.
• When we enter a key in the text field (like key pressed, key released
or key typed), the event is sent to TextField.
• Then the KeyEvent is passed to the registered KeyListener. It can also
be done using ActionEvent; if the ActionEvent is enabled on the text
field, then the ActionEvent may be fired by pressing return key.
• The event is handled by the ActionListener interface.

By Jagadish Sahoo
AWT TextField Class Declaration
• public class TextField extends TextComponent
TextField Class constructors

By Jagadish Sahoo
TextField Class Methods

By Jagadish Sahoo
Java AWT TextField Example
import java.awt.*;
public class TextFieldExample1 {
public static void main(String args[]) {
Frame f = new Frame("TextField Example");
TextField t1, t2;
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
By Jagadish Sahoo
Java AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*; tf3.setEditable(false);
// Our class extends Frame class and implements ActionListener interface b1 = new Button("+");
public class TextFieldExample2 extends Frame implements ActionListener { b1.setBounds(50, 200, 50, 50);
// creating instances of TextField and Button class b2 = new Button("-");
b2.setBounds(120,200,50,50);
TextField tf1, tf2, tf3;
// adding action listener
Button b1, b2; b1.addActionListener(this);
// instantiating using constructor b2.addActionListener(this);
TextFieldExample2() { // adding components to frame
// instantiating objects of text field and button add(tf1);
// setting position of components in frame add(tf2);
add(tf3);
tf1 = new TextField();
add(b1);
tf1.setBounds(50, 50, 150, 20); add(b2);
tf2 = new TextField(); // setting size, layout and visibility of frame
tf2.setBounds(50, 100, 150, 20); setSize(300,300);
tf3 = new TextField(); setLayout(null);
tf3.setBounds(50, 150, 150, 20); setVisible(true);
}
By Jagadish Sahoo
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
// main method
public static void main(String[] args) {
new TextFieldExample2();
}
} By Jagadish Sahoo
Java AWT TextArea
• The object of a TextArea class is a multiline region that displays text. It
allows the editing of multiple line text. It inherits TextComponent
class.
• The text area allows us to type as much text as we want. When the
text in the text area becomes larger than the viewable area, the scroll
bar appears automatically which helps us to scroll the text up and
down, or right and left.

By Jagadish Sahoo
AWT TextArea Class Declaration

public class TextArea extends TextComponent

Fields of TextArea Class

The fields of java.awt.TextArea class are as follows:

• static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical
scrollbars.
• static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal
scrollbar.
• static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar.
• static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area.

By Jagadish Sahoo
By Jagadish Sahoo
By Jagadish Sahoo
By Jagadish Sahoo
Java AWT TextArea Example
import java.awt.*;
public class TextAreaExample
{
TextAreaExample() {
Frame f = new Frame();
TextArea area = new TextArea("Welcome to javatpoint");
area.setBounds(10, 30, 300, 300);
f.add(area);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
By Jagadish Sahoo
Java AWT TextArea Example with ActionListener
import java.awt.*;
b.addActionListener(this);
import java.awt.event.*;
add(l1);
add(l2);
public class TextAreaExample2 extends Frame implements ActionListener {
add(area);
Label l1, l2; add(b);
setSize(400, 450);
TextArea area;
setLayout(null);
Button b; setVisible(true);
TextAreaExample2() { }

public void actionPerformed(ActionEvent e) {


l1 = new Label();
String text = area.getText();
l1.setBounds(50, 50, 100, 30); String words[]=text.split("\\s");
l2 = new Label(); l1.setText("Words: "+words.length);
l2.setBounds(160, 50, 100, 30); l2.setText("Characters: "+text.length());
area = new TextArea(); }
public static void main(String[] args) {
area.setBounds(20, 100, 300, 300); new TextAreaExample2();
b = new Button("Count Words"); }
b.setBounds(100, 400, 100, 30); }
By Jagadish Sahoo
Java AWT Checkbox
• The Checkbox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a Checkbox changes its state
from "on" to "off" or from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable,
Accessible

By Jagadish Sahoo
Checkbox Class Constructors

By Jagadish Sahoo
Checkbox Class Methods

By Jagadish Sahoo
By Jagadish Sahoo
Java AWT Checkbox Example
import java.awt.*;
public class CheckboxExample1
{
CheckboxExample1() {
Frame f = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main (String args[])
{
new CheckboxExample1();
}
}
By Jagadish Sahoo
Java AWT Checkbox Example with ItemListener
import java.awt.*; checkbox1.addItemListener(new ItemListener() {
import java.awt.event.*; public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
public class CheckboxExample2 + (e.getStateChange()==1?"checked":"unchecked"));
{ }
CheckboxExample2() { });
checkbox2.addItemListener(new ItemListener() {
Frame f = new Frame ("CheckBox Example"); public void itemStateChanged(ItemEvent e) {
final Label label = new Label(); label.setText("Java Checkbox: "
label.setAlignment(Label.CENTER); + (e.getStateChange()==1?"checked":"unchecked"));
}
label.setSize(400,100);
});
Checkbox checkbox1 = new Checkbox("C++"); f.setSize(400,400);
checkbox1.setBounds(100, 100, 50, 50); f.setLayout(null);
Checkbox checkbox2 = new Checkbox("Java"); f.setVisible(true);
}
checkbox2.setBounds(100, 150, 50, 50); public static void main(String args[])
f.add(checkbox1); {
f.add(checkbox2); new CheckboxExample2();
}
f.add(label); }
By Jagadish Sahoo
Java AWT CheckboxGroup
• The object of CheckboxGroup class is used to group together a set
of Checkbox. At a time only one check box button is allowed to be in
"on" state and remaining check box button in "off" state. It inherits
the object class.
• Note: CheckboxGroup enables you to create radio buttons in AWT.
There is no special control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
public class CheckboxGroup extends Object implements Serializable

By Jagadish Sahoo
Java AWT CheckboxGroup Example
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
By Jagadish Sahoo
Java AWT CheckboxGroup Example with
ItemListener f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
import java.awt.*; f.setVisible(true);
import java.awt.event.*; checkBox1.addItemListener(new ItemListener() {
public class CheckboxGroupExample public void itemStateChanged(ItemEvent e) {
{ label.setText("C++ checkbox: Checked");
CheckboxGroupExample(){ }
Frame f= new Frame("CheckboxGroup Example"); });
checkBox2.addItemListener(new ItemListener() {
final Label label = new Label();
public void itemStateChanged(ItemEvent e) {
label.setAlignment(Label.CENTER); label.setText("Java checkbox: Checked");
label.setSize(400,100); }
CheckboxGroup cbg = new CheckboxGroup(); });
Checkbox checkBox1 = new Checkbox("C++", cbg, false); }
checkBox1.setBounds(100,100, 50,50); public static void main(String args[])
{
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
new CheckboxGroupExample();
checkBox2.setBounds(100,150, 50,50); }
}
By Jagadish Sahoo
Java AWT Choice
• The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Accessible

Choice Class constructor

By Jagadish Sahoo
Choice Class Methods

By Jagadish Sahoo
Java AWT Choice Example
import java.awt.*;
public class ChoiceExample1 { public static void main(String args[])
ChoiceExample1() { {
new ChoiceExample1();
Frame f = new Frame();
}
Choice c = new Choice();
}
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
By Jagadish Sahoo
Java AWT Choice Example with ActionListener
import java.awt.*;
f.add(b);
import java.awt.event.*;
f.setSize(400, 400);
public class ChoiceExample2 {
f.setLayout(null);
ChoiceExample2() {
f.setVisible(true);
Frame f = new Frame(); b.addActionListener(new ActionListener() {
final Label label = new Label(); public void actionPerformed(ActionEvent e) {
label.setAlignment(Label.CENTER);
label.setSize(400, 100); String data = "Programming language Selected: "+
Button b = new Button("Show"); c.getItem(c.getSelectedIndex());
b.setBounds(200, 100, 50, 20); label.setText(data);
final Choice c = new Choice(); }
c.setBounds(100, 100, 75, 75); });
c.add("C"); }
c.add("C++");
c.add("Java"); // main method
c.add("PHP"); public static void main(String args[])
c.add("Android"); {
f.add(c); new ChoiceExample2();
f.add(label); }
}
By Jagadish Sahoo
Java AWT List
• The object of List class represents a list of text items. With the help of the
List class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible

By Jagadish Sahoo
AWT List Class Constructors

By Jagadish Sahoo
List Class Methods

By Jagadish Sahoo
Java AWT List Example
import java.awt.*;
public class ListExample1
{
ListExample1() {
Frame f = new Frame();
List l1 = new List(5);
l1.setBounds(100, 100, 75, 75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample1();
}
}
By Jagadish Sahoo
Java AWT List Example with ActionListener
import java.awt.*; f.add(l1);
import java.awt.event.*; f.add(l2);
public class ListExample2 f.add(label);
{ f.add(b);
ListExample2() { f.setSize(450,450);
Frame f = new Frame(); f.setLayout(null);
final Label label = new Label(); f.setVisible(true);
label.setAlignment(Label.CENTER); b.addActionListener(new ActionListener() {
label.setSize(500, 100); public void actionPerformed(ActionEvent e) {
Button b = new Button("Show");
String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex());
b.setBounds(200, 150, 80, 30);
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()) {
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70); data += frame + " ";
l1.add("C"); }
l1.add("C++"); label.setText(data);
l1.add("Java"); }
l1.add("PHP"); });
}
final List l2=new List(4, true); public static void main(String args[])
l2.setBounds(100, 200, 70, 70); {
l2.add("Turbo C++"); new ListExample2();
l2.add("Spring"); }
l2.add("Hibernate"); }
l2.add("CodeIgniter"); By Jagadish Sahoo
Java AWT Canvas
• The Canvas class controls and represents a blank rectangular area
where the application can draw or trap input events from the user. It
inherits the Component class.

By Jagadish Sahoo
import java.awt.*; public static void main(String args[])
public class CanvasExample {
{ new CanvasExample();
public CanvasExample() }
{ }
Frame f = new Frame("Canvas Example"); class MyCanvas extends Canvas
f.add(new MyCanvas()); {
public MyCanvas() {
f.setLayout(null); setBackground (Color.GRAY);
f.setSize(400, 400); setSize(300, 200);
f.setVisible(true); }
} public void paint(Graphics g)
{

// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}

By Jagadish Sahoo
Java AWT MenuItem and Menu
• The object of MenuItem class adds a simple labeled menu item on menu.
The items used in a menu must belong to the MenuItem or any of its
subclass.
• The object of Menu class is a pull down menu component which is displayed
on the menu bar. It inherits the MenuItem class.
AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessible

By Jagadish Sahoo
Java AWT MenuItem and Menu Example
import java.awt.*;
class MenuExample submenu.add(i4);
{ submenu.add(i5);
menu.add(submenu);
MenuExample(){ mb.add(menu);
f.setMenuBar(mb);
Frame f= new Frame("Menu and MenuItem Example"); f.setSize(400,400);
MenuBar mb=new MenuBar(); f.setLayout(null);
f.setVisible(true);
Menu menu=new Menu("Menu"); }
public static void main(String args[])
Menu submenu=new Menu("Sub Menu"); {
MenuItem i1=new MenuItem("Item 1"); new MenuExample();
}
MenuItem i2=new MenuItem("Item 2"); }
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);

By Jagadish Sahoo
Java AWT Panel
• The Panel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the Container
class.
• It doesn't have title bar.
AWT Panel class declaration
public class Panel extends Container implements Accessible

By Jagadish Sahoo
Java AWT Panel Example
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
By Jagadish Sahoo
Java AWT Dialog
• The Dialog control represents a top level window with a border and a
title used to take some form of input from the user. It inherits the
Window class.
• Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
• Frame and Dialog both inherits Window class. Frame has maximize
and minimize buttons but Dialog doesn't have.

By Jagadish Sahoo
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
By Jagadish Sahoo
Java WindowListener Interface
• The Java WindowListener is notified whenever you change the state
of window. It is notified against WindowEvent. The WindowListener
interface is found in java.awt.event package. It has 7 methods.
1. public abstract void windowActivated(WindowEvent e);
2. public abstract void windowClosed(WindowEvent e);
3. public abstract void windowClosing(WindowEvent e);
4. public abstract void windowDeactivated(WindowEvent e);
5. public abstract void windowDeiconified(WindowEvent e);
6. public abstract void windowIconified(WindowEvent e);
7. public abstract void windowOpened(WindowEvent e);

By Jagadish Sahoo
public void windowClosed(WindowEvent arg0) {
import java.awt.*;
System.out.println("closed");
import java.awt.event.WindowEvent;
}
import java.awt.event.WindowListener;
public void windowClosing(WindowEvent arg0) {
public class WindowExample extends Frame
System.out.println("closing");
implements WindowListener{
dispose();
WindowExample(){
}
addWindowListener(this);
public void windowDeactivated(WindowEvent arg0) {
System.out.println("deactivated");
setSize(400,400);
}
setLayout(null);
public void windowDeiconified(WindowEvent arg0) {
setVisible(true);
System.out.println("deiconified");
}
}
public void windowIconified(WindowEvent arg0) {
public static void main(String[] args) {
System.out.println("iconified");
new WindowExample();
}
}
public void windowOpened(WindowEvent arg0) {
public void windowActivated(WindowEvent arg0) {
System.out.println("opened");
System.out.println("activated");
}
}
}

By Jagadish Sahoo
Java Adapter Classes
• Java adapter classes provide the default implementation of
listener interfaces. If you inherit the adapter class, you will not be
forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
• The adapter classes are found
in java.awt.event, java.awt.dnd and javax.swing.event packages.

By Jagadish Sahoo
java.awt.event Adapter classes

By Jagadish Sahoo
Java WindowAdapter Example
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
By Jagadish Sahoo
File Handling in Java
• In Java, a File is an abstract data type. A named location used to store
related information is known as a File. There are several File
Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.
• Before understanding the File operations, it is required that we should
have knowledge of Stream and File methods.

By Jagadish Sahoo
Stream
• A series of data is referred to as a stream. Stream is classified into
two types, i.e., Byte Stream and Character Stream.

By Jagadish Sahoo
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process
with a byte stream is a process in which an input is provided and
executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling
process with a character stream is a process in which an input is
provided and executed with the character data.

By Jagadish Sahoo
Java File Class Methods

By Jagadish Sahoo
By Jagadish Sahoo
File Operations

By Jagadish Sahoo
Create a File
• Create a File operation is performed to create a new file. We use
the createNewFile() method of file. The createNewFile() method
returns true when it successfully creates a new file and returns false
when the file already exists.

By Jagadish Sahoo
import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:FileOperationExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
} By Jagadish Sahoo
Get File Information
import java.io.File;
class FileInfo {
public static void main(String[] args) {
File f0 = new File("D:FileOperationExample.txt");
if (f0.exists()) {
System.out.println("The name of the file is: " + f0.getName());
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
System.out.println("Is file writeable?: " + f0.canWrite());
System.out.println("Is file readable " + f0.canRead());
System.out.println("The size of the file in bytes is: " + f0.length());
} else {
System.out.println("The file does not exist.");
}
}
}
By Jagadish Sahoo
Write to a File
import java.io.FileWriter;
import java.io.IOException;
class WriteToFile {
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
fwrite.write("A named location used to store related information is referred to as a File.");
fwrite.close();
System.out.println("Content is successfully wrote to the file.");
} catch (IOException e) {
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}

By Jagadish Sahoo
Read from a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ReadFromFile {
public static void main(String[] args) {
try {
File f1 = new File("D:FileOperationExample.txt");
Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine()) {
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
dataReader.close();
} catch (FileNotFoundException exception) {
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
}
}
By Jagadish Sahoo
Delete a File
import java.io.File;
class DeleteFile {
public static void main(String[] args) {
File f0 = new File("D:FileOperationExample.txt");
if (f0.delete()) {
System.out.println(f0.getName()+ " file is deleted successfully.");
} else {
System.out.println("Unexpected error found in deletion of the file.");
}
}
}
By Jagadish Sahoo
Java FileInputStream Class
• The FileInputStream class of the java.io package can be used to read
data (in bytes) from files.
• It extends the InputStream abstract class.
Methods of FileInputStream
• read() Method
• read() - reads a single byte from the file
• read(byte[] array) - reads the bytes from the file and stores in the
specified array
• read(byte[] array, int start, int length) - reads the number of bytes
equal to length from the file and stores in the specified array starting
from the position start
By Jagadish Sahoo
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
FileInputStream input = new FileInputStream("input.txt");
System.out.println("Data in the file: ");
int i = input.read();
while(i != -1) {
System.out.print((char)i);
i = input.read();
}
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
} By Jagadish Sahoo
available() Method
To get the number of available bytes, we can use the available() method.
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
FileInputStream input = new FileInputStream("input.txt");
System.out.println("Available bytes at the beginning: " + input.available());
input.read();
input.read();
input.read();
System.out.println("Available bytes at the end: " + input.available());
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
} By Jagadish Sahoo
skip() Method
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) {
try {
FileInputStream input = new FileInputStream("input.txt");
input.skip(5);
System.out.println("Input stream after skipping 5 bytes:");
int i = input.read();
while (i != -1) {
System.out.print((char) i);
i = input.read();
}
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
} By Jagadish Sahoo
}
Java FileOutputStream Class
• The FileOutputStream class of the java.io package can be used to
write data (in bytes) to the files.
• It extends the OutputStream abstract class.

By Jagadish Sahoo
Create a FileOutputStream
1. Using the path to file
// Including the boolean parameter
FileOutputStream output = new FileOutputStream(String path, boolean
value);
// Not including the boolean parameter
FileOutputStream output = new FileOutputStream(String path);
• Created an output stream that will be linked to the file specified by the
path.
• value is an optional boolean parameter. If it is set to true, the new data
will be appended to the end of the existing data in the file. Otherwise, the
new data overwrites the existing data in the file.

By Jagadish Sahoo
2. Using an object of the file
FileOutputStream output = new FileOutputStream(File fileObject);
Created an output stream that will be linked to the file specified by
fileObject.
Methods of FileOutputStream
write() Method
• write() - writes the single byte to the file output stream
• write(byte[] array) - writes the bytes from the specified array to the
output stream
• write(byte[] array, int start, int length) - writes the number of bytes
equal to length to the output stream from an array starting from the
position start

By Jagadish Sahoo
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
String data = "This is a line of text inside the file.";
try {
FileOutputStream output = new FileOutputStream("output.txt");
byte[] array = data.getBytes();
output.write(array);
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
By Jagadish Sahoo
flush() Method
To clear the output stream, we can use the flush() method. This method forces the
output stream to write all data to the destination.
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream out = null;
String data = "This is demo of flush method";
try {
out = new FileOutputStream(" flush.txt");
out.write(data.getBytes());
out.flush();
out.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
By Jagadish Sahoo
Copy files using i/o streams
import java.io.FileInputStream;
import java.io.FileOutputStream;
class Main {
public static void main(String[] args) {
byte[] array = new byte[50];
try {
FileInputStream sourceFile = new FileInputStream("input.txt");
FileOutputStream destFile = new FileOutputStream("newFile");
sourceFile.read(array);
destFile.write(array);
System.out.println("The input.txt file is copied to newFile.");
sourceFile.close();
destFile.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
By Jagadish Sahoo
Java Swing
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on the top of
AWT (Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.

By Jagadish Sahoo
Difference between AWT and Swing

By Jagadish Sahoo
Simple Java Swing Example
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

By Jagadish Sahoo
Java JButton
• The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action
when the button is pushed. It inherits AbstractButton class.

By Jagadish Sahoo
Commonly used Methods of AbstractButton class:

By Jagadish Sahoo
Java JButton Example with ActionListener
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
By Jagadish Sahoo
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
By Jagadish Sahoo
Java JLabel
• The object of JLabel class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.

By Jagadish Sahoo
Commonly used Constructors:

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JLabel Example with ActionListener
import javax.swing.*;
import java.awt.*; public void actionPerformed(ActionEvent e) {
import java.awt.event.*; try{
public class LabelExample extends Frame implements ActionListener{ String host=tf.getText();
JTextField tf; JLabel l; JButton b; String ip=java.net.InetAddress.getByName(host)
LabelExample(){ .getHostAddress();
tf=new JTextField(); l.setText("IP of "+host+" is: "+ip);
tf.setBounds(50,50, 150,20); }catch(Exception ex){System.out.println(ex);}
l=new JLabel(); }
l.setBounds(50,100, 250,20); public static void main(String[] args) {
b=new JButton("Find IP"); new LabelExample();
b.setBounds(50,150,95,30); }}
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}

By Jagadish Sahoo
Java JTextField
• The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits JTextComponent class.

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JTextField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
public void actionPerformed(ActionEvent e) {
JTextField tf1,tf2,tf3; String s1=tf1.getText();
JButton b1,b2; String s2=tf2.getText();
TextFieldExample(){
int a=Integer.parseInt(s1);
JFrame f= new JFrame();
tf1=new JTextField(); int b=Integer.parseInt(s2);
tf1.setBounds(50,50,150,20); int c=0;
tf2=new JTextField(); if(e.getSource()==b1){
tf2.setBounds(50,100,150,20);
c=a+b;
tf3=new JTextField();
tf3.setBounds(50,150,150,20); }else if(e.getSource()==b2){
tf3.setEditable(false); c=a-b;
b1=new JButton("+"); }
b1.setBounds(50,200,50,50);
String result=String.valueOf(c);
b2=new JButton("-");
b2.setBounds(120,200,50,50); tf3.setText(result);
b1.addActionListener(this); }
b2.addActionListener(this); public static void main(String[] args) {
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
new TextFieldExample();
f.setSize(300,300);
f.setLayout(null); }}
f.setVisible(true);
}
By Jagadish Sahoo
Java JTextArea
• The object of a JTextArea class is a multi line region that displays text.
It allows the editing of multiple line text. It inherits JTextComponent
class

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JTextArea Example with ActionListener
import javax.swing.*;
import java.awt.event.*; public void actionPerformed(ActionEvent e){
public class TextAreaExample implements ActionListener{ String text=area.getText();
JLabel l1,l2; String words[]=text.split("\\s");
JTextArea area; l1.setText("Words: "+words.length);
JButton b; l2.setText("Characters: "+text.length());
TextAreaExample() { }
JFrame f= new JFrame(); public static void main(String[] args) {
l1=new JLabel(); new TextAreaExample();
l1.setBounds(50,25,100,30); }
l2=new JLabel(); }
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
} By Jagadish Sahoo
Java JPasswordField
• The object of a JPasswordField class is a text component specialized
for password entry. It allows the editing of a single line of text. It
inherits JTextField class.

By Jagadish Sahoo
Java JPasswordField Example with ActionListener
import javax.swing.*;
final JTextField text = new JTextField();
import java.awt.event.*; text.setBounds(100,20, 100,30);
public class PasswordFieldExample { f.add(value); f.add(l1); f.add(label); f.add(l2); f.ad
public static void main(String[] args) { d(b); f.add(text);
f.setSize(300,300);
JFrame f=new JFrame("Password Field Example"); f.setLayout(null);
final JLabel label = new JLabel(); f.setVisible(true);
b.addActionListener(new ActionListener() {
label.setBounds(20,150, 200,50); public void actionPerformed(ActionEvent e) {
final JPasswordField value = new JPasswordField(); String data = "Username " + text.getText();
value.setBounds(100,75,100,30); data += ", Password: "
+ new String(value.getPassword());
JLabel l1=new JLabel("Username:"); label.setText(data);
l1.setBounds(20,20, 80,30); }
});
JLabel l2=new JLabel("Password:"); }
l2.setBounds(20,75, 80,30); }
JButton b = new JButton("Login");
b.setBounds(100,120, 80,30);
By Jagadish Sahoo
Java JCheckBox
• The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state
from "on" to "off" or from "off" to "on ".
• It inherits JToggleButton class.

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JCheckBox Example with ItemListener
import javax.swing.*;
import java.awt.event.*; checkbox2.addItemListener(new ItemListener() {
public class CheckBoxExample public void itemStateChanged(ItemEvent e) {
{ label.setText("Java Checkbox: "
CheckBoxExample(){ + (e.getStateChange()==1?"checked":"unchecked"));
JFrame f= new JFrame("CheckBox Example"); }
final JLabel label = new JLabel();
});
f.setSize(400,400);
label.setHorizontalAlignment(JLabel.CENTER);
f.setLayout(null);
label.setSize(400,100);
f.setVisible(true);
JCheckBox checkbox1 = new JCheckBox("C++");
}
checkbox1.setBounds(150,100, 50,50);
public static void main(String args[])
JCheckBox checkbox2 = new JCheckBox("Java");
{
checkbox2.setBounds(150,150, 50,50);
new CheckBoxExample();
f.add(checkbox1); f.add(checkbox2); f.add(label); }
checkbox1.addItemListener(new ItemListener() { }
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
By Jagadish Sahoo
Java JCheckBox Example: Food Order
import javax.swing.*; public void actionPerformed(ActionEvent e){
import java.awt.event.*;
float amount=0;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
String msg="";
JCheckBox cb1,cb2,cb3; if(cb1.isSelected()){
JButton b; amount+=100;
CheckBoxExample(){ msg="Pizza: 100\n";
l=new JLabel("Food Ordering System");
}
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
if(cb2.isSelected()){
cb1.setBounds(100,100,150,20); amount+=30;
cb2=new JCheckBox("Burger @ 30"); msg+="Burger: 30\n";
cb2.setBounds(100,150,150,20);
}
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
if(cb3.isSelected()){
b=new JButton("Order"); amount+=10;
b.setBounds(100,250,80,30); msg+="Tea: 10\n";
b.addActionListener(this);
}
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
msg+="-----------------\n";
setLayout(null); JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
setVisible(true); }
setDefaultCloseOperation(EXIT_ON_CLOSE); public static void main(String[] args) {
}
new CheckBoxExample();
}
By Jagadish Sahoo
}
Java JRadioButton
• The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
• It should be added in ButtonGroup to select one radio button only.

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JRadioButton Example with ActionListener
import javax.swing.*;
import java.awt.event.*; public void actionPerformed(ActionEvent e){
class RadioButtonExample extends JFrame implements ActionListener{ if(rb1.isSelected()){
JRadioButton rb1,rb2;
JOptionPane.showMessageDialog(this,"You are Male.");
JButton b;
}
RadioButtonExample(){
if(rb2.isSelected()){
rb1=new JRadioButton("Male");
JOptionPane.showMessageDialog(this,"You are Female.");
rb1.setBounds(100,50,100,30);
}
rb2=new JRadioButton("Female");
}
rb2.setBounds(100,100,100,30);
public static void main(String args[]){
ButtonGroup bg=new ButtonGroup();
new RadioButtonExample();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
}}
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}

By Jagadish Sahoo
Java JComboBox
• The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu. It
inherits JComponent class.

By Jagadish Sahoo
Commonly used Methods:

By Jagadish Sahoo
Java JComboBox Example with ActionListener
import javax.swing.*; b.addActionListener(new ActionListener() {
import java.awt.event.*; public void actionPerformed(ActionEvent e) {
public class ComboBoxExample { String data = "Programming language Selected: "
JFrame f; + cb.getItemAt(cb.getSelectedIndex());
ComboBoxExample(){ label.setText(data);
f=new JFrame("ComboBox Example"); }
final JLabel label = new JLabel(); });
label.setHorizontalAlignment(JLabel.CENTER); }
label.setSize(400,100); public static void main(String[] args) {
JButton b=new JButton("Show"); new ComboBoxExample();
b.setBounds(200,100,75,20); }
String languages[]={"C","C++","C#","Java","PHP"}; }
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);

By Jagadish Sahoo
Java JTable
• The JTable class is used to display data in tabular form. It is composed
of rows and columns.

By Jagadish Sahoo
Java JTable Example with ListSelectionListener
import javax.swing.*;
import javax.swing.event.*; int[] columns = jt.getSelectedColumns();
public class TableExample { for (int i = 0; i < row.length; i++) {
public static void main(String[] a) { for (int j = 0; j < columns.length; j++) {
JFrame f = new JFrame("Table Example"); Data = (String) jt.getValueAt(row[i], columns[j]);
String data[][]={ {"101","Amit","670000"}, }}
{"102","Jai","780000"}, System.out.println("Table element selected is: " + Data);
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"}; }
final JTable jt=new JTable(data,column); });
jt.setCellSelectionEnabled(true); JScrollPane sp=new JScrollPane(jt);
ListSelectionModel select= jt.getSelectionModel();
f.add(sp);
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
f.setSize(300, 200);
f.setVisible(true);
select.addListSelectionListener(new ListSelectionListener() {
}
public void valueChanged(ListSelectionEvent e) {
}
String Data = null;
int[] row = jt.getSelectedRows();

By Jagadish Sahoo
l2.addElement("YII");

Java JList final JList<String> list2 = new JList<>(l2);


list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
import javax.swing.*; f.setSize(450,450);
import java.awt.event.*; f.setLayout(null);
f.setVisible(true);
public class ListExample
b.addActionListener(new ActionListener() {
{ public void actionPerformed(ActionEvent e) {
ListExample(){ String data = "";
JFrame f= new JFrame(); if (list1.getSelectedIndex() != -1) {
data = "Programming language Selected: " + list1.getSelectedValue();
final JLabel label = new JLabel();
label.setText(data);
label.setSize(500,100); }
JButton b=new JButton("Show"); if(list2.getSelectedIndex() != -1){
b.setBounds(200,150,80,30); data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValues()){
final DefaultListModel<String> l1 = new DefaultListModel<>();
data += frame + " ";
l1.addElement("C"); }
l1.addElement("C++"); }
l1.addElement("Java"); label.setText(data);
l1.addElement("PHP");
}
});
final JList<String> list1 = new JList<>(l1); }
list1.setBounds(100,100, 75,75); public static void main(String args[])
DefaultListModel<String> l2 = new DefaultListModel<>(); {
l2.addElement("Turbo C++");
new ListExample();
}}
l2.addElement("Struts");
l2.addElement("Spring");
By Jagadish Sahoo
Java JOptionPane
• The JOptionPane class is used to provide standard dialog boxes such as message dialog
box, confirm dialog box and input dialog box. These dialog boxes are used to display
information or get input from the user. The JOptionPane class inherits JComponent class.
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

By Jagadish Sahoo
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

By Jagadish Sahoo
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

By Jagadish Sahoo
import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
By Jagadish Sahoo
Java JMenuBar, JMenu and JMenuItem
• The JMenuBar class is used to display menubar on the window or
frame. It may have several menus.
• The object of JMenu class is a pull down menu component which is
displayed from the menu bar. It inherits the JMenuItem class.
• The object of JMenuItem class adds a simple labeled menu item. The
items used in a menu must belong to the JMenuItem or any of its
subclass.

By Jagadish Sahoo
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
import javax.swing.*;
mb.add(file);mb.add(edit);mb.add(help);
import java.awt.event.*;
ta=new JTextArea();
public class MenuExample implements ActionListener{
ta.setBounds(5,5,360,320);
JFrame f;
f.add(mb);f.add(ta);
JMenuBar mb;
f.setJMenuBar(mb);
JMenu file,edit,help;
f.setLayout(null);
JMenuItem cut,copy,paste,selectAll;
f.setSize(400,400);
JTextArea ta;
f.setVisible(true);
MenuExample(){
}
f=new JFrame();
public void actionPerformed(ActionEvent e) {
cut=new JMenuItem("cut");
if(e.getSource()==cut)
copy=new JMenuItem("copy");
ta.cut();
paste=new JMenuItem("paste");
if(e.getSource()==paste)
selectAll=new JMenuItem("selectAll");
ta.paste();
cut.addActionListener(this);
if(e.getSource()==copy)
copy.addActionListener(this);
ta.copy();
paste.addActionListener(this);
if(e.getSource()==selectAll)
selectAll.addActionListener(this);
ta.selectAll();
mb=new JMenuBar();
}
file=new JMenu("File");
public static void main(String[] args) {
edit=new JMenu("Edit");
new MenuExample();
help=new JMenu("Help");
By}Jagadish Sahoo
}
Java LayoutManagers
• The LayoutManagers are used to arrange components in a particular
manner. The Java LayoutManagers facilitates us to control the
positioning and size of the components in GUI forms. LayoutManager
is an interface that is implemented by all the classes of layout
managers.

By Jagadish Sahoo
• There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

By Jagadish Sahoo
Java BorderLayout
• The BorderLayout is used to arrange the components in five regions:
north, south, east, west, and center. Each region (area) may contain
one component only. It is the default layout of a frame or window.
The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

By Jagadish Sahoo
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
By Jagadish Sahoo
Java GridLayout
• The Java GridLayout class is used to arrange the components in a
rectangular grid. One component is displayed in each rectangle.

By Jagadish Sahoo
import java.awt.*;
// adding buttons to the frame
import javax.swing.*; f.add(b1); f.add(b2); f.add(b3);
public class MyGridLayout{ f.add(b4); f.add(b5); f.add(b6);
f.add(b7); f.add(b8); f.add(b9);
JFrame f; f.setLayout(new GridLayout(3,3));
MyGridLayout(){ f.setSize(300,300);
f.setVisible(true);
f=new JFrame(); }
JButton b1=new JButton("1"); public static void main(String[] args) {
new MyGridLayout();
JButton b2=new JButton("2"); }
JButton b3=new JButton("3"); }
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
By Jagadish Sahoo
Java FlowLayout
• The Java FlowLayout class is used to arrange the components in a line,
one after another (in a flow). It is the default layout of the applet or
panel.
• Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

By Jagadish Sahoo
import java.awt.*; JButton b8 = new JButton("8");
import javax.swing.*; JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
public class FlowLayoutExample frameObj.add(b1); frameObj.add(b2); frameObj.add(b3);
{ frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7);
JFrame frameObj; frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
FlowLayoutExample() frameObj.setLayout(new FlowLayout());
{
frameObj = new JFrame(); frameObj.setSize(300, 300);
frameObj.setVisible(true);
JButton b1 = new JButton("1"); }
JButton b2 = new JButton("2");
JButton b3 = new JButton("3"); // main method
JButton b4 = new JButton("4"); public static void main(String argvs[])
JButton b5 = new JButton("5"); {
JButton b6 = new JButton("6"); new FlowLayoutExample();
JButton b7 = new JButton("7"); }

By Jagadish Sahoo
Java CardLayout
• The Java CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a card
that is why it is known as CardLayout.
Commonly Used Methods of CardLayout Class
• public void next(Container parent): is used to flip to the next card of the
given container.
• public void previous(Container parent): is used to flip to the previous card of
the given container.
• public void first(Container parent): is used to flip to the first card of the
given container.
• public void last(Container parent): is used to flip to the last card of the given
container.
• public void show(Container parent, String name): is used to flip to the
specified card with the given name.
By Jagadish Sahoo
JPanel jPanel4 = new JPanel();
JLabel jLabel1 = new JLabel("C1");
import java.awt.*; JLabel jLabel2 = new JLabel("C2");
import java.awt.event.ActionEvent; JLabel jLabel3 = new JLabel("C3");
import java.awt.event.ActionListener;
import javax.swing.*; JLabel jLabel4 = new JLabel("C4");
jPanel1.add(jLabel1);
public class CardLayoutExample3 extends JFrame
{ jPanel2.add(jLabel2);
jPanel3.add(jLabel3);
private int currCard = 1; jPanel4.add(jLabel4);
private CardLayout cObjl; cPanel.add(jPanel1, "1");
cPanel.add(jPanel2, "2");
public CardLayoutExample3() cPanel.add(jPanel3, "3");
{ cPanel.add(jPanel4, "4");
setTitle("Card Layout Methods"); JPanel btnPanel = new JPanel();
setSize(310, 160); JButton firstButton = new JButton("First");
JPanel cPanel = new JPanel(); JButton nextButton = new JButton("->");
cObjl = new CardLayout(); JButton previousButton = new JButton("<-");
cPanel.setLayout(cObjl); JButton lastButton = new JButton("Last");
btnPanel.add(firstButton);
JPanel jPanel1 = new JPanel(); btnPanel.add(nextButton);
JPanel jPanel2 = new JPanel();
By Jagadish Sahoo
JPanel jPanel3 = new JPanel(); btnPanel.add(previousButton);
Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.

• The components may not be of the same size. Each GridBagLayout


object maintains a dynamic, rectangular grid of cells. Each component
occupies one or more cells known as its display area. Each component
associates an instance of GridBagConstraints. With the help of the
constraints object, we arrange the component's display area on the
grid. The GridBagLayout manages each component's minimum and
preferred sizes in order to determine the component's size.
GridBagLayout components are also arranged in the rectangular grid
but can have many different sizes and can occupy multiple rows or
columns.

By Jagadish Sahoo
import java.awt.Button; gbc.gridx = 1;
import java.awt.GridBagConstraints; gbc.gridy = 0;
import java.awt.GridBagLayout; this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
import javax.swing.*; gbc.ipady = 20;
public class GridBagLayoutExample extends JFrame{ gbc.gridx = 0;
public static void main(String[] args) { gbc.gridy = 1;
GridBagLayoutExample a = new this.add(new Button("Button Three"), gbc);
GridBagLayoutExample(); gbc.gridx = 1;
} gbc.gridy = 1;
public GridBagLayoutExample() { this.add(new Button("Button Four"), gbc);
GridBagLayoutgrid = new GridBagLayout(); gbc.gridx = 0;
GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 2;
setLayout(grid); gbc.fill = GridBagConstraints.HORIZONTAL;
setTitle("GridBag Layout Example"); gbc.gridwidth = 2;
GridBagLayout layout = new GridBagLayout(); this.add(new Button("Button Five"), gbc);
this.setLayout(layout); setSize(300, 300);
gbc.fill = GridBagConstraints.HORIZONTAL; setPreferredSize(getSize());
gbc.gridx = 0; setVisible(true);
gbc.gridy = 0; setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(new Button("Button One"), gbc);
}
By Jagadish Sahoo
}

You might also like