You are on page 1of 267

UNIT 1: Introduction to Java

Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as few implementation
dependencies as possible. It is intended to let application developers write once, and run anywhere (WORA),
meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java
was first released in 1995 and is widely used for developing applications for desktop, web, and mobile devices. Java
is known for its simplicity, robustness, and security features, making it a popular choice for enterprise-level
applications.

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995 and later acquired by Oracle
Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming
easy. It helps to create reusable code and modular programs. Java is a class-based, object-oriented programming
language and is designed to have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of
Java is similar to c/c++.

History: Java’s history is very interesting. It is a programming language created in 1991. James Gosling, Mike
Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java language in
1991. Sun Microsystems released its first public implementation in 1996 as Java 1.0. It provides no-cost -run-times
on popular platforms. Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for different types of
platforms.

In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but it soon withdrew from
the process. At one time, Sun made most of its Java implementations available without charge, despite their
proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products
such as the Java Enterprise System.

On November 13, 2006, Sun released much of its Java virtual machine as free, open-source software. On May 8,
2007, Sun finished the process, making all of its JVM’s core code available under open-source distribution terms.

The principles for creating java were simple, robust, secured, high-performance, portable, multi-threaded,
interpreted, dynamic, etc. In 1995 Java was developed by James Gosling, who is known as the Father of Java.
Currently, Java is used in mobile devices, internet programming, games, e-business, etc.

Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office. Also, Oak is an image of
solidarity and picked as a national tree of numerous nations like the U.S.A., France, Germany, Romania, etc. But they
had to later rename it as “JAVA” as it was already a trademark by Oak Technologies. “JAVA” Gosling and his team
did a brainstorm session and after the session, they came up with several names such as JAVA, DNA, SILK, RUBY,
etc. Java name was decided after much discussion since it was so unique. The name Java originates from a sort
of espresso bean, Java. Gosling came up with this name while having a coffee near his office. Java was created on
the principles like Robust, Portable, Platform Independent, High Performance, Multithread, etc. and was called one
of the Ten Best Products of 1995 by the TIME MAGAZINE. Currently, Java is used in internet programming, mobile
devices, games, e-business solutions, etc.

The Java language has experienced a few changes since JDK 1.0 just as various augmentations of classes and
packages to the standard library. In Addition to the language changes, considerably more sensational changes have
been made to the Java Class Library throughout the years, which has developed from a couple of hundred classes in
JDK 1.0 to more than three thousand in J2SE 5.
UNIT 1: Introduction to Java

Implementation of a Java application program involves a following step. They include:


1. Creating the program
2. Compiling the program
3. Running the program

Remember that, before we begin creating the program, the Java Development Kit (JDK) must be properly installed
on our system and also path will be set.
• Creating Program
We can create a program using Text Editor (Notepad) or IDE (NetBeans)
class Test
{
public static void main(String []args)
{
System.out.println(“My First Java Program.”);
}
};

File -> Save -> d:\Test.java

• Compiling the program


To compile the program, we must run the Java compiler (javac), with the name of the source file on “command
prompt” like as follows

If everything is OK, the “javac” compiler creates a file called “Test.class” containing byte code of the program.

• Running the program


We need to use the Java Interpreter to run a program.
UNIT 1: Introduction to Java
Java programming language is named JAVA. Why?

After the name OAK, the team decided to give it a new name to it and the suggested words were Silk, Jolt,
revolutionary, DNA, dynamic, etc. These all names were easy to spell and fun to say, but they all wanted the name to
reflect the essence of technology. In accordance with James Gosling, Java the among the top names along with Silk,
and since java was a unique name so most of them preferred it.

Java is the name of an island in Indonesia where the first coffee(named java coffee) was produced. And this name
was chosen by James Gosling while having coffee near his office. Note that Java is just a name, not an acronym.

Java Terminology

Before learning Java, one must be familiar with these common terms of Java.

1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases of a program.
They are written, compile and run the program.

 Writing a program is done by a java programmer like you and me.

 The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes the Java program as input and generates bytecode as output.

 In the Running phase of a program, JVM executes the bytecode generated by the compiler.

Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the compiler.
Every Operating System has a different JVM but the output they produce after the execution of bytecode is the same
across all the operating systems. This is why Java is known as a platform-independent language.

2. Bytecode in the Development Process: As discussed, the Javac compiler of JDK compiles the java source code into
bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the bytecode, a
disassembler like javap can be used.

3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode and JVM. So, as the
name suggests, it is a complete Java development kit that includes everything including compiler, Java Runtime
Environment (JRE), java debuggers, java docs, etc. For the program to execute in java, we need to install JDK on our
computer in order to create, compile and run the java program.

4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the java program to
run, however, we cannot compile it. JRE includes a browser, JVM, applet support, and plugins. For running the java
program, a computer needs JRE.

5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a
program called Garbage Collector. Garbage Collectors can recollect the objects that are not referenced. So Java
makes the life of a programmer easy by handling memory management. However, programmers should be careful
about their code whether they are using objects that have been used for a long time. Because Garbage cannot
recover the memory of objects being referenced.

6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class files to load. By
default, JDK provides many libraries. If you want to include external libraries they should be added to the classpath.

Primary/Main Features of Java


1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or macOS which means if
we compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has a
different JVM, but the output produced by all the OS is the same after the execution of the bytecode. That is why we
call java a platform-independent language.
UNIT 1: Introduction to Java
2. Object-Oriented Programming Language: Organizing the program in the terms of a collection of objects is a way
of object-oriented programming, each of which represents an instance of the class.

The four main concepts of Object-Oriented programming are:

 Abstraction

 Encapsulation

 Inheritance

 Polymorphism

3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator
overloading, multiple inheritances, and Explicit memory allocation.

4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java compiler is able to detect even those errors that are not
easy to detect by another programming language. The main features of java that make it robust are garbage
collection, Exception Handling, and memory allocation.

5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack corruption or
buffer overflow are impossible to exploit in Java. Also, java programs run in an environment that is independent of
the os(operating system) environment which makes java programs more secure.

6. Distributed: We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java programs can be
easily distributed on one or more systems that are connected to each other through an internet connection.

7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of the CPU.

8. Portable: As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any platform for execution
makes java portable.

9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime and at
some times java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basics where it only
compiles those methods that are called making applications to execute faster.

10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new methods to
existing classes, and even create new classes through sub-classes. Java even supports functions written in other
languages such as C, C++ which are referred to as native methods.

11. Sandbox Execution: Java programs run in a separate space that allows user to execute their applications without
affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides additional security as
its role is to check the code for any violation of access.

12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It provides ease t architecture-neutral ease as bytecode is
not dependent on any machine architecture. It is the primary reason java is used in the enterprising IT industry
globally worldwide.

13. Power of compilation and interpretation: Most languages are designed with the purpose of either they are
compiled language or they are interpreted language. But java integrates arising enormous power as Java compiler
compiles the source code to bytecode and JVM executes this bytecode to machine OS-dependent executable code.
UNIT 1: Introduction to Java
class : class keyword is used to declare classes in Java
public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a static function you do not have to
create an Object of the class. The main() method here is called by JVM, without creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the method which is executed, hence
all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation
error.
String[] args : This is used to signify that the user may opt to enter parameters to the Java Program at command line.
We can use both String[] args or String args[]. Java compiler would accept both forms.
System.out.println : This is used to print anything on the console like “printf” in C language.

How JVM Works – JVM Architecture?


JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls
the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on
one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible
because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are
generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe
the whole JVM.
UNIT 1: Introduction to Java
Class Loader Subsystem

It is mainly responsible for three activities.

 Loading

 Linking

 Initialization

Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method
area. For each “.class” file, JVM stores the following information in the method area.

 The fully qualified name of the loaded class and its immediate parent class.

 Whether the “.class” file is related to Class or Interface or Enum.

 Modifier, Variables and Method information etc.

Byte Code in Java


Byte Code

Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source
code(JAVA Program). This intermediate code makes Java a platform-independent language.

How is Byte Code generated?

Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the
Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine). The
byte code is the common piece between the compiler(which creates it) and the Interpreter (which runs it).
UNIT 1: Introduction to Java
Let us look at this phenomenon, step by step

 Suppose you are writing your first JAVA program.

Java

/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static void main (String[] args) {

System.out.println("GFG!");

Output

GFG!

 The above-written code is called JAVA source code.

 The compiler compiles the source code.

 Finally, Interpreter executes the compiled source code.

Setting up the environment in Java


Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java
applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of
computer architecture. The latest version is Java 21. Below are the environment settings for both Linux and
Windows. JVM, JRE, and JDK three are all platform-dependent because the configuration of each Operating System is
different. But, Java is platform-independent. Few things must be clear before setting up the environment which can
better be perceived from the below image provided as follows:
UNIT 1: Introduction to Java
 JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as
the Java compiler, Javadoc, Jar, and a debugger.

 JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs
and is intended for end-users. JRE can be viewed as a subset of JDK.

 JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime
environment in which java bytecode can be executed. JVMs are available for many hardware and software
platforms.

Now let us discuss the steps for setting up a Java environment with visual aids. Let’s use the Windows operating
system to illustrate visual aids.

Steps: Here we will be proposing steps for three different operating systems as listed:

1. Windows operating system

2. Linux operating system

3. macOS operating system

A. Windows operating systems

The steps for setting the environment in the Windows operating system are as follows:

Step 1: Java8 JDK is available at Download Java 8. Click the first link for Windows(32-bit) and the last link for
Windows(64-bit) as highlighted below.

Step 2: Now you will see a download prompt just accept the term and conditions and click on the download button
UNIT 1: Introduction to Java

Step 3: If you have an oracle account then sign in or if don’t then create one and sign in

Step 4: Then your download will start automatically after signing in if don’t then click on the previous link again
UNIT 1: Introduction to Java
Step 5: After downloading, run the jdk-8u Application(.exe file) and follow the instructions to install Java on your
machine. Once you install Java on your device, you have to set up the environment variable.

Step 6: Go to Control Panel -> System and Security -> System. Under the Advanced System Setting option click
on Environment Variables as highlighted below.

Step 7: Now, you have to alter the “Path” variable under System variables so that it also contains the path to the
Java environment. Select the “Path” variable and click on the Edit button as highlighted below.
UNIT 1: Introduction to Java
Step 8: You will see a list of different paths, click on the New button, and then add the path where java is installed.
By default, java is installed in “C:\Program Files\Java\jdk\bin” folder OR “C:\Program Files(x86)\Java\jdk\bin”. In
case, you have installed java at any other location, then add that path.

Step 9: Click on OK, Save the settings, and you are done !! Now to check whether the installation is done correctly,
open the command prompt and type javac -version. You will see that java is running on your machine.

Note: To make sure whether the compiler is set up, type javac in the command prompt. You will see a list related to
javac.

B. Linux Operating System

In Linux, there are several ways to install java. But we will refer to the simplest and easy way to install java using a
terminal. For Linux, we will install OpenJDK. OpenJDK is a free and open-source implementation of the Java
programming language. Steps for setting the environment in the Linux operating system are as follows:

Step 1: Go to Application -> Accessories -> Terminal.

Step 2: Type the command as below as follows:

sudo apt-get install openjdk-8-jdk

Step 3: For the “JAVA_HOME” (Environment Variable) type the command as shown below, in “Terminal” using your
installation path…(Note: the default path is as shown, but if you have to install OpenJDK at another location then set
that path.)

export JAVA_HOME = /usr/lib/jvm/java-8-openjdk

Step 4: For “PATH” (Environment Value) type command as shown below, in “Terminal” using your installation
path…Note: the default path is as shown, but if you have to install OpenJDK at another location then set that path.)

export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin

Note: We are done setting up the environment in Java for Linux OS.

Note: Now to check whether the installation is done correctly, type java -version in the Terminal. You will see that
java is running on your machine.
UNIT 1: Introduction to Java
 Notepad/gedit : They are simple text-editors for writing java programs. Notepad is available on Windows
and gedit is available on Linux.

 Eclipse IDE : It is the most widely used IDE(Integrated Development Environment) for developing software in
java. You can download Eclipse.

C. MacOS Operating System

Step 1: Open the terminal from the application folder or simply press the “command” and “shift” key together and
write initials of the terminal and press enter.

It will be good to have package manager such as homebrew installed in your machine as we can operate to install
any software from here itself simply by using terminal commands.

Step 2: Now in order to configure first write the command ‘java –version ‘ where the message below it will pop that
there is no

java --version
javac --version

Note: If it was set up then you would have been getting the version displayed on the screen as it is shown below
where in that machine it was already set up. So remember to cross-check in your machine once you have
successfully set it up in yours.

Step 2: Once we are done with installing JDK now let us move on setting up the java_home environment variable for
that you will have to look into something called s ‘bash_profie’ using the below command

ls -al

You will notice that in your terminal there will be no bash_profile set but it is shown below so here in this machine it
is already set up. In order to set it up if not there we have to create it which lets us prior seek into java home
variables whether it is set up or not.
UNIT 1: Introduction to Java

Step 3: Setting up the home java variable. Use the below command to check or setup if not installed as follows on
the terminal:

echo $JAVA_HOME

If it is showing blank then the java home variable is not set up as perceived from the above image.

Step 4: Installing bash_profile

Make sure to go to the root folder in the terminal and write the command ‘touch ./bash_profile ‘

Now you will see that bash-profile s created which is as shown in the step2 in your machine which hone can verify by
writing command as follows:

ls -al
UNIT 1: Introduction to Java
Step 5: Edit the .bash_profile created for java, you just have to write the command marked in below media and
provided below as follows:

export JAVA_HOME=$(/usr/libexec/java_home)
// No need to remember this command

Save this file and relaunch the terminal by closing it.

Step 5: Verifying whether it is installed by entering the following two commands

source .bash_profile
echo $JAVA_HOME

From the above media, we can see the java variable is all set to go as earlier there was a blank therein the above
media.
UNIT 1: Introduction to Java
Differences between Procedural and Object Oriented Programming
This article focuses on discussing the differences between procedural and object-oriented programming.

Procedural Programming

Procedural Programming can be defined as a programming model which is derived from structured programming,
based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply
consist of a series of computational steps to be carried out. During a program’s execution, any given procedure
might be called at any point, including by other procedures or itself.

Languages used in Procedural Programming:

FORTRAN, ALGOL, COBOL,

BASIC, Pascal and C.

Object-Oriented Programming

Object-oriented programming can be defined as a programming model which is based upon the concept of objects.
Objects contain data in the form of attributes and code in the form of methods. In object-oriented programming,
computer programs are designed using the concept of objects that interact with the real world. Object-oriented
programming languages are various but the most popular ones are class-based, meaning that objects are instances
of classes, which also determine their types.

Languages used in Object-Oriented Programming:

Java, C++, C#, Python,

PHP, JavaScript, Ruby, Perl,

Objective-C, Dart, Swift, Scala.

Procedural Programming vs Object-Oriented Programming


UNIT 1: Introduction to Java
Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided into small In object-oriented programming, the program is divided
parts called functions. into small parts called objects.

Object-oriented programming follows a bottom-up


Procedural programming follows a top-down approach.
approach.

Object-oriented programming has access specifiers like


There is no access specifier in procedural programming.
private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way of Object-oriented programming provides data hiding so it
hiding data so it is less secure. is more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming.

In procedural programming, there is no concept of data In object-oriented programming, the concept of data hiding
hiding and inheritance. and inheritance is used.

In procedural programming, the function is more important In object-oriented programming, data is more important
than the data. than function.

Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.

Procedural programming is used for designing medium-sized Object-oriented programming is used for designing large
programs. and complex programs.

Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.

Code reusability absent in procedural programming, Code reusability present in object-oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
UNIT 1: Introduction to Java

Object Oriented Programming (OOPs) Concept in Java


As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming,
they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or
user, performing tasks assigned by you. Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism etc. in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that function.

Let us discuss prerequisites by polishing concepts of method declaration and message passing. Starting off with the
method declaration, it consists of six components:

 Access Modifier: Defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there are 4 types of access specifiers:

 public: Accessible in all classes in your application.

 protected: Accessible within the package in which it is defined and in its subclass(es) (including
subclasses declared outside the package).

 private: Accessible only within the class in which it is defined.

 default (declared/defined without using any modifier): Accessible within the same class and
package within which its class is defined.

 The return type: The data type of the value returned by the method or void if it does not return a value.

 Method Name: The rules for field names apply to method names as well, but the convention is a little
different.

 Parameter list: Comma-separated list of the input parameters that are defined, preceded by their data type,
within the enclosed parentheses. If there are no parameters, you must use empty parentheses ().

 Exception list: The exceptions you expect the method to throw. You can specify these exception(s).

 Method body: It is the block of code, enclosed between braces, that you need to execute to perform your
intended operations.

Message Passing: Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves specifying the name of the object, the name of
the function and the information to be sent.

Master OOP in Java Write cleaner, more modular, and reusable Java code by building a foundation in object-oriented
programming with Educative’s interactive course Learn Object-Oriented Programming in Java. Sign up at Educative.io
with the code GEEKS10 to save 10% on your subscription.

Now that we have covered the basic prerequisites, we will move on to the 4 pillars of OOPs which are as follows.
But, let us start by learning about the different characteristics of an Object-Oriented Programming Language.
UNIT 1: Introduction to Java
OOPS concepts are as follows:

1. Class

2. Object

3. Method and method passing

4. Pillars of OOPs

 Abstraction

 Encapsulation

 Inheritance

 Polymorphism

 Compile-time polymorphism

 Runtime polymorphism

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. Using classes, you can create multiple objects with the same
behavior instead of writing their code multiple times. This includes classes for objects occurring more than once in
your code. In general, class declarations can include these components in order:

1. Modifiers: A class can be public or have default access (Refer to this for details).

2. Class name: The class name should begin with the initial letter capitalized by convention.

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

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

5. Body: The class body is surrounded by braces, { }.


UNIT 1: Introduction to Java
An object is a basic unit of Object-Oriented Programming that represents real-life entities. A typical Java program
creates many objects, which as you know, interact by invoking methods. The objects are what perform your code,
they are the part of your code visible to the viewer/user. An object mainly consists of:

1. State: It is represented by the attributes of an object. It also reflects the properties of an object.

2. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.

3. Identity: It is a unique name given to an object that enables it to interact with other objects.

4. Method: 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 it, which is why they are considered time savers. In Java, every method must be part
of some class, which is different from languages like C, C++, and Python.

class and objects one simple java program :

 Java

public class GFG {

static String Employee_name;

static float Employee_salary;

static void set(String n, float p) {

Employee_name = n;

Employee_salary = p;

static void get() {

System.out.println("Employee name is: " +Employee_name );

System.out.println("Employee CTC is: " + Employee_salary);

public static void main(String args[]) {

GFG.set("Rathod Avinash", 10000.0f);

GFG.get();

}
UNIT 1: Introduction to Java
Output

Employee name is: Rathod Avinash

Employee CTC is: 10000.0

Let us now discuss the 4 pillars of OOPs:

Pillar 1: Abstraction

Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or
non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object,
ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar
type and also help in classifying/grouping the object.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase
the car speed or applying brakes will stop the car, but he does not know how on pressing the accelerator, the speed
is actually increasing. He does not know about the inner mechanism of the car or the implementation of the
accelerators, brakes etc. in the car. This is what abstraction is.

In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

The abstract method contains only method declaration but not implementation.

Demonstration of Abstract class

 Java

//abstract class

abstract class GFG{

//abstract methods declaration

abstract void add();

abstract void mul();

abstract void div();

Pillar 2: Encapsulation

It is defined as the wrapping up of data under a single unit. It is the mechanism that binds together the code and the
data it manipulates. Another way to think about encapsulation is that it is a protective shield that prevents the data
from being accessed by the code outside this shield.

 Technically, in encapsulation, the variables or the data in a class is hidden from any other class and can be
accessed only through any member function of the class in which they are declared.

 In encapsulation, the data in a class is hidden from other classes, which is similar to what data-hiding does.
So, the terms “encapsulation” and “data-hiding” are used interchangeably.

 Encapsulation can be achieved by declaring all the variables in a class as private and writing public methods
in the class to set and get the values of the variables.
UNIT 1: Introduction to Java
Demonstration of Encapsulation:

 Java

//Encapsulation using private modifier

//Employee class contains private data called employee id and employee name

class Employee {

private int empid;

private String ename;

Pillar 3: Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in Java by which one
class is allowed to inherit the features (fields and methods) of another class. We are achieving inheritance by
using extends keyword. Inheritance is also known as “is-a” relationship.

Let us discuss some frequently used important terminologies:

 Superclass: The class whose features are inherited is known as superclass (also known as base or parent
class).

 Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or
child class). The subclass can add its own fields and methods in addition to the superclass fields and
methods.

 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
UNIT 1: Introduction to Java
Demonstration of Inheritance :

 Java

//base class or parent class or super class

class A{

//parent class methods

void method1(){}

void method2(){}

//derived class or child class or base class

class B extends A{ //Inherits parent class methods

//child class methods

void method3(){}

void method4(){}

Pillar 4: Polymorphism

It refers to the ability of object-oriented programming languages to differentiate between entities with the same
name efficiently. This is done by Java with the help of the signature and declaration of these entities. The ability to
appear in many forms is called polymorphism.

E.g.

 Java

sleep(1000) //millis

sleep(1000,2000) //millis,nanos

Note: Polymorphism in Java is mainly of 2 types:

1. Overloading

2. Overriding
UNIT 1: Introduction to Java
Example

 Java

// Java program to Demonstrate Polymorphism

// This class will contain

// 3 methods with same name,

// yet the program will

// compile & run successfully

public class Sum {

// Overloaded sum().

// This sum takes two int parameters

public int sum(int x, int y)

return (x + y);

// Overloaded sum().

// This sum takes three int parameters

public int sum(int x, int y, int z)

return (x + y + z);

// Overloaded sum().

// This sum takes two double parameters

public double sum(double x, double y)

return (x + y);

// Driver code
UNIT 1: Introduction to Java
public static void main(String args[])

Sum s = new Sum();

System.out.println(s.sum(10, 20));

System.out.println(s.sum(10, 20, 30));

System.out.println(s.sum(10.5, 20.5));

Output

30

60

31.0

Java Hello World Program


Java is one of the most popular and widely used programming languages and platforms. Java is fast, reliable, and
secure. Java is used in every nook and corner from desktop to web applications, scientific supercomputers to gaming
consoles, cell phones to the Internet. In this article, we will learn how to write a simple Java Program.

Steps to Implement Java Program

Implementation of a Java application program involves the following step. They include:

1. Creating the program

2. Compiling the program

3. Running the program

1. Creating Programs in Java

We can create a program using Text Editor (Notepad) or IDE (NetBeans)

class Test

public static void main(String []args)

System.out.println("My First Java Program.");

};

File Save: d:\Test.java


UNIT 1: Introduction to Java
2. Compiling the Program in Java

To compile the program, we must run the Java compiler (javac), with the name of the source file on the “command
prompt” like as follows

If everything is OK, the “javac” compiler creates a file called “Test.class” containing the byte code of the program.

3. Running the Program in Java

We need to use the Java Interpreter to run a program. Java is easy to learn, and its syntax is simple and easy to
understand. It is based on C++ (so easier for programmers who know C++).

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.

The below-given program is the most simple program of Java printing “Hello World” to the screen. Let us try to
understand every bit of code step by step.

 Java

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

Output

Hello, World

The complexity of the above method

Time Complexity: O(1)

Space Complexity: O(1)

The “Hello World!” program consists of three primary components: the HelloWorld class definition, the main
method, and source code comments. The following explanation will provide you with a basic understanding of the
code:
UNIT 1: Introduction to Java
1. Class Definition

This line uses the keyword class to declare that a new class is being defined.

class HelloWorld {

//

//Statements

2. HelloWorld

It 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 “}“.

3. main Method

In the Java programming language, every application must contain a main method. The main function(method) is the
entry point of your Java application, and it’s mandatory in a Java program. whose signature in Java is:

public static void main(String[] args)

Explanation of the above syntax

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

 static: The main method is to be called without an object. The modifiers are public and static can be written
in either order.

 void: The main method doesn’t return anything.

 main(): Name configured in the JVM. The main method must be inside the class definition. The compiler
executes the codes starting always from the main function.

 String[]: The main method accepts a single argument, i.e., an array of elements of type String.

Like in C/C++, the main method is the entry point for your application and will subsequently invoke all the other
methods required by your program.

The next line of code is shown here. Notice that it occurs inside the main() method.

System.out.println("Hello, World");

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

Comments

They can either be multiline or single-line comments.

// This is a simple Java program.

// Call this file "HelloWorld.java".

This is a single-line comment. This type of comment must begin with // as in C/C++. For multiline comments, they
must begin from /* and end with */.
UNIT 1: Introduction to Java
Important Points

 The name of the class defined by the program is HelloWorld, which is the same as the name of the
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 contains the main() method.

 By convention, the name of the main class(a class that contains the main method) should match the name of
the file that holds the program.

 Every Java program must have a class definition that matches the filename (class name and file name should
be same).

Compiling the Program

 After successfully setting up the environment, we can open a terminal in both Windows/Unix and go to the
directory where the file – HelloWorld.java is present.

 Now, to compile the HelloWorld program, execute the compiler – javac, to specify the name of
the source file on the command line, as shown:

javac HelloWorld.java

 The compiler creates a HelloWorld.class (in the current 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.

In Windows
UNIT 1: Introduction to Java

In Linux
UNIT 2: Building Blocks of the Language
Java Data Types
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 Java data types.

Data Types in Java

Data types in Java are of different sizes and values that can be stored in the variable that is made as per convenience
and circumstances to cover up all test cases. Java has two categories in which data types are segregated

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double

2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
UNIT 2: Building Blocks of the Language
Primitive Data Types in Java

Primitive data are only single values and have no special capabilities. There are 8 primitive data types. They are
depicted below in tabular format below as follows:

Example
Type Description Default Size Literals Range of values

boolean true or false false 1 bit true, false true, false

twos-
complement 0 8 bits (none) -128 to 127
byte integer

‘a’, ‘\u0041’, characters representation


Unicode of ASCII values
\u0000 16 bits ‘\101’, ‘\\’, ‘\’,
character
char ‘\n’, ‘β’ 0 to 255

twos-
complement 0 16 bits (none) -32,768 to 32,767
short integer

-2,147,483,648
twos-
complement 0 32 bits -2,-1,0,1,2 to
intger
int 2,147,483,647

-
twos- 9,223,372,036,854,775,808
complement 0 64 bits -2L,-1L,0L,1L,2L
to
integer
long 9,223,372,036,854,775,807

1.23e100f , -
IEEE 754
0.0 32 bits 1.23e-100f , .3f upto 7 decimal digits
floating point
float ,3.14F

1.23456e300d ,
IEEE 754
0.0 64 bits -123456e-300d upto 16 decimal digits
floating point
double , 1e1d

Let us discuss and implement each one of the following data types that are as follows:
UNIT 2: Building Blocks of the Language
1. Boolean Data Type

Boolean data type represents only one bit of information either true or false which is intended to represent the two
truth values of logic and Boolean algebra, 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. But the programmer
can easily write conversion code.

Syntax:

boolean booleanVar;

Size: Virtual machine dependent

2. Byte Data Type

The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in
large arrays.

Syntax:

byte byteVar;

Size: 1 byte (8 bits)

3. Short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large
arrays, in situations where the memory savings actually matters.

Syntax:

short shortVar;

Size: 2 bytes (16 bits)

4. Integer Data Type

It is a 32-bit signed two’s complement integer.

Syntax:

int intVar;

Size: 4 bytes ( 32 bits )

Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has a
value in the range [0, 232-1]. Use the Integer class to use the int data type as an unsigned integer.

5. Long Data Type

The range of a long is quite large. The long data type is a 64-bit two’s complement integer and is useful for those
occasions where an int type is not large enough to hold the desired value. The size of the Long Datatype is 8 bytes
(64 bits).

Syntax:

long longVar;
UNIT 2: Building Blocks of the Language
Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a
minimum value of 0 and a maximum value of 264-1. The Long class also contains methods like comparing Unsigned,
divide Unsigned, etc to support arithmetic operations for unsigned long.

6. Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to
save memory in large arrays of floating-point numbers. The size of the float data type is 4 bytes (32 bits).

Syntax:

float floatVar;

7. Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is
generally the default choice. The size of the double data type is 8 bytes or 64 bits.

Syntax:

double doubleVar;

Note: Both float and double data types were designed especially for scientific calculations, where approximation
errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and
use BigDecimal class instead.

It is recommended to go through rounding off errors in java.

8. Char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

Syntax:

char charVar;

Why is the Size of char 2 bytes in Java?

So, other languages like C/C++ use 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 the Unicode system 8 bits is not enough
to represent all characters so Java uses 2 bytes for characters. 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,
Greek, Cyrillic, Katakana, Arabic, and many more.
UNIT 2: Building Blocks of the Language
Example:

 Java

// Java Program to Demonstrate Char Primitive Data Type

// Class

class GFG {

// Main driver method

public static void main(String args[])

// Creating and initializing custom character

char a = 'G';

// Integer data type is generally

// used for numeric values

int i = 89;

// use byte and short

// if memory is a constraint

byte b = 4;

// this will give error as number is

// larger than byte range

// byte b1 = 7888888955;

short s = 56;

// this will give error as number is

// larger than short range

// short s1 = 87878787878;
UNIT 2: Building Blocks of the Language
// by default fraction value

// is double in java

double d = 4.355453532;

// for float use 'f' as suffix as standard

float f = 4.7333434f;

// need to hold big range of numbers then we need

// this data type

long l = 12121;

System.out.println("char: " + a);

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

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("long: " + l);

Output

char: G

integer: 89

byte: 4

short: 56

float: 4.7333436

double: 4.355453532

long: 12121
UNIT 2: Building Blocks of the Language
Non-Primitive Data Type or Reference Data Types

The Reference Data Types will contain a memory address of variable values because the reference types won’t store
the variable value directly in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character array and a string in Java is, that
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.

Syntax: Declaring a string

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator


String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");

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

1. Modifiers: A class can be public or has default access. Refer to access specifiers for classes or interfaces in
Java

2. Class name: The name should begin with an initial letter (capitalized by convention).

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

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

5. Body: The class body is surrounded by braces, { }.

3. Object

An Object is a basic unit of Object-Oriented Programming and represents 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 the attributes of an object. It also reflects the properties of an object.

2. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.

3. Identity: It gives a unique name to an object and enables one object to interact with other objects.

4. 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, no body).

 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.
UNIT 2: Building Blocks of the Language
 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.

 A Java library example is Comparator Interface. If a class implements this interface, then it can be used to
sort a collection.

5. 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. (discussed below)

 Since arrays are objects in Java, we can find their length using member 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 with 0.

 Java array can also be used as a static field, a local variable, or a method parameter.

 The size of an array must be specified by an int value and not long or short.

 The direct superclass of an array type is Object.

 Every array type implements the interfaces Cloneable and java.io.Serializable.

FAQs of Data Types in Java

1. What are Data Types in Java?

Data types are of different sizes and values that can be stored in the variable that is made as per convenience and
circumstances to cover up all test cases.

2. What are the 8 Data Types that use in Java?

There are 8 main primitive data types in java as mentioned below:

 boolean

 byte

 char

 short

 int

 long

 float

 double

3. Which is a Primitive Type in Java?

Primitive data types are the types in java that can store a single value and do not provide any special capability.

4. Why char uses 2 bytes in Java and what is \u0000?

Char uses 2 bytes in java because it uses the Unicode system rather than the ASCII system. “\u000” is the lowest
range of the Unicode system.
UNIT 2: Building Blocks of the Language
User defined data types are those that user / programmer himself defines. For example, classes, interfaces.

In very-very simple words I can say,

int a

Here a is a variable of int data type.

MyClass obj

Here obj is a variable of data type MyClass and we call them reference variables as they can be used to store the
reference to the object of that class.

Java Identifiers
In Java, identifiers are used for identification purposes. Java Identifiers can be a class name, method name, variable
name, or label.

Example of Java Identifiers

public class Test


{
public static void main(String[] args)
{
int a = 20;
}
}

In the above Java code, we have 5 identifiers namely :

 Test: class name.

 main: method name.

 String: predefined class name.

 args: variable name.

 a: variable name.

Rules For Defining Java Identifiers

There are certain rules for defining a valid Java identifier. These rules must be followed, otherwise, we get a compile-
time error. These rules are also valid for other languages like C, and C++.

 The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign)
and ‘_‘ (underscore).For example “geek@” is not a valid Java identifier as it contains a ‘@’ a special
character.

 Identifiers should not start with digits([0-9]). For example “123geeks” is 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 a
while is a reserved word. There are 53 reserved words in Java.
UNIT 2: Building Blocks of the Language
Examples of valid identifiers :

MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123

Examples of invalid identifiers :

My Variable // contains a space


123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

Reserved Words in Java

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 value. Identifiers are used by symbol tables in various analyzing phases(like
lexical, syntax, and semantic) of a compiler architecture.

abstract continue for protected transient

Assert Default Goto public Try

Boolean Do If Static throws

break double implements strictfp Package

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void


UNIT 2: Building Blocks of the Language
abstract continue for protected transient

Char Final Int synchronized volatile

class finally long throw Date

const float Native This while

Literals in Java
Literal: Any constant value which can be assigned to the variable is called literal/constant.

In simple words, Literals in Java is a synthetic representation of boolean, numeric, character, or string data. It is a
medium of expressing particular values in the program, such as an integer variable named ‘’/count is assigned an
integer value in the following statement.

// Here 100 is a constant/literal.

int x = 100;

Integral literals

For Integral data types (byte, short, int, long), we can specify literals in 4 ways:-

Decimal literals (Base 10): In this form, the allowed digits are 0-9.

int x = 101;

Octal literals (Base 8): In this form, the allowed digits are 0-7.

// The octal number should be prefix with 0.

int x = 0146;

Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9, and characters are a-f. We can use both
uppercase and lowercase characters as we know that java is a case-sensitive programming language, but here java is
not case-sensitive.

// The hexa-decimal number should be prefix

// with 0X or 0x.

int x = 0X123Face;

Binary literals: From 1.7 onward, we can specify literal value even in binary form also, allowed digits are 0 and 1.
Literals value should be prefixed with 0b or 0B.

int x = 0b1111;

Example:

Java

// Java program to illustrate the


// application of char literals
UNIT 2: Building Blocks of the Language
public class Test {
public static void main(String[] args)
{
// single character literal within single quote
char ch = ‘a’;
// It is an Integer literal with octal form
char b = 0789;
// Unicode representation
char c = ‘\u0061’;

System.out.println(ch);
System.out.println(b);
System.out.println(c);

// Escape character literal


System.out.println(“\” is a symbol”);
}
}

Output

101

64

64206

15

Note : By default, every literal is of int type, we can specify explicitly as long type by suffixed with l or L. There is no
way to specify byte and short literals explicitly but indirectly we can specify. Whenever we are assigning integral
literal to the byte variable and if the value is within the range of byte then the compiler treats it automatically as byte
literals.

Floating-Point literal

For Floating-point data types, we can specify literals in only decimal form, and we cant specify in octal and
Hexadecimal forms.

Decimal literals(Base 10): In this form, the allowed digits are 0-9.

double d = 123.456;

Java

// Java program to illustrate the


// application of String literals

public class Test {


public static void main(String[] args)
{
String s = “Hello”;

// If we assign without “” then it treats


// as a variable and causes compiler error
String s1 = Hello;

System.out.println(s);
System.out.println(s1);
UNIT 2: Building Blocks of the Language
}
}

Output

101.230

123.222

Error: malformed floating point literal

Note: By default, every floating-point literal is of double type, and hence we cant assign directly to the float variable.
But we can specify floating-point literal as float type by suffixed with f or F. We can specify explicitly floating-point
literal as double type by suffixed with d or D. Of course this convention is not required.

Char literals

For char data types, we can specify literals in 4 ways:

Single quote: We can specify literal to a char data type as a single character within the single quote.

char ch = 'a';

Char literal as Integral literal: we can specify char literal as integral literal, which represents the Unicode value of the
character, and that integral literal can be specified either in Decimal, Octal, and Hexadecimal forms. But the allowed
range is 0 to 65535.

char ch = 062;

Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx represents 4
hexadecimal numbers.

char ch = '\u0061';// Here /u0061 represent a.

Escape Sequence: Every escape character can be specified as char literals.

char ch = '\n';
UNIT 2: Building Blocks of the Language
Example:

Java

// Java program to illustrate the

// application of char literals

public class Test {

public static void main(String[] args)

// single character literal within single quote

char ch = 'a';

// It is an Integer literal with octal form

char b = 0789;

// Unicode representation

char c = '\u0061';

System.out.println(ch);

System.out.println(b);

System.out.println(c);

// Escape character literal

System.out.println("\" is a symbol");

Output

error:Integer number too large

" is a symbol

String literals

Any sequence of characters within double quotes is treated as String literals.

String s = "Hello";

String literals may not contain unescaped newline or linefeed characters. However, the Java compiler will evaluate
compile-time expressions, so the following String expression results in a string with three lines of text:
UNIT 2: Building Blocks of the Language
Example:

String text = "This is a String literal\n"

+ "which spans not one and not two\n"

+ "but three lines of text.\n";

Java

// Java program to illustrate the behaviour of


// char literals and integer literals when
// we are performing addition

public class Test {


public static void main(String[] args)
{
// ASCII value of 0 is 48
int first = ‘0’;

// ASCII value of 7 is 55
int second = ‘7’;
System.out.println(“Geeks!” + first +
‘2’ + second);
}
}

Output

Hello

error: cannot find symbol

symbol: variable Hello

location: class Test

Boolean literals

Only two values are allowed for Boolean literals, i.e., true and false.

boolean b = true;

Java

Output

true

false

error: incompatible types: int cannot be converted to boolean

error: incompatible types: int cannot be converted to boolean

Note: When we are performing concatenation operations, then the values in brackets are concatenated first. Then
the values are concatenated from the left to the right. We should be careful when we are mixing character literals
and integers in String concatenation operations and this type of operation are known as Mixed Mode operation.
UNIT 2: Building Blocks of the Language
Java

// Java program to illustrate the behaviour of

// char literals and integer literals when

// we are performing addition

public class Test {

public static void main(String[] args)

// ASCII value of 0 is 48

int first = '0';

// ASCII value of 7 is 55

int second = '7';

System.out.println("Geeks!" + first +

'2' + second);

Output

Geeks!48255

Explanation: Whenever we are performing addition between a string and integer, the overall result is converted into
a string. The above program evaluation is done in the following way:

"Geeks!" + first + '2' + second

"Geeks! " + 48 + '2' + 55

"Geeks!48" + '2' + 55

"Geeks!482" + 55

"Geeks!48255"

Java String Literals as Constants or Singletons


String is a sequence of characters, which is widely used in Java Programming. In the Java programming language,
strings are objects. In Java, the virtual machine may only create a single String instance in memory, if we use the
same string in other string variable declarations. Let us consider illustrations for the sake of understanding which is
as follows:

Illustration 1:

String string1 = "GeeksForGeeks";

String string2 = "GeeksForGeeks";


UNIT 2: Building Blocks of the Language
In the above example, the java virtual machine will create only one instance of “GeeksForGeeks” in memory. There
are two different variables, initialized to “GeeksForGeeks” string will point to the same String instance in memory.
The figure below depicts example more accurately:-

The string literal thus becomes a de facto constant or singleton. More precisely in java, objects representing Java
String literals are obtained from a constant String pool which is internally kept by a java virtual machine. This means,
that even classes from different projects compiled separately, but which are used in the same application may share
constant String objects. The sharing happens at runtime and hence it is not a compile-time feature.

Illustration 2: If we want those two string variables point to separate String objects then we use the new operator as
follows:

String string1 = new String("GeeksForGeeks");

String string2 = new String("GeeksForGeeks");

The above code will create two different memory objects in memory to represent them even if the value of two
strings is the same. The image below depicts the use of new operator:

Note: From the image above it is clearly depicted that two different memory blocks are created for two different
string which contains same value string.
UNIT 2: Building Blocks of the Language
Example 1:

 Java

// Java Program to Illustrate String Literals as

// Constants or Singletons

// Main class

// StringSingleton

public class GFG {

// Main driver method

public static void main(String[] args)

// Strings

String string1 = "GeeksForGeeks";

String string2 = "GeeksForGeeks";

String string3 = new String("GeeksForGeeks");

String string4 = new String("GeeksForGeeks");

// Checking if two string are same or not

if (string1 == string2) {

// Returns true

System.out.println("True");

else {

// Returns false

System.out.println("False");

// Again checking if two string are same or not


UNIT 2: Building Blocks of the Language
if (string1 == string3) {

// Returns false

System.out.println("True");

else {

System.out.println("False");

// Again checking if two string are same or not

if (string4 == string3) {

// Returns false

System.out.println("True");

else {

System.out.println("False");

Output

True

False

False

In the above program, a total of 3 objects will be created. Now, if we want to compare 2 string contents, we can use
the equals method, and ‘==’ operator can be used to compare whether two string references are the same or not.
UNIT 2: Building Blocks of the Language
Example 2:

 Java

// Java Program to Illustrate String Literals as

// Constants or Singletons

// Main class

// StringSingleton

public class GFG {

// Main driver method

public static void main(String[] args)

// Strings

String string1 = "GeeksForGeeks";

String string3 = new String("GeeksForGeeks");

// Print and display statements

// Displays true

System.out.println(string1.equals(string3));

// Displays false

System.out.println(string1 == string3);

Output

true

false

What is constants in Java ?

 An element of program whose value can not be changed at the time of execution of program is called
constant.

 It is also called literals.

 It may be int,float and character data type.


UNIT 2: Building Blocks of the Language
Rules for constructing integer constant:

1. It must have atleast one digit.

2. It must not have a decimal point.

3. It may be positive or negative.

4. No comma or blank space are allowed in integer constant.

Rules for constructing floating point constant:

1. It must have atleast one digit.

2. It must have a decimal point.

3. It may be positive or negative.

4. No comma or blank space are allowed in floating point constant.

Rules for constructing character constant :

1. It is a single alphabet,digit or special symbol.

2. The length of character constant is 1 character.

3. Character constant is enclosed within single quotes (Example char c=’A’;).

Java Variables
In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in
Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory
location name for the data.

Variables in Java

Java variable is a name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.

 Variables in Java are only a name given to a memory location. All the operations done on the variable affect
that memory location.

 In Java, all variables must be declared before use.

How to Declare Variables in Java?

We can declare variables in Java as pictorially depicted below as a visual aid.


UNIT 2: Building Blocks of the Language
From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that
are:

1. datatype: Type of data that can be stored in this variable.

2. data_name: Name was given to the variable.

In this way, a name can only be given to a memory location. It can be assigned values in two ways:

 Variable Initialization

 Assigning value by taking input

How to Initialize Variables in Java?

It can be perceived with the help of 3 components that are as follows:

 datatype: Type of data that can be stored in this variable.

 variable_name: Name given to the variable.

 value: It is the initial value stored in the variable.

Illustrations:

// Declaring float variable


float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
// Declaring and initializing character variable
char var = 'h';

Types of Variables in Java

Now let us discuss different types of variables which are listed as follows:

1. Local Variables

2. Instance Variables

3. Static Variables
UNIT 2: Building Blocks of the Language

Let us discuss the traits of every type of variable listed here in detail.

1. Local Variables

A variable defined within a block or method or constructor is called a local variable.

 These variables are created when the block is entered, or the function is called and destroyed after exiting
from the block or when the call returns from the function.

 The scope of these variables exists only within the block in which the variables are declared, i.e., we can
access these variables only within that block.

 Initialization of the local variable is mandatory before using it in the defined scope.

Time Complexity of the Method:

Time Complexity: O(1)


Auxiliary Space: O(1)
UNIT 2: Building Blocks of the Language
Below is the implementation of the above approach:

 Java

// Java Program to implement

// Local Variables

import java.io.*;

class GFG {

public static void main(String[] args)

// Declared a Local Variable

int var = 10;

// This variable is local to this main method only

System.out.println("Local Variable: " + var);

Output

Local Variable: 10

Example :

 Java

package a;

public class LocalVariable {

public static void main(String[] args)

// x is a local variable

int x = 10;

// message is also a local

// variable

String message = "Hello, world!";


UNIT 2: Building Blocks of the Language

System.out.println("x = " + x);

System.out.println("message = " + message);

if (x > 5) {

// result is a

// local variable

String result = "x is greater than 5";

System.out.println(result);

// Uncommenting the line below will result in a

// compile-time error System.out.println(result);

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

String loopMessage

= "Iteration "

+ i; // loopMessage is a local variable

System.out.println(loopMessage);

// Uncommenting the line below will result in a

// compile-time error

// System.out.println(loopMessage);

Output :

message = Hello, world!


x is greater than 5
Iteration 0
Iteration 1
Iteration 2
UNIT 2: Building Blocks of the Language
2. Instance Variables

Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block.

 As instance variables are declared in a class, these variables are created when an object of the class is
created and destroyed when the object is destroyed.

 Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access
specifier, then the default access specifier will be used.

 Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.

 Instance variables can be accessed only by creating objects.

 We initialize instance variables using constructors while creating an object. We can also use instance
blocks to initialize the instance variables.

The complexity of the method:

Time Complexity: O(1)


Auxiliary Space: O(1)

Below is the implementation of the above approach:

 Java

// Java Program to demonstrate

// Instance Variables

import java.io.*;

class GFG {

// Declared Instance Variable

public String geek;

public int i;

public Integer I;

public GFG()

// Default Constructor

// initializing Instance Variable

this.geek = "Shubham Jain";

// Main Method
UNIT 2: Building Blocks of the Language
public static void main(String[] args)

// Object Creation

GFG name = new GFG();

// Displaying O/P

System.out.println("Geek name is: " + name.geek);

System.out.println("Default value for int is "

+ name.i);

// toString() called internally

System.out.println("Default value for Integer is "

+ name.I);

Output

Geek name is: Shubham Jain

Default value for int is 0

Default value for Integer is null

3. Static Variables

Static variables are also known as class variables.

 These variables are declared similarly to instance variables. The difference is that static variables are
declared using the static keyword within a class outside of any method, constructor, or block.

 Unlike instance variables, we can only have one copy of a static variable per class, irrespective of how many
objects we create.

 Static variables are created at the start of program execution and destroyed automatically when execution
ends.

 Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable.
For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.

 If we access a static variable like an instance variable (through an object), the compiler will show a warning
message, which won’t halt the program. The compiler will replace the object name with the class name
automatically.

 If we access a static variable without the class name, the compiler will automatically append the class name.
But for accessing the static variable of a different class, we must mention the class name as 2 different
classes might have a static variable with the same name.
UNIT 2: Building Blocks of the Language
 Static variables cannot be declared locally inside an instance method.

 Static blocks can be used to initialize static variables.

The complexity of the method:

Time Complexity: O(1)


Auxiliary Space: O(1)

Below is the implementation of the above approach:

 Java

// Java Program to demonstrate

// Static variables

import java.io.*;

class GFG {

// Declared static variable

public static String geek = "Shubham Jain";

public static void main(String[] args)

// geek variable can be accessed without object

// creation Displaying O/P GFG.geek --> using the

// static variable

System.out.println("Geek Name is : " + GFG.geek);

// static int c=0;

// above line,when uncommented,

// will throw an error as static variables cannot be

// declared locally.

Output

Geek Name is : Shubham Jain


UNIT 2: Building Blocks of the Language
Differences Between the Instance Variables and the Static Variables

Now let us discuss the differences between the Instance variables and the Static variables:

 Each object will have its own copy of an instance variable, whereas we can only have one copy of a static
variable per class, irrespective of how many objects we create. Thus, static variables are good
for memory management.

 Changes made in an instance variable using one object will not be reflected in other objects as each object
has its own copy of the instance variable. In the case of a static variable, changes will be reflected in other
objects as static variables are common to all objects of a class.

 We can access instance variables through object references, and static variables can be accessed directly
using the class name.

 Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed
when the object is destroyed. Static variables are created when the program starts and destroyed when the
program stops.

Syntax: Static and instance variables

class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

Type conversion in Java with Examples


Java provides various data types just like any other dynamic languages such as boolean, char, int, unsigned int,
signed int, float, double, long, etc in total providing 7 types where every datatype acquires different space while
storing in memory. When you assign a value of one data type to another, the two types might not be compatible
with each other. If the data types are compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example, assigning an
int value to a long variable.

Datatype Bits Acquired In Memory

boolean 1

byte 8 (1 byte)

char 16 (2 bytes)

short 16(2 bytes)


UNIT 2: Building Blocks of the Language
Datatype Bits Acquired In Memory

int 32 (4 bytes)

long 64 (8 bytes)

float 32 (4 bytes)

double 64 (8 bytes)

Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted. This happens when:

 The two data types are compatible.

 When we assign a value of a smaller data type to a bigger data type.

For Example, in java, the numeric data types are compatible with each other but no automatic conversion is
supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.

Example:

 Java

// Java Program to Illustrate Automatic Type Conversion

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

int i = 100;

// Automatic type conversion


UNIT 2: Building Blocks of the Language
// Integer to long type

long l = i;

// Automatic type conversion

// long to float type

float f = l;

// Print and display commands

System.out.println("Int value " + i);

System.out.println("Long value " + l);

System.out.println("Float value " + f);

Output

Int value 100

Long value 100

Float value 100.0

Narrowing or Explicit Conversion

If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting or
narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.

 Here, the target type specifies the desired type to convert the specified value to.

char and number are not compatible with each other. Let’s see when we try to convert one into another.
UNIT 2: Building Blocks of the Language
 Java

// Java program to illustrate Incompatible data Type

// for Explicit Type Conversion

// Main class

public class GFG {

// Main driver method

public static void main(String[] argv)

// Declaring character variable

char ch = 'c';

// Declaringinteger variable

int num = 88;

// Trying to insert integer to character

ch = num;

Output: An error will be generated

This error is generated as an integer variable takes 4 bytes while character datatype requires 2 bytes. We are trying
to plot data from 4 bytes into 2 bytes which is not possible.
UNIT 2: Building Blocks of the Language
How to do Explicit Conversion?

// Java program to Illustrate Explicit Type Conversion

// Main class

public class GFG {

// Main driver method

public static void main(String[] args)

// Double datatype

double d = 100.04;

// Explicit type casting by forcefully getting

// data from long datatype to integer type

long l = (long)d;

// Explicit type casting

int i = (int)l;

// Print statements

System.out.println("Double value " + d);

// While printing we will see that

// fractional part lost

System.out.println("Long value " + l);

// While printing we will see that

// fractional part lost

System.out.println("Int value " + i);

}
UNIT 2: Building Blocks of the Language
Output

Double value 100.04

Long value 100

Int value 100

Note: While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).

Example:

 Java

// Java Program to Illustrate Conversion of

// Integer and Double to Byte

// Main class

class GFG {

// Main driver method

public static void main(String args[])

// Declaring byte variable

byte b;

// Declaring and initializing integer and double

int i = 257;

double d = 323.142;

// Display message

System.out.println("Conversion of int to byte.");

// i % 256

b = (byte)i;

// Print commands

System.out.println("i = " + i + " b = " + b);

System.out.println(
UNIT 2: Building Blocks of the Language
"\nConversion of double to byte.");

// d % 256

b = (byte)d;

// Print commands

System.out.println("d = " + d + " b= " + b);

Output

Conversion of int to byte.

i = 257 b = 1

Conversion of double to byte.

d = 323.142 b= 67

Type Promotion in Expressions

While evaluating expressions, the intermediate value may exceed the range of operands and hence the expression
value will be promoted. Some conditions for type promotion are:

1. Java automatically promotes each byte, short, or char operand to int when evaluating an expression.

2. If one operand is long, float or double the whole expression is promoted to long, float, or double
respectively.

Example:

 Java

// Java program to Illustrate Type promotion in Expressions

// Main class

class GFG {

// Main driver method

public static void main(String args[])

{
UNIT 2: Building Blocks of the Language
// Declaring and initializing primitive types

byte b = 42;

char c = 'a';

short s = 1024;

int i = 50000;

float f = 5.67f;

double d = .1234;

// The Expression

double result = (f * b) + (i / c) - (d * s);

// Printing the result obtained after

// all the promotions are done

System.out.println("result = " + result);

Output

result = 626.7784146484375

Explicit Type Casting in Expressions

While evaluating expressions, the result is automatically updated to a larger data type of the operand. But if we
store that result in any smaller data type it generates a compile-time error, due to which we need to typecast the
result.

Example:

 Java

// Java program to Illustrate Type Casting

// in Integer to Byte

// Main class

class GFG {

// Main driver method

public static void main(String args[])


UNIT 2: Building Blocks of the Language
{

// Declaring byte array

byte b = 50;

// Type casting int to byte

b = (byte)(b * 2);

// Display value in byte

System.out.println(b);

Output

100

Typecasting in Java
Typecasting in Java is the process of converting one data type to another data type using the casting operator. When
you assign a value from one primitive data type to another type, this is known as type casting. To enable the use of a
variable in a specific manner, this method requires explicitly instructing the Java compiler to treat a variable of one
data type as a variable of another data type.

Syntax:

<datatype> variableName = (<datatype>) value;

Types of Type Casting

There are two types of Type Casting in java:

 Widening Type Casting

 Narrow Type Casting

Widening Type Casting

A lower data type is transformed into a higher one by a process known as widening type casting. Implicit type casting
and casting down are some names for it. It occurs naturally. Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:

 The target type must be larger than the source type.

 Both data types must be compatible with each other.

Syntax:

larger_data_type variable_name = smaller_data_type_variable;


UNIT 2: Building Blocks of the Language

 Java

// Java program to demonstrate Widening TypeCasting

import java.io.*;

class GFG {

public static void main(String[] args)

int i = 10;

// Wideing TypeCasting (Automatic Casting)

// from int to long

long l = i;

// Wideing TypeCasting (Automatic Casting)

// from int to double

double d = i;

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

System.out.println("Long: " + l);

System.out.println("Double: " + d);

}
UNIT 2: Building Blocks of the Language
Output

Integer: 10

Long: 10

Double: 10.0

Narrow Type Casting

The process of downsizing a bigger data type into a smaller one is known as narrowing type casting. Casting up or
explicit type casting are other names for it. It doesn’t just happen by itself. If we don’t explicitly do that, a compile-
time error will occur. Narrowing type casting is unsafe because data loss might happen due to the lower data type’s
smaller range of permitted values. A cast operator assists in the process of explicit casting.

Syntax:

smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

Example:

 Java

// Java Program to demonstrate Narrow type casting

import java.io.*;

class GFG {

public static void main(String[] args)

double i = 100.245;

// Narrowing Type Casting

short j = (short)i;

int k = (int)i;
UNIT 2: Building Blocks of the Language

System.out.println("Original Value before Casting"

+ i);

System.out.println("After Type Casting to short "

+ j);

System.out.println("After Type Casting to int "

+ k);

Output

Original Value before Casting100.245

After Type Casting to short 100

After Type Casting to int 100

Types of Explicit Casting

Mainly there are two types of Explicit Casting:

 Explicit Upcasting

 Explicit Downcasting

Explicit Upcasting

Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction. When a sub-
class object is referenced by a superclass reference variable, an automatic process is triggered without any further
effort.

Example:

 Java

// Java Program to demonstrate Explicit Upcasting

import java.io.*;

class Animal {

public void makeSound()

System.out.println("The animal makes a sound");

}
UNIT 2: Building Blocks of the Language

class Dog extends Animal {

public void makeSound()

System.out.println("The dog barks");

public void fetch()

System.out.println("The dog fetches a ball");

class GFG {

public static void main(String[] args)

{ // Upcasting

Animal animal = new Dog();

// Calls the overridden method in Dog class

animal.makeSound();

// This would give a compile error as fetch() is not

// a method in Animal class

// animal.fetch();

Output

The dog barks

Explicit Downcasting

When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is done
manually, the compiler issues a runtime ClassCastException error. It can only be done by using the instanceof
operator. Only the downcast of an object that has already been upcast is possible.
UNIT 2: Building Blocks of the Language
Example:

// Java Program to demonstrate Explicit downcasting

import java.io.*;

class Animal {

public void eat()

System.out.println("The animal is eating.");

class Cat extends Animal {

public void meow()

System.out.println("The cat is meowing.");

class GFG {

public static void main(String[] args)

Animal animal = new Cat();

animal.eat();

// Explicit downcasting

Cat cat = (Cat)animal;

cat.meow();

Output

The animal is eating.

The cat is meowing.


UNIT 2: Building Blocks of the Language
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 and independent of function
call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be
covered under following categories.

Member Variables (Class Level Scope)

These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class.
Let’s take a look at an example:

public class Test

// All variables defined directly inside a class

// are member variables

int a;

private String b;

void method1() {....}

int method2() {....}

char c;

 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

Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no

modifier) Yes No No

private No No No
UNIT 2: Building Blocks of the Language
Local Variables (Method Level Scope)

Variables declared inside a method have method level scope and can’t be accessed outside the method.

public class Test

void method1()

// Local variable (Method level scope)

int x;

Note : Local variables don’t exist after method’s execution is over.

Here’s another example of method scope, except this time the variable got passed in as a parameter to the method:

class Test

private int x;

public void setX(int x)

this.x = x;

The above code uses this keyword to differentiate between the local and class variables.

As an exercise, predict the output of following Java program.

 Java

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;
UNIT 2: Building Blocks of the Language

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

Output:

Test.x: 22

t.x: 22

t.y: 33

y: 44

Loop Variables (Block Scope)


A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only.

 Java

public class Test

public static void main(String args[])

// The variable x has scope within

// brackets

int x = 10;

System.out.println(x);

}
UNIT 2: Building Blocks of the Language

// Uncommenting below line would produce

// error since variable x is out of scope.

// System.out.println(x);

Output:

10

As another example, consider following program with a for loop.

 Java

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

Output:

11: error: cannot find symbol

System.out.println(x);

The right way of doing above is,


UNIT 2: Building Blocks of the Language
// Above program after correcting the error

class Test

public static void main(String args[])

int x;

for (x = 0; x < 4; x++)

System.out.println(x);

System.out.println(x);

Output:

Let’s look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are
regular C/C++ programmer.

 Java

class Test

public static void main(String args[])

int a = 5;

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

System.out.println(a);
UNIT 2: Building Blocks of the Language
}

Output :

6: error: variable a is already defined in method go(int)

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

1 error

Note:- 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.
A similar program in C++ works. See this.

As an exercise, predict the output of the following Java program.

class Test

public static void main(String args[])

int x = 5;

int x = 10;

System.out.println(x);

Some 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.
UNIT 2: Building Blocks of the Language
Wrapper Classes in Java
A Wrapper class in Java is a class whose object wraps or contains primitive data types. When we create an object to
a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a
primitive value into a wrapper class object. Let’s check on the wrapper classes in Java with examples:

Need of Wrapper Classes

There are certain needs for using the Wrapper class in Java as mentioned below:

1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).

2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.

3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference
types) and not primitive types.

4. An object is needed to support synchronization in multithreading.

Advantages of Wrapper Classes

1. Collections allowed only object data.

2. On object data we can call multiple methods compareTo(), equals(), toString()

3. Cloning process only objects

4. Object data allowed null values.

5. Serialization can allow only object data.

Below are given examples of wrapper classes in Java with their corresponding Primitive data types in Java.

Primitive Data Types and their Corresponding Wrapper Class

Primitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float
UNIT 2: Building Blocks of the Language
Primitive Data Type Wrapper Class

double Double

boolean Boolean

Autoboxing and Unboxing

1. Autoboxing

The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.

Example:

// Java program to demonstrate Autoboxing

import java.util.ArrayList;

class Autoboxing {

public static void main(String[] args)

char ch = 'a';

// Autoboxing- primitive to Character object

// conversion

Character a = ch;

ArrayList<Integer> arrayList

= new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects

arrayList.add(25);

// printing the values from object

System.out.println(arrayList.get(0));

}
UNIT 2: Building Blocks of the Language
Output

25

2. Unboxing

It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its
corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double
to double, etc.

Example:

Java

// Java program to demonstrate Unboxing

import java.util.ArrayList;

class Unboxing {

public static void main(String[] args)

Character ch = 'a';

// unboxing - Character object to primitive

// conversion

char a = ch;

ArrayList<Integer> arrayList

= new ArrayList<Integer>();

arrayList.add(24);

// unboxing because get method returns an Integer

// object

int num = arrayList.get(0);

// printing the values from primitive data types

System.out.println(num);

}
UNIT 2: Building Blocks of the Language
Output

24

Java Wrapper Classes Example

Java

// Java program to demonstrate Wrapping and UnWrapping

// in Classes

import java.io.*;

class GFG {

public static void main(String[] args)

// byte data type

byte a = 1;

// wrapping around Byte object

Byte byteobj = new Byte(a);

// Use with Java 9

// Byte byteobj = Byte.valueOf(a);

// int data type

int b = 10;

// wrapping around Integer object

Integer intobj = new Integer(b);

// Use with Java 9

// Integer intobj = Integer.valueOf(b);

// float data type

float c = 18.6f;

// wrapping around Float object

Float floatobj = new Float(c);


UNIT 2: Building Blocks of the Language
// Use with Java 9

// Float floatobj = Float.valueOf(c);

// double data type

double d = 250.5;

// Wrapping around Double object

Double doubleobj = new Double(d);

// Use with Java 9

// Double doubleobj = Double.valueOf(d);

// char data type

char e = 'a';

// wrapping around Character object

Character charobj = e;

// printing the values from objects

System.out.println(

"Values of Wrapper objects (printing as objects)");

System.out.println("\nByte object byteobj: "

+ byteobj);

System.out.println("\nInteger object intobj: "

+ intobj);

System.out.println("\nFloat object floatobj: "

+ floatobj);

System.out.println("\nDouble object doubleobj: "

+ doubleobj);

System.out.println("\nCharacter object charobj: "

+ charobj);

// objects to data types (retrieving data types from


UNIT 2: Building Blocks of the Language
// objects) unwrapping objects to primitive data

// types

byte bv = byteobj;

int iv = intobj;

float fv = floatobj;

double dv = doubleobj;

char cv = charobj;

// printing the values from data types

System.out.println(

"\nUnwrapped values (printing as data types)");

System.out.println("\nbyte value, bv: " + bv);

System.out.println("\nint value, iv: " + iv);

System.out.println("\nfloat value, fv: " + fv);

System.out.println("\ndouble value, dv: " + dv);

System.out.println("\nchar value, cv: " + cv);

Output

Values of Wrapper objects (printing as objects)

Byte object byteobj: 1

Integer object intobj: 10

Float object floatobj: 18.6

Double object doubleobj: 250.5

Character object charobj: a

Unwrapped values (printing as data types)

byte value, bv: 1

int value, iv: 10

float value, fv: 18.6

double value, dv: 250.5

char value, cv: a


UNIT 2: Building Blocks of the Language
Custom Wrapper Classes in Java

Java Wrapper classes wrap the primitive data types. We can create a class that wraps data inside it. So let us check
how to create our own custom wrapper class in Java. It can be implemented for creating certain structures like
queues, stacks, etc.

Example:

Java

// Java Program to implement

// Custom wrapper class

import java.io.*;

// wrapper class

class Maximum {

private int maxi = 0;

private int size = 0;

public void insert(int x)

this.size++;

if (x <= this.maxi)

return;

this.maxi = x;

public int top() { return this.maxi; }

public int elementNumber() { return this.size; }

};

//

class GFG {

public static void main(String[] args)

Maximum x = new Maximum();


UNIT 2: Building Blocks of the Language
x.insert(12);

x.insert(3);

x.insert(23);

System.out.println("Maximum element: " + x.top());

System.out.println("Number of elements inserted: "

+ x.elementNumber());

Output

Maximum element: 23

Number of elements inserted: 3

1. Which are the wrapper classes in Java?

A Wrapper class in Java is a class whose object wraps or contains primitive data types.

2. Why use the wrapper class in Java?

The wrapper class in Java is used to convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method.

3. What are the 8 wrapper classes in Java?

There are 8 Wrapper classes in Java these are Boolean, Byte, Short, Character, Integer, Long, Float, Double.

Comments in Java
In a program, comments are like indents one makes, they are used so that it is easier for someone who isn’t familiar
with the language to be able to understand the code. It will also make the job easier for you, as a coder, to find
errors in the code since you will be easily able to find the location of the bug. Comments are ignored by the compiler
while compiling a code, which makes the job more complex in the long run when they have to go through so much
code to find one line.

In Java there are three types of comments:

1. Single-line comments.

2. Multi-line comments.

3. Documentation comments.

A. Single-line comments

A beginner-level programmer uses mostly single-line comments for describing the code functionality. It’s the easiest
typed comments.

Syntax:

//Comments here( Text in this line only is considered as comment )


UNIT 2: Building Blocks of the Language
Illustration:

Examples in an actual code

Example:

 Java

// Java program to show single line comments

class Scomment

public static void main(String args[])

// Single line comment here

System.out.println("Single line comment above");

Output:

Single line comment above

B. Multi-line Comments:

To describe a full method in a code or a complex snippet single line comments can be tedious to write since we have
to give ‘//’ at every line. So to overcome this multi-line comments can be used.

Syntax:

/*Comment starts

continues

continues

Comment ends*/
UNIT 2: Building Blocks of the Language
Example:

 Java

//Java program to show multi line comments

class Scomment

public static void main(String args[])

System.out.println("Multi line comments below");

/*Comment line 1

Comment line 2

Comment line 3*/

Output:

Multi line comments below

We can also accomplish single line comments by using the above syntax as shown below:

/*Comment line 1*/

C. Documentation Comments:

This type of comment is used generally when writing code for a project/software package, since it helps to generate
a documentation page for reference, which can be used for getting information about methods present, its
parameters, etc. For example, http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html is an auto-
generated documentation page that is generated by using documentation comments and a javadoc tool for
processing the comments.

Syntax:

/**Comment start

*tags are used in order to specify a parameter

*or method or heading

*HTML tags can also be used

*such as <h1>

*comment ends*/
UNIT 2: Building Blocks of the Language
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static void main (String[] args) {

/**

comment line 1

comment line 2

*/

Available tags to use:

Tag Description Syntax

@author Adds the author of a class. @author name-text

Displays text in code font without interpreting the text as


{@code} {@code text}
HTML markup or nested javadoc tags.

Represents the relative path to the generated document’s


{@docRoot} {@docRoot}
root directory from any generated page.

Adds a comment indicating that this API should no longer be


@deprecated @deprecated deprecatedtext
used.

Adds a Throws subheading to the generated @exception class-name


@exception
documentation, with the classname and description text. description

Inherits a comment from the nearest inheritable class or Inherits a comment from the
{@inheritDoc}
implementable interface. immediate surperclass.
UNIT 2: Building Blocks of the Language
Tag Description Syntax

Inserts an in-line link with the visible text label that points to
{@link package.class#member
{@link} the documentation for the specified package, class, or
label}
member name of a referenced class.

Identical to {@link}, except the link’s label is displayed in {@linkplain


{@linkplain}
plain text than code font. package.class#member label}

Adds a parameter with the specified parameter-name


@param parameter-name
@param followed by the specified description to the “Parameters”
description
section.

@return Adds a “Returns” section with the description text. @return description

Adds a “See Also” heading with a link or text entry that


@see @see reference
points to reference.

@serial field-description |
@serial Used in the doc comment for a default serializable field.
include | exclude

Documents the data written by the writeObject( ) or


@serialData @serialData data-description
writeExternal( ) methods.

@serialField field-name field-


@serialField Documents an ObjectStreamField component.
type field-description

Adds a “Since” heading with the specified since-text to the


@since @since release
generated documentation.

@throws class-name
@throws The @throws and @exception tags are synonyms.
description

When {@value} is used in the doc comment of a static field,


{@value} {@value package.class#field}
it displays the value of that constant.
UNIT 2: Building Blocks of the Language
Tag Description Syntax

Adds a “Version” subheading with the specified version-text


@version @version version-text
to the generated docs when the -version option is used.

Implementation:

// Java program to illustrate frequently used

// Comment tags

/**

* <h1>Find average of three numbers!</h1>

* The FindAvg program implements an application that

* simply calculates average of three integers and Prints

* the output on the screen.

* @author Pratik Agarwal

* @version 1.0

* @since 2017-02-18

*/

public class FindAvg

/**

* This method is used to find average of three integers.

* @param numA This is the first parameter to findAvg method

* @param numB This is the second parameter to findAvg method

* @param numC This is the second parameter to findAvg method

* @return int This returns average of numA, numB and numC.

*/

public int findAvg(int numA, int numB, int numC)

return (numA + numB + numC)/3;

}
UNIT 2: Building Blocks of the Language
/**

* This is the main method which makes use of findAvg method.

* @param args Unused.

* @return Nothing.

*/

public static void main(String args[])

FindAvg obj = new FindAvg();

int avg = obj.findAvg(10, 20, 30);

System.out.println("Average of 10, 20 and 30 is :" + avg);

Output:

Average of 10, 20 and 30 is :20

For the above code documentation can be generated by using the tool ‘javadoc’:

Javadoc can be used by running the following command in the terminal.

javadoc FindAvg.java

Garbage Collection in Java


Garbage collection in Java is the process by which Java programs perform automatic memory management. Java
programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run
on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually,
some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up
memory.

What is Garbage Collection?

In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually, programmer
neglects the destruction of useless objects. Due to this negligence, at a certain point, sufficient memory may not be
available to create new objects, and the entire program will terminate abnormally, causing OutOfMemoryErrors.

But in Java, the programmer need not care for all those objects which are no longer in use. Garbage collector
destroys these objects. The main objective of Garbage Collector is to free heap memory by destroying unreachable
objects. The garbage collector is the best example of the Daemon thread as it is always running in the background.

How Does Garbage Collection in Java works?

Java garbage collection is an automatic process. Automatic garbage collection is the process of looking at heap
memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object,
or a referenced object, means that some part of your program still maintains a pointer to that object. An unused or
UNIT 2: Building Blocks of the Language
unreferenced object is no longer referenced by any part of your program. So the memory used by an unreferenced
object can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage
collection implementation lives in the JVM.

Types of Activities in Java Garbage Collection

Two types of garbage collection activity usually happen in Java. These are:

1. Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young
generation heap memory are removed.

2. Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor
garbage collection are copied into the old generation or permanent generation heap memory are removed.
When compared to the young generation, garbage collection happens less frequently in the old generation.

Important Concepts Related to Garbage Collection in Java

1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference to it. Also, note that
objects which are part of the island of isolation are also unreachable.

Integer i = new Integer(4);

// the new Integer object is reachable via the reference in 'i'

i = null;

// the Integer object is no longer reachable.

2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage collection) if it is unreachable.
After i = null, integer object 4 in the heap area is suitable for garbage collection in the above image.

Ways to make an object eligible for Garbage Collector

 Even though the programmer is not responsible for destroying useless objects but it is highly recommended
to make an object unreachable(thus eligible for GC) if it is no longer required.

 There are generally four ways to make an object eligible for garbage collection.

1. Nullifying the reference variable

2. Re-assigning the reference variable

3. An object created inside the method

4. Island of Isolation
UNIT 2: Building Blocks of the Language
Ways for requesting JVM to run Garbage Collector

 Once we make an object eligible for garbage collection, it may not destroy immediately by the garbage
collector. Whenever JVM runs the Garbage Collector program, then only the object will be destroyed. But
when JVM runs Garbage Collector, we can not expect.

 We can also request JVM to run Garbage Collector. There are two ways to do it :

1. Using System.gc() method: System class contain static method gc() for requesting JVM to run
Garbage Collector.

2. Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the
JVM in which the application is running. Hence by using its gc() method, we can request JVM to run
Garbage Collector.

3. There is no guarantee that any of the above two methods will run Garbage Collector.

4. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()

Finalization

 Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup
activities. Once finalize() method completes, Garbage Collector destroys that object.

 finalize() method is present in Object class with the following prototype.

protected void finalize() throws Throwable

Based on our requirement, we can override finalize() method for performing our cleanup activities like closing
connection from the database.

1. The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the
modules of JVM.

2. Object class finalize() method has an empty implementation. Thus, it is recommended to override
the finalize() method to dispose of system resources or perform other cleanups.

3. The finalize() method is never invoked more than once for any object.

4. If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of
that object terminates.

Advantages of Garbage Collection in Java

The advantages of Garbage Collection in Java are:

 It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap
memory.

 It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort.

Real-World Example

Let’s take a real-life example, where we use the concept of the garbage collector.

Question: Suppose you go for the internship at GeeksForGeeks, and you were told to write a program to count the
number of employees working in the company(excluding interns). To make this program, you have to use the
concept of a garbage collector.
UNIT 2: Building Blocks of the Language
This is the actual task you were given at the company:

Write a program to create a class called Employee having the following data members.

1. An ID for storing unique id allocated to every employee.


2. Name of employee.
3. age of an employee.

Also, provide the following methods:

1. A parameterized constructor to initialize name and age. The ID should be initialized in this constructor.

2. A method show() to display ID, name, and age.

3. A method showNextId() to display the ID of the next employee.

Now any beginner, who doesn’t know Garbage Collector in Java will code like this:

 Java

// Java Program to count number

// of employees working

// in a company

class Employee {

private int ID;

private String name;

private int age;

private static int nextId = 1;

// it is made static because it

// is keep common among all and

// shared by all objects

public Employee(String name, int age)

this.name = name;

this.age = age;

this.ID = nextId++;

public void show()

{
UNIT 2: Building Blocks of the Language
System.out.println("Id=" + ID + "\nName=" + name

+ "\nAge=" + age);

public void showNextId()

System.out.println("Next employee id will be="

+ nextId);

class UseEmployee {

public static void main(String[] args)

Employee E = new Employee("GFG1", 56);

Employee F = new Employee("GFG2", 45);

Employee G = new Employee("GFG3", 25);

E.show();

F.show();

G.show();

E.showNextId();

F.showNextId();

G.showNextId();

{ // It is sub block to keep

// all those interns.

Employee X = new Employee("GFG4", 23);

Employee Y = new Employee("GFG5", 21);

X.show();

Y.show();

X.showNextId();

Y.showNextId();

}
UNIT 2: Building Blocks of the Language
// After countering this brace, X and Y

// will be removed.Therefore,

// now it should show nextId as 4.

// Output of this line

E.showNextId();

// should be 4 but it will give 6 as output.

Output

Id=1

Name=GFG1

Age=56

Id=2

Name=GFG2

Age=45

Id=3

Name=GFG3

Age=25

Next employee id will be=4

Next employee id will be=4

Next employee id will be=4

Id=4

Name=GFG4

Age=23

Id=5

Name=GFG5

Age=21

Next employee id will be=6

Next employee id will be=6

Next employee id will be=6


UNIT 2: Building Blocks of the Language
Now to get the correct output:
Now garbage collector(gc) will see 2 objects free. Now to decrement nextId,gc(garbage collector) will call method to
finalize() only when we programmers have overridden it in our class. And as mentioned previously, we have to
request gc(garbage collector), and for this, we have to write the following 3 steps before closing brace of sub-block.

1. Set references to null(i.e X = Y = null;)

2. Call, System.gc();

3. Call, System.runFinalization();

Now the correct code for counting the number of employees(excluding interns)

// Correct code to count number

// of employees excluding interns.

class Employee {

private int ID;

private String name;

private int age;

private static int nextId = 1;

// it is made static because it

// is keep common among all and

// shared by all objects

public Employee(String name, int age)

this.name = name;

this.age = age;

this.ID = nextId++;

public void show()

System.out.println("Id=" + ID + "\nName=" + name

+ "\nAge=" + age);

public void showNextId()


UNIT 2: Building Blocks of the Language
{

System.out.println("Next employee id will be="

+ nextId);

protected void finalize()

--nextId;

// In this case,

// gc will call finalize()

// for 2 times for 2 objects.

public class UseEmployee {

public static void main(String[] args)

Employee E = new Employee("GFG1", 56);

Employee F = new Employee("GFG2", 45);

Employee G = new Employee("GFG3", 25);

E.show();

F.show();

G.show();

E.showNextId();

F.showNextId();

G.showNextId();

// It is sub block to keep

// all those interns.

Employee X = new Employee("GFG4", 23);

Employee Y = new Employee("GFG5", 21);

X.show();
UNIT 2: Building Blocks of the Language
Y.show();

X.showNextId();

Y.showNextId();

X = Y = null;

System.gc();

System.runFinalization();

E.showNextId();

Output

Id=1

Name=GFG1

Age=56

Id=2

Name=GFG2

Age=45

Id=3

Name=GFG3

Age=25

Next employee id will be=4

Next employee id will be=4

Next employee id will be=4

Id=4

Name=GFG4

Age=23

Id=5

Name=GFG5

Age=21

Next employee id will be=6

Next employee id will be=6

Next employee id will be=4


UNIT 2: Building Blocks of the Language
Arrays in Java
In Java, Array is a group of like-typed variables 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.

Arrays in Java

 In Java, all arrays are dynamically allocated. (discussed below)

 Arrays may be stored in contiguous memory [consecutive memory locations].

 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 has an index beginning with 0.

 Java array can also be used as a static field, a local variable, or a method parameter.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the
definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory
locations(JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap
segment.

Note: This storage of arrays helps us randomly access the elements of an array [Support Random Access].

Creating, Initializing, and Accessing an Arrays

One-Dimensional Arrays

The general form of a one-dimensional array declaration is

-- type var-name[];
-- 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.

Example:

// both are valid declarations


int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
UNIT 2: Building Blocks of the Language
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;

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

Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To create or give memory to the array, you create
an array like this: 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 determines the number of elements in the array, and var-
name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify
the type and number of elements to allocate.

Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in oneint[]
intArray = new int[20];

Note: 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). Do refer to default array values in Java.

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 to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays
are dynamically allocated.

Array Literal in Java

In a situation where the size of the array and variables of the array are already known, array literals can be used.

// Declaring array literal


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.

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.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
UNIT 2: Building Blocks of the Language
Implementation:

// Java program to illustrate creating an array

// of integers, puts some values in the array,

// and prints each value to standard output.

class GFG {

public static void main(String[] args)

// declares an Array of integers.

int[] arr;

// allocating memory for 5 integers.

arr = new int[5];

// initialize the first elements of the array

arr[0] = 10;

// initialize the second elements of the array

arr[1] = 20;

// so on...

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

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

System.out.println("Element at index " + i

+ " : " + arr[i]);

}
UNIT 2: Building Blocks of the Language
Output

Element at index 0 : 10

Element at index 1 : 20

Element at index 2 : 30

Element at index 3 : 40

Element at index 4 : 50

Complexity of the above method:

Time Complexity: O(n)


Auxiliary Space: O(1)

You can also access java arrays using for each loops.

Arrays of Objects in Java

An array of objects is created like an array of primitive-type data items in the following way.

Student[] arr = new Student[5]; //student is a user-defined class

Syntax:

-- data type[] arrName;


-- datatype arrName[];
-- datatype [] arrName;

Example of Arrays of Objects

Example 1:

Below is the implementation of the above mentioned topic:


UNIT 2: Building Blocks of the Language
import java.io.*;

class GFG {

public static void main (String[] args) {

int [] arr=new int [4];

// 4 is the size of arr

System.out.println("Array Size:"+arr.length);

Output

Array Size:4

The student Array contains five memory spaces each of the size of student class in which the address of five 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.

Example 2:

Below is the implementation of the above mentioned topic:

// Java program to illustrate creating

// an array of objects

class Student {

public int roll_no;

public String name;

Student(int roll_no, String name)

this.roll_no = roll_no;

this.name = name;

// Elements of the array are objects of a class Student.


UNIT 2: Building Blocks of the Language
public class GFG {

public static void main(String[] args)

// declares an Array of Students

Student[] arr;

// allocating memory for 5 objects of type Student.

arr = new Student[5];

// initialize the first elements of the array

arr[0] = new Student(1, "aman");

// initialize the second elements of the array

arr[1] = new Student(2, "vaibhav");

// so on...

arr[2] = new Student(3, "shikar");

arr[3] = new Student(4, "dharmesh");

arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array

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

System.out.println("Element at " + i + " : "

+ arr[i].roll_no + " "

+ arr[i].name);

Output

Element at 0 : 1 aman

Element at 1 : 2 vaibhav

Element at 2 : 3 shikar

Element at 3 : 4 dharmesh

Element at 4 : 5 mohit
UNIT 2: Building Blocks of the Language
Complexity of the above method:

Time Complexity: O(n)


Auxiliary Space : O(1)

Example 3

An array of objects is also created like :

Java

// Java program to illustrate creating

// an array of objects

class Student

public String name;

Student(String name)

this.name = name;

@Override

public String toString(){

return name;

// Elements of the array are objects of a class Student.

public class GFG

public static void main (String[] args)

// declares an Array and initializing the elements of the array

Student[] myStudents = new Student[]{new Student("Dharma"),new Student("sanvi"),new Student("Rupa"),new Studen

// accessing the elements of the specified array


UNIT 2: Building Blocks of the Language
for(Student m:myStudents){

System.out.println(m);

Output

Dharma

sanvi

Rupa

Ajay

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index.
The index is either negative or greater than or equal to the size of an array.

Below code shows what happens if we try to access elements outside the array size:

Java

// Code for showing error "ArrayIndexOutOfBoundsException"

public class GFG {

public static void main(String[] args)

int[] arr = new int[4];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

System.out.println(

"Trying to access element outside the size of array");

System.out.println(arr[5]);

}
UNIT 2: Building Blocks of the Language
Output

Trying to access element outside the size of array


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at GFG.main(GFG.java:13)

Example (Iterating the array):

Java

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

Output

10

20

Complexity of the above method:

Time Complexity: O(n),here n is size of array.


Auxiliary Space: O(1), since no extra space required.

Multidimensional Arrays in Java

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays.
These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets
([]) per dimension.

Syntax of Java Multidimensional Array

There are 2 methods to declare Java Multidimensional Arrays as mentioned below:

-- datatype [][] arrayrefvariable;


-- datatype arrayrefvariable[][];
UNIT 2: Building Blocks of the Language
Example:

// Java Program to demonstrate

// Java Multidimensional Array

import java.io.*;

// Driver class

class GFG {

public static void main(String[] args)

// Syntax

int[][] arr = new int[3][3];

// 3 row and 3 column

// Number of Rows

System.out.println("Number of Rows:"+

arr.length);

// Number of Columns

System.out.println("Number of Columns:"+

arr[0].length);

Output

Number of Rows:3

Number of Columns:3
UNIT 2: Building Blocks of the Language
Multidimensional Array Declaration

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

Example of Muilti Dimensional Array in Java

Example 1:

Below is the implementation of the above method:

Java

// Java Program to Multidimensional Array

// Driver Class

public class multiDimensional {

// main function

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

Output

279

361

742
UNIT 2: Building Blocks of the Language
Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, the below program passes the array to
method sum to calculate the sum of the array’s values.

Java

// Java program to demonstrate

// passing of array to method

public class Test {

// Driver method

public static void main(String args[])

int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1

sum(arr);

public static void sum(int[] arr)

// getting sum of array values

int sum = 0;

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

sum += arr[i];

System.out.println("sum of array values : " + sum);

Output

sum of array values : 15


UNIT 2: Building Blocks of the Language
Complexity of the above method:

Time Complexity: O(n)


Auxiliary Space : O(1)

Returning Arrays from Methods

As usual, a method can also return an array. For example, the below program returns an array from method m1.

Java

// Java program to demonstrate

// return of array from method

class Test {

// Driver method

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

// returning array

return new int[] { 1, 2, 3 };

Output

123

Complexity of the above method:

Time Complexity: O(n)


Auxiliary Space : O(1)

Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the same component type.
UNIT 2: Building Blocks of the Language
// Java program to demonstrate

// Class Objects for Arrays

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

Output

class [I

class java.lang.Object

class [B

class [S

class [Ljava.lang.String;

Explanation of the above method:

1. The string “[I” is the run-time type signature for the class object “array with component type int.”

2. The only direct superclass of an array type is java.lang.Object.

3. The string “[B” is the run-time type signature for the class object “array with component type byte.”

4. The string “[S” is the run-time type signature for the class object “array with component type short.”

5. 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.
UNIT 2: Building Blocks of the Language
Java Array Members

Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members
of an array type are all of the following:

 The public final field length contains the number of components of the array. Length may be positive or zero.

 All the members are inherited from class Object; the only method of Object that is not inherited is
its clone method.

 The public method clone() overrides the clone method in class Object and throws no checked exceptions.

Arrays Types and Their Allowed Element Types

Array Types Allowed Element Types

Any type which can be implicitly promoted to declared


Primitive Type Arrays
type.

Object Type Arrays Either declared type objects or it’s child class objects.

Abstract Class Type Arrays Its child-class objects are allowed.

Interface Type Arrays Its implementation class objects are allowed.

Cloning of Single-Dimensional Array in Java

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.

Below is the implementation of the above method:

Java

// Java program to demonstrate

// cloning of one-dimensional arrays

class Test {

public static void main(String args[])

int intArray[] = { 1, 2, 3 };

int cloneArray[] = intArray.clone();


UNIT 2: Building Blocks of the Language
// 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] + " ");

Output

false

123

Cloning Multidimensional Array in Java

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.
UNIT 2: Building Blocks of the Language
// Java program to demonstrate

// cloning of multi-dimensional arrays

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

Output

false

true

true
UNIT 2: Building Blocks of the Language
Frequently Asked Questions in Java Arrays

1. Can we specify the size of array as long?

No we can’t specify the size of array as long but we can specify it as int or short.

2. Which is the direct superclass of an array in Java?

An Object is direct superclass of an array in Java.

3. Which Interfaces are implemented by Arrays in Java?

Every array type implements the interfaces Cloneable and java.io.Serializable.

4. Can we alter the size of Array?

The size of the array cannot be altered(once initialized). However, an array reference can be made to point to
another array.

String class in Java


The string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot
be changed once created.

Creating a String

There are two ways to create string in Java:

1. String literal

String s = “GeeksforGeeks”;

2. Using new keyword

String s = new String (“GeeksforGeeks”);

String Constructors in Java

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 = {71, 101, 101, 107, 115};


String s_byte =new String(b_arr); //Geeks

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 = {71, 101, 101, 107, 115};


Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks
UNIT 2: Building Blocks of the Language
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
above constructs and they appear before similar functions but it takes the String(which contains char_set_name) as
parameter while the above constructor takes CharSet.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};


String s = new String(b_arr, "US-ASCII"); //Geeks

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 = {71, 101, 101, 107, 115};


String s = new String(b_arr, 1, 3); // eek

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 for decoding.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};


Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek

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 = {71, 101, 101, 107, 115};


String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks

7. String(char[] char_arr)

Allocates a new String from the given Character array

Example:

char char_arr[] = {'G', 'e', 'e', 'k', 's'};


String s = new String(char_arr); //Geeks

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[] = {'G', 'e', 'e', 'k', 's'};


String s = new String(char_arr , 1, 3); //eek
UNIT 2: Building Blocks of the Language
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 = {71, 101, 101, 107, 115};


String s = new String(uni_code, 1, 3); //eek

10. String(StringBuffer s_buffer)

Allocates a new string from the string in s_buffer

Example:

StringBuffer s_buffer = new StringBuffer("Geeks");


String s = new String(s_buffer); //Geeks

11. String(StringBuilder s_builder)

Allocates a new string from the string in s_builder

Example:

StringBuilder s_builder = new StringBuilder("Geeks");


String s = new String(s_builder); //Geeks

String Methods in Java

1. int length()

Returns the number of characters in the String.

"GeeksforGeeks".length(); // returns 13

2. Char charAt(int i)

Returns the character at ith index.

"GeeksforGeeks".charAt(3); // returns ‘k’

3. String substring (int i)

Return the substring from the ith index character to end.

"GeeksforGeeks".substring(3); // returns “ksforGeeks”

4. String substring (int i, int j)

Returns the substring from i to j-1 index.

"GeeksforGeeks".substring(2, 5); // returns “eks”

5. String concat( String str)

Concatenates specified string to the end of this string.

String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
UNIT 2: Building Blocks of the Language
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

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 = “Geeks”.equals(“Geeks”); // returns true


Boolean out = “Geeks”.equals(“geeks”); // returns false

10. boolean equalsIgnoreCase (String anotherString)

Compares string to another string, ignoring case considerations.

Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true


Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

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.
UNIT 2: Building Blocks of the Language
Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).

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”

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 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksforgeeks”

Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks

17. boolean contains(string) :

Returns true if string contains contains the given string

String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true

18. Char[] toCharArray():

Converts this String to a new character array.

String s1="geeksforgeeks";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]

19. boolean starsWith(string):

Return true if string starts with this prefix.

String s1="geeksforgeeks";
String s2="geeks";
s1.startsWith(s2) // return true

Example of String Constructor and String Methods

Below is the implementation of the above mentioned topic:


UNIT 2: Building Blocks of the Language
// Java code to illustrate different constructors and methods

// String class.

import java.io.*;

import java.util.*;

// Driver Class

class Test

// main function

public static void main (String[] args)

String s= "GeeksforGeeks";

// or String s= new String ("GeeksforGeeks");

// Returns the number of characters in the String.

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

// Returns the character at ith index.

System.out.println("Character at 3rd position = "

+ s.charAt(3));

// Return the substring from the ith index character

// to end of string

System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.

System.out.println("Substring = " + s.substring(2,5));

// Concatenates string2 to the end of string1.

String s1 = "Geeks";

String s2 = "forGeeks";

System.out.println("Concatenated string = " +


UNIT 2: Building Blocks of the Language
s1.concat(s2));

// Returns the index within the string

// of the first occurrence of the specified string.

String s4 = "Learn Share Learn";

System.out.println("Index of Share " +

s4.indexOf("Share"));

// Returns the index within the string of the

// first occurrence of the specified string,

// starting at the specified index.

System.out.println("Index of a = " +

s4.indexOf('a',3));

// Checking equality of Strings

Boolean out = "Geeks".equals("geeks");

System.out.println("Checking Equality " + out);

out = "Geeks".equals("Geeks");

System.out.println("Checking Equality " + out);

out = "Geeks".equalsIgnoreCase("gEeks ");

System.out.println("Checking Equality " + out);

//If ASCII difference is zero then the two strings are similar

int out1 = s1.compareTo(s2);

System.out.println("the difference between ASCII value is="+out1);

// Converting cases

String word1 = "GeeKyMe";

System.out.println("Changing to lower Case " +

word1.toLowerCase());

// Converting cases
UNIT 2: Building Blocks of the Language
String word2 = "GeekyME";

System.out.println("Changing to UPPER Case " +

word2.toUpperCase());

// Trimming the word

String word4 = " Learn Share Learn ";

System.out.println("Trim the word " + word4.trim());

// Replacing characters

String str1 = "feeksforfeeks";

System.out.println("Original String " + str1);

String str2 = "feeksforfeeks".replace('f' ,'g') ;

System.out.println("Replaced f with g -> " + str2);

Learn Data Structures & Algorithms with GeeksforGeeks

Output

String length = 13

Character at 3rd position = k

Substring ksforGeeks

Substring = eks

Concatenated string = GeeksforGeeks

Index of Share 6

Index of a = 8

Checking Equality false

Checking Equality ...

Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the
functionality they provide. In this article, we will learn about Java Operators and learn all their types.

What are the Java Operators?

Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks like
addition, multiplication, etc which look easy although the implementation of these tasks is quite complex.
UNIT 2: Building Blocks of the Language
Types of Operators in Java

There are multiple types of operators in Java all are mentioned below:

1. Arithmetic Operators

2. Unary Operators

3. Assignment Operator

4. Relational Operators

5. Logical Operators

6. Ternary Operator

7. Bitwise Operators

8. Shift Operators

9. instance of operator

1. Arithmetic Operators

They are used to perform simple arithmetic operations on primitive data types.

 * : Multiplication

 / : Division

 % : Modulo

 + : Addition

 – : Subtraction

Example:

 Java

// Java Program to implement

// Arithmetic Operators

import java.io.*;

// Drive Class

class GFG {

// Main Function

public static void main (String[] args) {

// Arithmetic operators

int a = 10;

int b = 3;
UNIT 2: Building Blocks of the Language

System.out.println("a + b = " + (a + b));

System.out.println("a - b = " + (a - b));

System.out.println("a * b = " + (a * b));

System.out.println("a / b = " + (a / b));

System.out.println("a % b = " + (a % b));

Output

a + b = 13

a-b=7

a * b = 30

a/b=3

a%b=1

2. 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 the positive value (numbers are positive without this, however). It performs an
automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary
numeric promotion.

 ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.

 Post-Increment: Value is first used for computing the result and then incremented.

 Pre-Increment: Value is incremented first, and then the result is computed.

 – – : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement
operators.

 Post-decrement: Value is first used for computing the result and then decremented.

 Pre-Decrement: The value is decremented first, and then the result is computed.

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


UNIT 2: Building Blocks of the Language
Example:

// Java Program to implement

// Uniary Operators

import java.io.*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

// Interger declared

int a = 10;

int b = 10;

// Using uniary operators

System.out.println("Postincrement : " + (a++));

System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));

System.out.println("Predecrement : " + (--b));

Output

Postincrement : 10

Preincrement : 12

Postdecrement : 10

Predecrement : 8

3. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value given on
the right-hand side of the 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.

The general format of the assignment operator is:


UNIT 2: Building Blocks of the Language
variable = value;

In many cases, the assignment operator can be combined with other operators to build a shorter version of the
statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5.

 +=, for adding the left operand with the right operand and then assigning it to the variable on the left.

 -=, for subtracting the right operand from the left operand and then assigning it to the variable on the left.

 *=, for multiplying the left operand with the right operand and then assigning it to the variable on the left.

 /=, for dividing the left operand by the right operand and then assigning it to the variable on the left.

 %=, for assigning the modulo of the left operand by the right operand and then assigning it to the variable on
the left.

Example:

// Java Program to implement

// Assignment Operators

import java.io.*;

// Driver Class

class GFG {

// Main Function

public static void main(String[] args)

// Assignment operators

int f = 7;

System.out.println("f += 3: " + (f += 3));

System.out.println("f -= 2: " + (f -= 2));

System.out.println("f *= 4: " + (f *= 4));

System.out.println("f /= 3: " + (f /= 3));

System.out.println("f %= 2: " + (f %= 2));

System.out.println("f &= 0b1010: " + (f &= 0b1010));

System.out.println("f |= 0b1100: " + (f |= 0b1100));

System.out.println("f ^= 0b1010: " + (f ^= 0b1010));

System.out.println("f <<= 2: " + (f <<= 2));

System.out.println("f >>= 1: " + (f >>= 1));


UNIT 2: Building Blocks of the Language
System.out.println("f >>>= 1: " + (f >>>= 1));

Output

f += 3: 10

f -= 2: 8

f *= 4: 32

f /= 3: 10

f %= 2: 0

f &= 0b1010: 0

f |= 0b1100: 12

f ^= 0b1010: 6

f <<= 2: 24

f >>= 1: 12

f >>>= 1: 6

4. Relational Operators

These operators are used to check for relations like equality, greater than, and less than. They return boolean results
after the comparison and are extensively used in looping statements as well as conditional if-else statements. The
general format is,

variable relation_operator value

Some of the relational operators are-

 ==, Equal to returns true if the left-hand side is equal to the right-hand side.

 !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.

 <, less than: returns true if the left-hand side is less than the right-hand side.

 <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.

 >, Greater than: returns true if the left-hand side is greater than the right-hand side.

 >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side.
UNIT 2: Building Blocks of the Language
Example:

// Java Program to implement

// Relational Operators

import java.io.*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

// Comparison operators

int a = 10;

int b = 3;

int c = 5;

System.out.println("a > b: " + (a > b));

System.out.println("a < b: " + (a < b));

System.out.println("a >= b: " + (a >= b));

System.out.println("a <= b: " + (a <= b));

System.out.println("a == c: " + (a == c));

System.out.println("a != c: " + (a != c));

Output

a > b: true

a < b: false

a >= b: true

a <= b: false

a == c: false

a != c: true
UNIT 2: Building Blocks of the Language
5. Logical Operators

These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar to AND gate
and OR gate in digital electronics. One thing to keep in mind is 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. Java
also has “Logical NOT”, which returns true when the condition is false and vice-versa

Conditional operators are:

 &&, Logical AND: returns true when both conditions are true.

 ||, Logical OR: returns true if at least one condition is true.

 !, Logical NOT: returns true when a condition is false and vice-versa

Example:

 Java

// Java Program to implemenet

// Logical operators

import java.io.*;

// Driver Class

class GFG {

// Main Function

public static void main (String[] args) {

// Logical operators

boolean x = true;

boolean y = false;

System.out.println("x && y: " + (x && y));

System.out.println("x || y: " + (x || y));

System.out.println("!x: " + (!x));

Output

x && y: false

x || y: true

!x: false
UNIT 2: Building Blocks of the Language
6. Ternary operator

The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name
Ternary.

The general format is:

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else
execute the statements after the ‘:’.

Example:

 Java

// Java program to illustrate

// max of three numbers using

// ternary operator.

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

Output

Max of three numbers = 30

7. Bitwise Operators

These operators are used to perform the manipulation of individual bits of a number. They can be used with any of
the integer types. They are used when performing update and query operations of the Binary indexed trees.

 &, 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.


UNIT 2: Building Blocks of the Language
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement
representation of the input value, i.e., with all bits inverted.

// Java Program to implement

// bitwise operators

import java.io.*;

// Driver class

class GFG {

// main function

public static void main(String[] args)

// Bitwise operators

int d = 0b1010;

int e = 0b1100;

System.out.println("d & e: " + (d & e));

System.out.println("d | e: " + (d | e));

System.out.println("d ^ e: " + (d ^ e));

System.out.println("~d: " + (~d));

System.out.println("d << 2: " + (d << 2));

System.out.println("e >> 1: " + (e >> 1));

System.out.println("e >>> 1: " + (e >>> 1));

Output

d & e: 8

d | e: 14

d ^ e: 6

~d: -11

d << 2: 40

e >> 1: 6

e >>> 1: 6
UNIT 2: Building Blocks of the Language
8. 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. General format-

number shift_op number_of_places_to_shift;

 <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as 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 the initial number. Similar effect to 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.

 Java

// Java Program to implement

// shift operators

import java.io.*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

int a = 10;

// using left shift

System.out.println("a<<1 : " + (a << 1));

// using right shift

System.out.println("a>>1 : " + (a >> 1));

Output

a<<1 : 20

a>>1 : 5
UNIT 2: Building Blocks of the Language

9. instanceof operator

The instance of the 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. General format-

object instance of class/subclass/interface

// Java program to illustrate

// instance of operator

class operators {

public static void main(String[] args)

Person obj1 = new Person();

Person obj2 = new Boy();

// As obj is of type person, it is not an

// instance of Boy or interface

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

// Since obj2 is of type boy,

// whose parent class is person

// and it implements the interface Myinterface

// it is instance of all of these classes

System.out.println("obj2 instanceof Person: "

+ (obj2 instanceof Person));

System.out.println("obj2 instanceof Boy: "

+ (obj2 instanceof Boy));


UNIT 2: Building Blocks of the Language
System.out.println("obj2 instanceof MyInterface: "

+ (obj2 instanceof MyInterface));

class Person {

class Boy extends Person implements MyInterface {

interface MyInterface {

Output

obj1 instanceof Person: true

obj1 instanceof Boy: false

obj1 instanceof MyInterface: false

obj2 instanceof Person: true

obj2 instanceof Boy: true

obj2 instanceof MyInterface: true

Precedence and Associativity of Java Operators

Precedence and associative rules are used when dealing with hybrid equations involving more than one type of
operator. In such cases, these rules determine which part of the equation to consider first, as there can be many
different valuations for the same equation. The below table depicts the precedence of operators in decreasing order
as magnitude, with the top representing the highest precedence and the bottom showing the lowest precedence.
UNIT 2: Building Blocks of the Language

Interesting Questions about Java Operators

1. Precedence and Associativity:

There is often confusion when it comes to hybrid equations which are equations having multiple operators. The
problem is which part to solve first. There is a golden rule to follow in these situations. If the operators have
different precedence, solve the higher precedence first. If they have the same precedence, solve according to
associativity, that is, either from right to left or from left to right. The explanation of the below program is well
written in comments within the program itself.

public class operators {

public static void main(String[] args)

int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;

// precedence rules for arithmetic operators.

// (* = / = %) > (+ = -)

// prints a+(b/d)

System.out.println("a+b/d = " + (a + b / d));

// if same precedence then associative

// rules are followed.


UNIT 2: Building Blocks of the Language
// e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)

System.out.println("a+b*d-e/f = "

+ (a + b * d - e / f));

Output

a+b/d = 20

a+b*d-e/f = 219

2. Be a Compiler:

The compiler in our systems uses a lex tool to match the greatest match when generating tokens. This creates a bit
of a problem if overlooked. For example, consider the statement a=b+++c; too many of the readers might seem to
create a compiler error. But this statement is absolutely correct as the token created by lex is a, =, b, ++, +, c.
Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly,
a=b+++++c; would generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an error as
there is no operand after the second unary operand.

public class operators {

public static void main(String[] args)

int a = 20, b = 10, c = 0;

// a=b+++c is compiled as

// b++ +c

// a=b+c then b=b+1

a = b++ + c;

System.out.println("Value of a(b+c), "

+ " b(b+1), c = " + a + ", " + b

+ ", " + c);

// a=b+++++c is compiled as

// b++ ++ +c

// which gives error.

// a=b+++++c;

// System.out.println(b+++++c);

}
UNIT 2: Building Blocks of the Language
Output

Value of a(b+c), b(b+1), c = 10, 11, 0

3. Using + over ():

When using the + operator inside system.out.println() make sure to do addition using parenthesis. If we write
something before doing addition, then string addition takes place, that is, associativity of addition is left to right, and
hence integers are added to a string first producing a string, and string objects concatenate when using +. Therefore
it can create unwanted results.

public class operators {

public static void main(String[] args)

int x = 5, y = 8;

// concatenates x and y as

// first x is added to "concatenation (x+y) = "

// producing "concatenation (x+y) = 5"

// and then 8 is further concatenated.

System.out.println("Concatenation (x+y)= " + x + y);

// addition of x and y

System.out.println("Addition (x+y) = " + (x + y));

Output

Concatenation (x+y)= 58

Addition (x+y) = 13

Advantages of Operators in Java

The advantages of using operators in Java are mentioned below:

1. Expressiveness: Operators in Java provide a concise and readable way to perform complex calculations and
logical operations.

2. Time-Saving: Operators in Java save time by reducing the amount of code required to perform certain tasks.

3. Improved Performance: Using operators can improve performance because they are often implemented at
the hardware level, making them faster than equivalent Java code.
UNIT 2: Building Blocks of the Language
Disadvantages of Operators in Java

The disadvantages of Operators in Java are mentioned below:

1. Operator Precedence: Operators in Java have a defined precedence, which can lead to unexpected results if
not used properly.

2. Type Coercion: Java performs implicit type conversions when using operators, which can lead to unexpected
results or errors if not used properly.

3. Overloading: Java allows for operator overloading, which can lead to confusion and errors if different classes
define the same operator with different behavior.

Decision Making in Java (if, if-else, switch, break, continue, jump)


Decision Making in programming is similar to decision-making in real life. In programming also 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 a 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.

Java’s Selection statements:

 if

 if-else

 nested-if

 if-else-if

 switch-case

 jump – break, continue, return

1. 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 statements is executed
otherwise not.

Syntax:

if(condition)

// Statements to execute if

// condition is true

Here, the 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. For example,

if(condition) //Assume condition is true

statement1; //part of if block

statement2; // separate from if block


UNIT 2: Building Blocks of the Language

// Here if the condition is true

// if block will consider statement1 as its part and executes in only true condition

// statement2 will be separate from the if block so it will always executes whether the condition is true or false.

Example:

 Java

// Java program to illustrate If statement without curly block

import java.util.*;

class IfDemo {

public static void main(String args[])

int i = 10;

if (i < 15)

System.out.println("Inside If block"); // part of if block(immediate one statement after if condition)

System.out.println("10 is less than 15"); //always executes as it is outside of if block


UNIT 2: Building Blocks of the Language
// This statement will be executed

// as if considers one statement by default again below statement is outside of if block

System.out.println("I am Not in if");

Output

Inside If block

10 is less than 15

I am Not in if

Time Complexity: O(1)


Auxiliary Space : O(1)

2. 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 the if statement to execute a block of code when the condition is
false.

Syntax:

if (condition)

// Executes this block if

// condition is true

else

// Executes this block if

// condition is false

}
UNIT 2: Building Blocks of the Language

Example:

 Java

// Java program to illustrate if-else statement

import java.util.*;

class IfElseDemo {

public static void main(String args[])

int i = 10;

if (i < 15)

System.out.println("i is smaller than 15");

else

System.out.println("i is greater than 15");

}
UNIT 2: Building Blocks of the Language
Output

i is smaller than 15

Time Complexity: O(1)


Auxiliary Space : O(1)

3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if
statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.

Syntax:

if (condition1)

// Executes when condition1 is true

if (condition2)

// Executes when condition2 is true

}
UNIT 2: Building Blocks of the Language
Example:

// Java program to illustrate nested-if statement

import java.util.*;

class NestedIfDemo {

public static void main(String args[])

int i = 10;

if (i == 10 || i<15) {

// First if statement

if (i < 15)

System.out.println("i is smaller than 15");

// Nested - if statement

// Will only be executed if statement above

// it is true

if (i < 12)

System.out.println(

"i is smaller than 12 too");

} else{

System.out.println("i is greater than 15");

Output

i is smaller than 15

i is smaller than 12 too

Time Complexity: O(1)


Auxiliary Space: O(1)
UNIT 2: Building Blocks of the Language
4. 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. There can be as many as ‘else if’ blocks associated with one ‘if’ block but only one ‘else’ block is allowed
with one ‘if’ block.

if (condition)

statement;

else if (condition)

statement;

else

statement;
UNIT 2: Building Blocks of the Language
Example:

// Java program to illustrate if-else-if ladder

import java.util.*;

class ifelseifDemo {

public static void main(String args[])

int i = 20;

if (i == 10)

System.out.println("i is 10");

else if (i == 15)

System.out.println("i is 15");

else if (i == 20)

System.out.println("i is 20");

else

System.out.println("i is not present");

Output

i is 20

Time Complexity: O(1)


Auxiliary Space: O(1)

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

Syntax:

switch (expression)

case value1:

statement1;

break;

case value2:

statement2;
UNIT 2: Building Blocks of the Language
break;

case valueN:

statementN;

break;

default:

statementDefault;

/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static void main (String[] args) {

int num=20;

switch(num){

case 5 : System.out.println("It is 5");

break;

case 10 : System.out.println("It is 10");

break;

case 15 : System.out.println("It is 15");

break;

case 20 : System.out.println("It is 20");

break;

default: System.out.println("Not present");

}
UNIT 2: Building Blocks of the Language
Output

It is 20

Time Complexity: O(1)

Space Complexity: O(1)

 The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7,
the expression can also be of type String.

 Duplicate 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 statements are necessary without the break keyword, statements in switch blocks fall through.

 If the break keyword is omitted, execution will continue to the next case.

6. jump: Java supports three jump statements: break, continue and return. These three statements transfer control
to another part of the program.

 Break: In Java, a break is majorly used for:

 Terminate a sequence in a switch statement (discussed above).

 To exit a loop.

 Used as a “civilized” form of goto.

 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. This
is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such
an action.
UNIT 2: Building Blocks of the Language
Example:

// Java program to illustrate using

// continue in an if statement

import java.util.*;

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

Output

13579

Time Complexity: O(1)


Auxiliary Space: O(1)

 Return: The return statement is used to explicitly return from a method. That is, it causes program control to
transfer back to the caller of the method.
UNIT 2: Building Blocks of the Language

Example:

// Java program to illustrate using return

import java.util.*;

public 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.");

Output

Before the return.

Time Complexity: O(1)


Auxiliary Space: O(1)
UNIT 3: Object Oriented Programming Concepts
Classes and Objects in Java

In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent
real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For
example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.

In this article, we will discuss Java objects and classes and how to implement them in our program.

Java Classes

A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes.
It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a
particular student named Ravi is an object.

Properties of Java Classes

1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.

2. Class does not occupy memory.

3. Class is a group of variables of different data types and a group of methods.

4. A Class in Java can contain:

 Data member

 Method

 Constructor

 Nested Class

 Interface

Class Declaration in Java

access_modifier class <class_name>

data member;

method;

constructor;

nested class;

interface;

}
UNIT 3: Object Oriented Programming Concepts
Example of Java Class

// Java Program for class example

class Student {

// data member (also instance variable)

int id;

// data member (also instance variable)

String name;

public static void main(String args[])

// creating an object of

// Student

Student s1 = new Student();

System.out.println(s1.id);

System.out.println(s1.name);

Output 1

null

Output 2

GeeksForGeeks

Output 3

GeeksForGeeks

Components of Java Classes

In general, class declarations can include these components, in order:

1. Modifiers: A class can be public or has default access (Refer this for details).

2. Class keyword: class keyword is used to create a class.

3. Class name: The name should begin with an initial letter (capitalized by convention).

4. 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.
UNIT 3: Object Oriented Programming Concepts
5. 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.

6. Body: The class body is surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provide the state of the class and its
objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real-time applications such as nested classes, anonymous classes,
and lambda expressions.

Java Objects

An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. Objects are the
instances of a class that are created to use the attributes and methods of a class. 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 the 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.

Example of an object: dog

Java Objects

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

Note: When we create an object which is a non primitive data type, it’s always allocated on the heap memory.

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.

Example:

Java Object Declaration

As we declare variables like (type name;). This notifies the compiler that we will use the 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 variables , the type must be strictly a concrete class name. In general, we can’t create objects of an
abstract class or an interface.

Dog tuffy;

If we declare a 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.

Initializing a Java 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.
UNIT 3: Object Oriented Programming Concepts
Example:

// Class Declaration

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;

// method 1

public String getName() { return name; }

// method 2

public String getBreed() { return breed; }

// method 3

public int getAge() { return age; }

// method 4

public String getColor() { return color; }


UNIT 3: Object Oriented Programming Concepts
@Override 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());

Output

Hi my name is tuffy.

My breed,age and color are papillon,5,white

Initialize by using method/function:

public class GFG {

// sw=software

static String sw_name;

static float sw_price;

static void set(String n, float p)

sw_name = n;

sw_price = p;

static void get()


UNIT 3: Object Oriented Programming Concepts
{

System.out.println("Software name is: " + sw_name);

System.out.println("Software price is: "

+ sw_price);

public static void main(String args[])

GFG.set("Visual studio", 0.0f);

GFG.get();

Output

Software name is: Visual studio

Software price is: 0.0

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, and “white” as values for those arguments:

Dog tuffy = new Dog("tuffy","papillon",5, "white");

The result of executing this statement can be illustrated as :

Memory Allocation of Java Objects

Note: 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 contains only one statement i.e super();), or the Object class
constructor if the class has no other parent (as the Object class is the parent of all classes either directly or
indirectly).

Ways to Create an Object of a Class

There are four ways to create objects in Java. Strictly speaking, there is only one way(by using a new keyword), and
the rest internally use a new keyword.

1. Using new keyword

It is the most common and general way to create an object in Java.

Example:

// creating object of class Test

Test t = new Test();


UNIT 3: Object Oriented Programming Concepts
2. 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 a fully qualified name for a
class. On calling the new Instance() method on this Class object returns a 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();

3. Using clone() method

clone() method is present in the 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();

4. Deserialization

De-serialization is a technique of reading an object from the saved state in a file. Refer to Serialization/De-
Serialization in Java

FileInputStream file = new FileInputStream(filename);

ObjectInputStream in = new ObjectInputStream(file);

Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

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, the wastage of memory is less. The objects that are not referenced anymore will be destroyed by the Garbage
Collector of Java.

Example:

Test test = new Test();

test = new Test();

In the inheritance system, we use a parent class reference variable to store a sub-class object. In this case, we can
switch into different subclass objects using the same referenced variable.

Example:

class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

public class Test

{
UNIT 3: Object Oriented Programming Concepts
// using Dog object

Animal obj = new Dog();

// using Cat object

obj = new Cat();

Anonymous Objects in Java

Anonymous objects are objects that are instantiated but are not stored in a reference variable.

 They are used for immediate method calls.

 They will be destroyed after method calling.

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

 In the example below, when a key button(referred to by the btn) is pressed, we are simply creating an
anonymous object of EventHandler class for just calling the handle method.

btn.setOnAction(new EventHandler()

public void handle(ActionEvent event)

System.out.println("Hello World!");

});
UNIT 3: Object Oriented Programming Concepts
Difference between Java Class and Objects

The differences between class and object in Java are as follows:

Class Object

Class is the blueprint of an object. It is used to create


An object is an instance of the class.
objects.

No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.

An object is a real-world entity such as a book, car,


A class is a group of similar objects.
etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.

static Keyword in Java

The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the
same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and
nested classes. The static keyword belongs to the class than an instance of the class. The static keyword is used for a
constant variable or a method that is the same for every instance of a class.

The static keyword is a non-access modifier in Java that is applicable for the following:

1. Blocks

2. Variables

3. Methods

4. Classes

Note: To create a static member(block, variable, method, nested class), precede its declaration with the
keyword static.

Characteristics of static keyword:

Here are some characteristics of the static keyword in Java:

 Shared memory allocation: Static variables and methods are allocated memory space only once during the
execution of the program. This memory space is shared among all instances of the class, which makes static
members useful for maintaining global state or shared functionality.
UNIT 3: Object Oriented Programming Concepts
 Accessible without object instantiation: Static members can be accessed without the need to create an
instance of the class. This makes them useful for providing utility functions and constants that can be used
across the entire program.

 Associated with class, not objects: Static members are associated with the class, not with individual objects.
This means that changes to a static member are reflected in all instances of the class, and that you can
access static members using the class name rather than an object reference.

 Cannot access non-static members: Static methods and variables cannot access non-static members of a
class, as they are not associated with any particular instance of the class.

 Can be overloaded, but not overridden: Static methods can be overloaded, which means that you can
define multiple methods with the same name but different parameters. However, they cannot be
overridden, as they are associated with the class rather than with a particular instance of the class.

When a member is declared static, it can be accessed before any objects of its class are created, and without
reference to any object. For example, in the below java program, we are accessing static method m1() without
creating any object of the Test class.

 Java

// Java program to demonstrate that a static member

// can be accessed before instantiating a class

class Test

// static method

static void m1()

System.out.println("from m1");

public static void main(String[] args)

// calling m1 without creating

// any object of class Test

m1();

Output

from m1
UNIT 3: Object Oriented Programming Concepts
Static blocks

If you need to do the computation in order to initialize your static variables, you can declare a static block that gets
executed exactly once, when the class is first loaded.

Consider the following java program demonstrating the use of static blocks.

// Java program to demonstrate use of static blocks

class Test

// static variable

static int a = 10;

static int b;

// static block

static {

System.out.println("Static block initialized.");

b = a * 4;

public static void main(String[] args)

System.out.println("from main");

System.out.println("Value of a : "+a);

System.out.println("Value of b : "+b);

Output

Static block initialized.

from main

Value of a : 10

Value of b : 40

For a detailed article on static blocks, see static blocks


UNIT 3: Object Oriented Programming Concepts
Static variables

When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the
class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Important points for static variables:

 We can create static variables at the class level only. See here

 static block and static variables are executed in the order they are present in a program.

Below is the Java program to demonstrate that static block and static variables are executed in the order they are
present in a program.

// Java program to demonstrate execution

// of static blocks and variables

class Test

// static variable

static int a = m1();

// static block

static {

System.out.println("Inside static block");

// static method

static int m1() {

System.out.println("from m1");

return 20;

// static method(main !!)

public static void main(String[] args) {

System.out.println("Value of a : "+a);

System.out.println("from main");

}
UNIT 3: Object Oriented Programming Concepts
Output

from m1

Inside static block

Value of a : 20

from main

Static methods

When a method is declared with the static keyword, it is known as the static method. The most common example of
a static method is the main( ) method. As discussed above, Any static member can be accessed before any objects of
its class are created, and without reference to any object. Methods declared as static have several restrictions:

 They can only directly call other static methods.

 They can only directly access static data.

 They cannot refer to this or super in any way.

Below is the java program to demonstrate restrictions on static methods.

 Java

// Java program to demonstrate restriction on static methods

class Test

// static variable

static int a = 10;

// instance variable

int b = 20;

// static method

static void m1()

a = 20;

System.out.println("from m1");

// Cannot make a static reference to the non-static field b

b = 10; // compilation error


UNIT 3: Object Oriented Programming Concepts
// Cannot make a static reference to the

// non-static method m2() from the type Test

m2(); // compilation error

// Cannot use super in a static context

System.out.println(super.a); // compiler error

// instance method

void m2()

System.out.println("from m2");

public static void main(String[] args)

// main method

Output:

prog.java:18: error: non-static variable b cannot be referenced from a static context

b = 10; // compilation error

prog.java:22: error: non-static method m2() cannot be referenced from a static context

m2(); // compilation error

prog.java:25: error: non-static variable super cannot be referenced from a static context

System.out.println(super.a); // compiler error

prog.java:25: error: cannot find symbol


UNIT 3: Object Oriented Programming Concepts
System.out.println(super.a); // compiler error

symbol: variable a

4 errors

When to use static variables and methods?

Use the static variable for the property that is common to all objects. For example, in class Student, all students
share the same college name. Use static methods for changing static variables.

Consider the following java program, that illustrates the use of static keywords with variables and methods.

 Java

// A java program to demonstrate use of

// static keyword with methods and variables

// Student class

class Student {

String name;

int rollNo;

// static variable

static String cllgName;

// static counter to set unique roll no

static int counter = 0;

public Student(String name)

this.name = name;

this.rollNo = setRollNo();

// getting unique rollNo

// through static variable(counter)


UNIT 3: Object Oriented Programming Concepts
static int setRollNo()

counter++;

return counter;

// static method

static void setCllg(String name) { cllgName = name; }

// instance method

void getStudentInfo()

System.out.println("name : " + this.name);

System.out.println("rollNo : " + this.rollNo);

// accessing static variable

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

// Driver class

public class StaticDemo {

public static void main(String[] args)

// calling static method

// without instantiating Student class

Student.setCllg("XYZ");

Student s1 = new Student("Alice");

Student s2 = new Student("Bob");

s1.getStudentInfo();
UNIT 3: Object Oriented Programming Concepts
s2.getStudentInfo();

Output

name : Alice

rollNo : 1

cllgName : XYZ

name : Bob

rollNo : 2

cllgName : XYZ

Static Classes

A class can be made static only if it is a nested class. We cannot declare a top-level class with a static modifier but
can declare nested classes as static. Such types of classes are called Nested static classes. Nested static class doesn’t
need a reference of Outer class. In this case, a static class cannot access non-static members of the Outer class.
UNIT 3: Object Oriented Programming Concepts
Implementation:

// A java program to demonstrate use

// of static keyword with Classes

import java.io.*;

public class GFG {

private static String str = "GeeksforGeeks";

// Static class

static class MyNestedClass {

// non-static method

public void disp(){

System.out.println(str);

public static void main(String args[])

GFG.MyNestedClass obj

= new GFG.MyNestedClass();

obj.disp();

Output

GeeksforGeeks
UNIT 3: Object Oriented Programming Concepts
Here’s an example Java program that demonstrates the use of the static keyword:

public class ExampleClass {

public static int count = 0;

public int id;

public ExampleClass() {

count++;

id = count;

public static void printCount() {

System.out.println("Number of instances: " + count);

public void printId() {

System.out.println("Instance ID: " + id);

public static void main(String[] args) {

ExampleClass e1 = new ExampleClass();

ExampleClass e2 = new ExampleClass();

ExampleClass e3 = new ExampleClass();

e1.printId();

e2.printId();

e3.printId();

ExampleClass.printCount();

Output

Instance ID: 1
UNIT 3: Object Oriented Programming Concepts
Instance ID: 2

Instance ID: 3

Number of instances: 3

Advantages:

 Memory efficiency: Static members are allocated memory only once during the execution of the program,
which can result in significant memory savings for large programs.

 Improved performance: Because static members are associated with the class rather than with individual
instances, they can be accessed more quickly and efficiently than non-static members.

 Global accessibility: Static members can be accessed from anywhere in the program, regardless of whether
an instance of the class has been created.

 Encapsulation of utility methods: Static methods can be used to encapsulate utility functions that don’t
require any state information from an object. This can improve code organization and make it easier to
reuse utility functions across multiple classes.

 Constants: Static final variables can be used to define constants that are shared across the entire program.

 Class-level functionality: Static methods can be used to define class-level functionality that doesn’t require
any state information from an object, such as factory methods or helper functions.

Method Overloading in Java

In Java, Method Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters, or a mixture of both.

Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or Early binding. In
Method overloading compared to the parent argument, the child argument will get the highest priority.

Example of Method Overloading

 Java

// Java program to demonstrate working of method

// overloading in Java

public class Sum {

// Overloaded sum(). This sum takes two int parameters

public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters

public int sum(int x, int y, int z)

return (x + y + z);

}
UNIT 3: Object Oriented Programming Concepts

// Overloaded sum(). This sum takes two double

// parameters

public double sum(double x, double y)

return (x + y);

// Driver code

public static void main(String args[])

Sum s = new Sum();

System.out.println(s.sum(10, 20));

System.out.println(s.sum(10, 20, 30));

System.out.println(s.sum(10.5, 20.5));

Output

30

60

31.0

Different Ways of Method Overloading in Java

 Changing the Number of Parameters.

 Changing Data Types of the Arguments.

 Changing the Order of the Parameters of Methods

1. Changing the Number of Parameters

Method overloading can be achieved by changing the number of parameters while passing to different methods.
UNIT 3: Object Oriented Programming Concepts
Below is the implementation of the above method:

// Java Program to Illustrate Method Overloading

// By Changing the Number of Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Product {

// Method 1

// Multiplying two integer values

public int multiply(int a, int b)

int prod = a * b;

return prod;

// Method 2

// Multiplying three integer values

public int multiply(int a, int b, int c)

int prod = a * b * c;

return prod;

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String[] args)


UNIT 3: Object Oriented Programming Concepts
{

// Creating object of above class inside main()

// method

Product ob = new Product();

// Calling method to Multiply 2 numbers

int prod1 = ob.multiply(1, 2);

// Printing Product of 2 numbers

System.out.println(

"Product of the two integer value :" + prod1);

// Calling method to multiply 3 numbers

int prod2 = ob.multiply(1, 2, 3);

// Printing product of 3 numbers

System.out.println(

"Product of the three integer value :" + prod2);

Output

Product of the two integer value :2

Product of the three integer value :6

2. Changing Data Types of the Arguments

In many cases, methods can be considered Overloaded if they have the same name but have different parameter
types, methods are considered to be overloaded.
UNIT 3: Object Oriented Programming Concepts
Below is the implementation of the above method:

// Java Program to Illustrate Method Overloading

// By Changing Data Types of the Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Product {

// Multiplying three integer values

public int Prod(int a, int b, int c)

int prod1 = a * b * c;

return prod1;

// Multiplying three double values.

public double Prod(double a, double b, double c)

double prod2 = a * b * c;

return prod2;

class GFG {

public static void main(String[] args)

Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);

System.out.println(
UNIT 3: Object Oriented Programming Concepts
"Product of the three integer value :" + prod1);

double prod2 = obj.Prod(1.0, 2.0, 3.0);

System.out.println(

"Product of the three double value :" + prod2);

Output

Product of the three integer value :6

Product of the three double value :6.0

3. Changing the Order of the Parameters of Methods

Method overloading can also be implemented by rearranging the parameters of two or more overloaded methods.
For example, if the parameters of method 1 are (String name, int roll_no) and the other method is (int roll_no, String
name) but both have the same name, then these 2 methods are considered to be overloaded with different
sequences of parameters.

Below is the implementation of the above method:

// Java Program to Illustrate Method Overloading

// By changing the Order of the Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Student {

// Method 1

public void StudentId(String name, int roll_no)

System.out.println("Name :" + name + " "

+ "Roll-No :" + roll_no);

}
UNIT 3: Object Oriented Programming Concepts
// Method 2

public void StudentId(int roll_no, String name)

// Again printing name and id of person

System.out.println("Roll-No :" + roll_no + " "

+ "Name :" + name);

// Class 2

// Main class

class GFG {

// Main function

public static void main(String[] args)

// Creating object of above class

Student obj = new Student();

// Passing name and id

// Note: Reversing order

obj.StudentId("Spyd3r", 1);

obj.StudentId(2, "Kamlesh");

Output

Name :Spyd3r Roll-No :1

Roll-No :2 Name :Kamlesh

What if the exact prototype does not match with arguments?

Priority-wise, the compiler takes these steps:

 Type Conversion but to a higher type(in terms of range) in the same family.

 Type conversion to the next higher family(suppose if there is no long data type available for an int data type,
then it will search for the float data type).
UNIT 3: Object Oriented Programming Concepts

Let’s take an example to clarify the concept:

 Java

// Demo Class

class Demo {

public void show(int x)

System.out.println("In int" + x);

public void show(String s)

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

public void show(byte b)

System.out.println("In byte" + b);

class UseDemo {
UNIT 3: Object Oriented Programming Concepts
public static void main(String[] args)

byte a = 25;

Demo obj = new Demo();

// it will go to

// byte argument

obj.show(a);

// String

obj.show("hello");

// Int

obj.show(250);

// Since char is

// not available, so the datatype

// higher than char in terms of

// range is int.

obj.show('A');

// String

obj.show("A");

// since float datatype

// is not available and so it's higher

// datatype, so at this step their

// will be an error.

obj.show(7.5);

}
UNIT 3: Object Oriented Programming Concepts
Output

./UseDemo.java:46: error: no suitable method found for show(double)

obj.show(7.5);

method Demo.show(int) is not applicable

(argument mismatch; possible lossy conversion from double to int)

method Demo.show(String) is not applicable

(argument mismatch; double cannot be converted to String)

method Demo.show(byte) is not applicable

(argument mismatch; possible lossy conversion from double to byte)

1 error

Advantages of Method Overloading

 Method overloading improves the Readability and reusability of the program.

 Method overloading reduces the complexity of the program.

 Using method overloading, programmers can perform a task efficiently and effectively.

 Using method overloading, it is possible to access methods performing related functions with slightly
different arguments and types.

 Objects of a class can also be initialized in different ways using the constructors.

final Keyword in Java

final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a variable, a
method, or a class. The following are different contexts where final is used.
UNIT 3: Object Oriented Programming Concepts
Characteristics of final keyword in java:

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended. Here
are some of its characteristics:

 Final variables: When a variable is declared as final, its value cannot be changed once it has been initialized.
This is useful for declaring constants or other values that should not be modified.

 Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is useful for
methods that are part of a class’s public API and should not be modified by subclasses.

 Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for classes
that are intended to be used as is and should not be modified or extended.

 Initialization: Final variables must be initialized either at the time of declaration or in the constructor of the
class. This ensures that the value of the variable is set and cannot be changed.

 Performance: The use of final can sometimes improve performance, as the compiler can optimize the code
more effectively when it knows that a variable or method cannot be changed.

 Security: final can help improve security by preventing malicious code from modifying sensitive data or
behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of a program
cannot be modified or extended. By declaring variables, methods, and classes as final, developers can write more
secure, robust, and maintainable code.

Final Variables

When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. This also
means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot
be re-bound to reference another object, but the internal state of the object pointed by that reference variable can
be changed i.e. you can add or remove elements from the final array or final collection. It is good practice to
represent final variables in all uppercase, using underscore to separate words.

Illustration:

final int THRESHOLD = 5;

// Final variable

final int THRESHOLD;

// Blank final variable

static final double PI = 3.141592653589793;

// Final static variable PI

static final double PI;

// Blank final static variable

Initializing a final Variable

We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only
be initialized once, either via an initializer or an assignment statement. There are three ways to initialize a final
variable:
UNIT 3: Object Oriented Programming Concepts
1. You can initialize a final variable when it is declared. This approach is the most common. A final variable is
called a blank final variable if it is not initialized while declaration. Below are the two ways to initialize a
blank final variable.

2. A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you
have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-
time error will be thrown.

3. A blank final static variable can be initialized inside a static block.

Let us see these two different ways of initializing a final variable:

// Java Program to demonstrate Different

// Ways of Initializing a final Variable

// Main class

class GFG {

// a final variable

// direct initialize

final int THRESHOLD = 5;

// a blank final variable

final int CAPACITY;

// another blank final variable

final int MINIMUM;

// a final static variable PI

// direct initialize

static final double PI = 3.141592653589793;

// a blank final static variable

static final double EULERCONSTANT;

// instance initializer block for

// initializing CAPACITY
UNIT 3: Object Oriented Programming Concepts
{

CAPACITY = 25;

// static initializer block for

// initializing EULERCONSTANT

static{

EULERCONSTANT = 2.3;

// constructor for initializing MINIMUM

// Note that if there are more than one

// constructor, you must initialize MINIMUM

// in them also

public GFG()

MINIMUM = -1;

Geeks there was no main method in the above code as it was simply for illustration purposes to get a better
understanding in order to draw conclusions:

Observation 1: When to use a final variable?

The only difference between a normal variable and a final variable is that we can re-assign the value to a normal
variable but we cannot change the value of a final variable once assigned. Hence final variables must be used only
for the values that we want to remain constant throughout the execution of the program.

Observation 2: Reference final variable?

When a final variable is a reference to an object, then this final variable is called the reference final variable. For
example, a final StringBuffer variable looks defined below as follows:

final StringBuffer sb;

As we all know that a final variable cannot be re-assign. But in the case of a reference final variable, the internal
state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This
property of final is called non-transitivity. To understand what is meant by the internal state of the object as shown
in the below example as follows:
UNIT 3: Object Oriented Programming Concepts
Example 1:

// Java Program to demonstrate

// Reference of Final Variable

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating an object of StringBuilder class

// Final reference variable

final StringBuilder sb = new StringBuilder("Geeks");

// Printing the element in StringBuilder object

System.out.println(sb);

// changing internal state of object reference by

// final reference variable sb

sb.append("ForGeeks");

// Again printing the element in StringBuilder

// object after appending above element in it

System.out.println(sb);

Output

Geeks

GeeksForGeeks

The non-transitivity property also applies to arrays, because arrays are objects in Java. Arrays with the final
keyword are also called final arrays.
UNIT 3: Object Oriented Programming Concepts
Example 2:

// Java Program to Demonstrate Re-assigning

// Final Variable will throw Compile-time Error

// Main class

class GFG {

// Declaring and customly initializing

// static final variable

static final int CAPACITY = 4;

// Main driver method

public static void main(String args[])

// Re-assigning final variable

// will throw compile-time error

CAPACITY = 5;

Output:

Remember: When a final variable is created inside a method/constructor/block, it is called local final variable, and it
must initialize once where it is created. See below program for local final variable.
UNIT 3: Object Oriented Programming Concepts
Example:

// Java program to demonstrate

// local final variable

// Main class

class GFG {

// Main driver method

public static void main(String args[])

// Declaring local final variable

final int i;

// Now initializing it with integer value

i = 20;

// Printing the value on console

System.out.println(i);

Output

20

Remember the below key points as perceived before moving forward as listed below as follows:

1. Note the difference between C++ const variables and Java final variables. const variables in C++ must be
assigned a value when declared. For final variables in Java, it is not necessary as we see in the above
examples. A final variable can be assigned value later, but only once.

2. final with foreach loop: final with for-each statement is a legal statement.
UNIT 3: Object Oriented Programming Concepts
Example:

// Java Program to demonstrate Final

// with for-each Statement

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Declaring and initializing

// custom integer array

int arr[] = { 1, 2, 3 };

// final with for-each statement

// legal statement

for (final int i : arr)

System.out.print(i + " ");

Output

123

Output explanation: Since the “i” variable goes out of scope with each iteration of the loop, it is actually re-
declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables.
UNIT 3: Object Oriented Programming Concepts
Example:

public class Example {

public static void main(String[] args) {

final int VALUE = 10; // declaring a final variable

System.out.println("The value is: " + VALUE);

// VALUE = 20; // uncommenting this line will cause a compiler error

// System.out.println("The new value is: " + VALUE);

final String MESSAGE = "Hello, world!"; // declaring a final variable

System.out.println(MESSAGE);

MyClass myObj = new MyClass();

myObj.printMessage();

myObj.printFinalMessage();

// MyOtherClass extends MyClass {} // uncommenting this line will cause a compiler error

class MyClass {

final String message = "Hello!"; // declaring a final instance variable

void printMessage() {

System.out.println(message);

void printFinalMessage() {

final String finalMessage = "Hello, final!";

System.out.println(finalMessage);

}
UNIT 3: Object Oriented Programming Concepts

final class MyOtherClass { // declaring a final class

// ...

Output

The value is: 10

Hello, world!

Hello!

Hello, final!

Final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited).

There are two uses of a final class:

Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper
Classes like Integer, Float, etc. are final classes. We can not extend them.

final class A

// methods and fields

// The following class is illegal

class B extends A

// COMPILE-ERROR! Can't subclass A

Usage 2: The other use of final with classes is to create an immutable class like the predefined String class. One can
not make a class immutable without making it final.

Final Methods

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden.
The Object class does this—a number of its methods are final. We must declare methods with the final keyword for
which we are required to follow the same implementation throughout all the derived classes.

Illustration: Final keyword with a method

class A

final void m1()

{
UNIT 3: Object Oriented Programming Concepts
System.out.println("This is a final method.");

class B extends A

void m1()

// Compile-error! We can not override

System.out.println("Illegal!");

Advantages:

The final keyword in Java provides several advantages, including:

 Ensuring immutability: When a variable or reference is marked as final, its value cannot be changed once it
is assigned. This helps ensure that data is immutable and cannot be accidentally or maliciously modified.

 Improving performance: The use of final can sometimes help improve performance, as the Java Virtual
Machine (JVM) can optimize code more effectively when it knows that certain values or references cannot
be changed.

 Making code easier to understand: By declaring variables, methods, or classes as final, developers can make
their code easier to understand and reason about. When a value or reference is marked as final, it is clear
that it will not change, which can simplify code analysis and debugging.

 Promoting code reuse: By declaring methods as final, developers can prevent subclasses from overriding
them. This can help promote code reuse and reduce duplication, as subclasses must use the parent class’s
implementation of the method.

 Enhancing security: The use of final can help enhance security by preventing malicious code from modifying
sensitive data or behavior.

Constructor Overloading in Java

Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called
based on the parameters specified when a new is executed.

When do we need Constructor Overloading?

Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading.

For example, the Thread class has 8 types of constructors. If we do not want to specify anything about a thread then
we can simply use the default constructor of the Thread class, however, if we need to specify the thread name, then
we may call the parameterized constructor of the Thread class with a String args like this:

Thread t= new Thread (" MyThread ");

Let us take an example to understand the need of constructor overloading. Consider the following implementation
of a class Box with only one constructor taking three arguments.
UNIT 3: Object Oriented Programming Concepts
// An example class to understand need of

// constructor overloading.

class Box

double width, height,depth;

// constructor used when all dimensions

// specified

Box(double w, double h, double d)

width = w;

height = h;

depth = d;

// compute and return volume

double volume()

return width * height * depth;

As we can see that the Box() constructor requires three parameters. This means that all declarations of Box objects
must pass three arguments to the Box() constructor.

For example, the following statement is currently invalid:

Box ob = new Box();

Since Box() requires three arguments, it’s an error to call it without them. Suppose we simply wanted a box object
without initial dimension, or want to initialize a cube by specifying only one value that would be used for all three
dimensions. From the above implementation of the Box class, these options are not available to us. These types of
problems of different ways of initializing an object can be solved by constructor overloading.

Example of Constructor Overloading


UNIT 3: Object Oriented Programming Concepts
Below is the improved version of class Box with constructor overloading.

// Java program to illustrate

// Constructor Overloading

class Box {

double width, height, depth;

// constructor used when all dimensions

// specified

Box(double w, double h, double d)

width = w;

height = h;

depth = d;

// constructor used when no dimensions

// specified

Box() { width = height = depth = 0; }

// constructor used when cube is created

Box(double len) { width = height = depth = len; }

// compute and return volume

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

// Driver code

public class Test {

public static void main(String args[])

// create boxes using the various

// constructors
UNIT 3: Object Oriented Programming Concepts
Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

// get volume of cube

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

Output

Volume of mybox1 is 3000.0

Volume of mybox2 is 0.0

Volume of mycube is 343.0

Using this() in Constructor Overloading

this() reference can be used during constructor overloading to call the default constructor implicitly from the
parameterized constructor.
UNIT 3: Object Oriented Programming Concepts
Below is the implementation of the above method:

// Java program to illustrate role of this() in

// Constructor Overloading

public class Box {

double width, height, depth;

int boxNo;

// constructor used when all dimensions and

// boxNo specified

Box(double w, double h, double d, int num)

width = w;

height = h;

depth = d;

boxNo = num;

// constructor used when no dimensions specified

Box()

// an empty box

width = height = depth = 0;

// constructor used when only boxNo specified

Box(int num)

// this() is used for calling the default

// constructor from parameterized constructor

this();

boxNo = num;
UNIT 3: Object Oriented Programming Concepts
}

public static void main(String[] args)

// create box using only boxNo

Box box1 = new Box(1);

// getting initial width of box1

System.out.println(box1.width);

Output

0.0

As we can see in the above program 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 the dimension of Box with 0.

For example, the following fragment is invalid and throws compile time error.

Box(int num)

boxNo = num;

/* Constructor call must be the first

statement in a constructor */

this(); /*ERROR*/

Important points to be taken care of while doing Constructor Overloading

 Constructor calling must be the first statement of the constructor in Java.

 If we have defined any parameterized constructor, then the compiler will not create a 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.


UNIT 4: Inheritance, Packages & Interfaces
Types of Inheritance in Java

Inheritance is the most powerful feature of object-oriented programming. It allows us to inherit the properties of
one class into another class. In this section, we will discuss types of inheritance in Java in-depth with real-life
examples. Also, we will create Java programs to implement the concept of different types of inheritance.

Inheritance

Inheritance is a mechanism of driving a new class from an existing class. The existing (old) class is known as base
class or super class or parent class. The new class is known as a derived class or sub class or child class. It allows us
to use the properties and behavior of one class (parent) in another class (child).

A class whose properties are inherited is known as parent class and a class that inherits the properties of the parent
class is known as child class. Thus, it establishes a relationship between parent and child class that is known as
parent-child or Is-a relationship.

Suppose, there are two classes named Father and Child and we want to inherit the properties of the Father class in
the Child class. We can achieve this by using the extends keyword.

Backward Skip 10sPlay VideoForward Skip 10s

1. //inherits the properties of the Father class

2. class Child extends Father

3. {

4. //functionality

5. }
UNIT 4: Inheritance, Packages & Interfaces
When we should use inheritance?

Inheritance provides the reusability of code especially when there is a large scale of code to reuse. It also establishes
the relationship between different classes that is known as a Is-a relationship. We can also use it if we want to
achieve method overriding.

Points to Remember

o Constructor cannot be inherited in Java.

o Private members do not get inherited in Java.

o Cyclic inheritance is not permitted in Java.

o Assign parent reference to child objects.

o Constructors get executed because of super() present in the constructor.

Types of Inheritance

Java supports the following four types of inheritance:

o Single Inheritance

o Multi-level Inheritance

o Hierarchical Inheritance

o Hybrid Inheritance

Note: Multiple inheritance is not supported in Java.

Let's discuss each with proper example.

Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a
single-parent class. Sometimes it is also known as simple inheritance.
UNIT 4: Inheritance, Packages & Interfaces

In the above figure, Employee is a parent class and Executive is a child class. The Executive class inherits all the
properties of the Employee class.

Let's implement the single inheritance mechanism in a Java program.

ADVERTISEMENT

Executive.java

1. class Employee

2. {

3. float salary=34534*12;

4. }

5. public class Executive extends Employee

6. {

7. float bonus=3000*6;

8. public static void main(String args[])

9. {

10. Executive obj=new Executive();

11. System.out.println("Total salary credited: "+obj.salary);

12. System.out.println("Bonus of six months: "+obj.bonus);

13. }

14. }

Output:

Total salary credited: 414408.0

Bonus of six months: 18000.0

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is called multi-level
inheritance. In simple words, we can say that a class that has more than one parent class is called multi-level
inheritance. Note that the classes must be at different levels. Hence, there exists a single base class and single
derived class but multiple intermediate base classes.
UNIT 4: Inheritance, Packages & Interfaces

In the above figure, the class Marks inherits the members or methods of the class Students. The class Sports inherits
the members of the class Marks. Therefore, the Student class is the parent class of the class Marks and the class
Marks is the parent of the class Sports. Hence, the class Sports implicitly inherits the properties of the Student along
with the class Marks.

Let's implement the multi-level inheritance mechanism in a Java program.

MultilevelInheritanceExample.java

1. //super class

2. class Student

3. {

4. int reg_no;

5. void getNo(int no)

6. {

7. reg_no=no;

8. }

9. void putNo()

10. {

11. System.out.println("registration number= "+reg_no);

12. }

13. }

14. //intermediate sub class

15. class Marks extends Student

16. {
UNIT 4: Inheritance, Packages & Interfaces
17. float marks;

18. void getMarks(float m)

19. {

20. marks=m;

21. }

22. void putMarks()

23. {

24. System.out.println("marks= "+marks);

25. }

26. }

27. //derived class

28. class Sports extends Marks

29. {

30. float score;

31. void getScore(float scr)

32. {

33. score=scr;

34. }

35. void putScore()

36. {

37. System.out.println("score= "+score);

38. }

39. }

40. public class MultilevelInheritanceExample

41. {

42. public static void main(String args[])

43. {

44. Sports ob=new Sports();

45. ob.getNo(0987);

46. ob.putNo();

47. ob.getMarks(78);

48. ob.putMarks();

49. ob.getScore(68.7);
UNIT 4: Inheritance, Packages & Interfaces
50. ob.putScore();

51. }

52. }

Output:

registration number= 0987

marks= 78.0

score= 68.7

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named Student.

Let's implement the hierarchical inheritance mechanism in a Java program.

ADVERTISEMENT

HierarchicalInheritanceExample.java

1. //parent class

2. class Student

3. {

4. public void methodStudent()

5. {

6. System.out.println("The method of the class Student invoked.");

7. }

8. }

9. class Science extends Student

10. {

11. public void methodScience()


UNIT 4: Inheritance, Packages & Interfaces
12. {

13. System.out.println("The method of the class Science invoked.");

14. }

15. }

16. class Commerce extends Student

17. {

18. public void methodCommerce()

19. {

20. System.out.println("The method of the class Commerce invoked.");

21. }

22. }

23. class Arts extends Student

24. {

25. public void methodArts()

26. {

27. System.out.println("The method of the class Arts invoked.");

28. }

29. }

30. public class HierarchicalInheritanceExample

31. {

32. public static void main(String args[])

33. {

34. Science sci = new Science();

35. Commerce comm = new Commerce();

36. Arts art = new Arts();

37. //all the sub classes can access the method of super class

38. sci.methodStudent();

39. comm.methodStudent();

40. art.methodStudent();

41. }

42. }

Output:

The method of the class Student invoked.


UNIT 4: Inheritance, Packages & Interfaces
The method of the class Student invoked.

The method of the class Student invoked.

Hybrid Inheritance

ADVERTISEMENT

ADVERTISEMENT

Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of inheritance.

In the above figure, GrandFather is a super class. The Father class inherits the properties of the GrandFather class.
Since Father and GrandFather represents single inheritance. Further, the Father class is inherited by the Son and
Daughter class. Thus, the Father becomes the parent class for Son and Daughter. These classes represent the
hierarchical inheritance. Combinedly, it denotes the hybrid inheritance.

Let's implement the hybrid inheritance mechanism in a Java program.

Daughter.java

1. //parent class

2. class GrandFather

3. {

4. public void show()

5. {

6. System.out.println("I am grandfather.");

7. }

8. }

9. //inherits GrandFather properties

10. class Father extends GrandFather

11. {
UNIT 4: Inheritance, Packages & Interfaces
12. public void show()

13. {

14. System.out.println("I am father.");

15. }

16. }

17. //inherits Father properties

18. class Son extends Father

19. {

20. public void show()

21. {

22. System.out.println("I am son.");

23. }

24. }

25. //inherits Father properties

26. public class Daughter extends Father

27. {

28. public void show()

29. {

30. System.out.println("I am a daughter.");

31. }

32. public static void main(String args[])

33. {

34. Daughter obj = new Daughter();

35. obj.show();

36. }

37. }

Output:

I am daughter.

Multiple Inheritance (not supported)

Java does not support multiple inheritances due to ambiguity. For example, consider the following Java program.
UNIT 4: Inheritance, Packages & Interfaces
Demo.java

1. class Wishes

2. {

3. void message()

4. {

5. System.out.println("Best of Luck!!");

6. }

7. }

8. class Birthday

9. {

10. void message()

11. {

12. System.out.println("Happy Birthday!!");

13. }

14. }

15. public class Demo extends Wishes, Birthday //considering a scenario

16. {

17. public static void main(String args[])

18. {

19. Demo obj=new Demo();

20. //can't decide which classes' message() method will be invoked

21. obj.message();

22. }

23. }

The above code gives error because the compiler cannot decide which message() method is to be invoked. Due to
this reason, Java does not support multiple inheritances at the class level but can be achieved through an interface.

Dynamic Method Dispatch or Runtime Polymorphism in Java

Prerequisite: Overriding in java, Inheritance

Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is
the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.

 When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is made at run time.

 At run-time, it depends on the type of the object being referred to (not the type of the reference variable)
that determines which version of an overridden method will be executed
UNIT 4: Inheritance, Packages & Interfaces
 A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this
fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects
are referred to through a superclass reference variable, different versions of the method are executed. Here is an
example that illustrates dynamic method dispatch:

// A Java program to illustrate Dynamic Method

// Dispatch using hierarchical inheritance

class A

void m1()

System.out.println("Inside A's m1 method");

class B extends A

// overriding m1()

void m1()

System.out.println("Inside B's m1 method");

}
UNIT 4: Inheritance, Packages & Interfaces
}

class C extends A

// overriding m1()

void m1()

System.out.println("Inside C's m1 method");

// Driver class

class Dispatch

public static void main(String args[])

// object of type A

A a = new A();

// object of type B

B b = new B();

// object of type C

C c = new C();

// obtain a reference of type A

A ref;

// ref refers to an A object

ref = a;

// calling A's version of m1()


UNIT 4: Inheritance, Packages & Interfaces
ref.m1();

// now ref refers to a B object

ref = b;

// calling B's version of m1()

ref.m1();

// now ref refers to a C object

ref = c;

// calling C's version of m1()

ref.m1();

Output:

Inside A's m1 method

Inside B's m1 method

Inside C's m1 method

Explanation :

The above program creates one superclass called A and it’s two subclasses B and C. These subclasses overrides m1( )
method.

1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.

2. A a = new A(); // object of type A

3. B b = new B(); // object of type B

4. C c = new C(); // object of type C


UNIT 4: Inheritance, Packages & Interfaces

5. Now a reference of type A, called ref, is also declared, initially it will point to null.

6. A ref; // obtain a reference of type A

7. Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one,
and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is
determined by the type of object being referred to at the time of the call.

8. ref = a; // r refers to an A object

9. ref.m1(); // calling A's version of m1()


UNIT 4: Inheritance, Packages & Interfaces

ref = b; // now r refers to a B object

ref.m1(); // calling B's version of m1()

ref = c; // now r refers to a C object

ref.m1(); // calling C's version of m1()


UNIT 4: Inheritance, Packages & Interfaces

Runtime Polymorphism with Data Members

In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be
achieved by data members. For example :

// Java program to illustrate the fact that

// runtime polymorphism cannot be achieved

// by data members

// class A

class A

int x = 10;

// class B

class B extends A

int x = 20;

// Driver class

public class Test


UNIT 4: Inheritance, Packages & Interfaces
{

public static void main(String args[])

A a = new B(); // object of type B

// Data member of class A will be accessed

System.out.println(a.x);

Output:

10

Explanation : In above program, both the class A(super class) and B(sub class) have a common variable ‘x’. Now we
make object of class B, referred by ‘a’ which is of type of class A. Since variables are not overridden, so the statement
“a.x” will always refer to data member of super class.

Advantages of Dynamic Method Dispatch

1. Dynamic method dispatch allow Java to support overriding of methods which is central for run-time
polymorphism.

2. It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to
define the specific implementation of some or all of those methods.

3. It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.

Static vs Dynamic binding

 Static binding is done during compile-time while dynamic binding is done during run-time.

 private, final and static methods and variables uses static binding and bonded by compiler while overridden
methods are bonded during runtime based upon type of runtime object

Packages In Java

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used
for:

 Preventing naming conflicts. For example there can be two classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee

 Making searching/locating and usage of classes, interfaces, enumerations and annotations easier

 Providing controlled access: protected and default have package level access control. A protected member is
accessible by classes in the same package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.

 Packages can be considered as data encapsulation (or data-hiding).

All we need to do is put related classes into packages. After that, we can simply write an import class from existing
packages and use it in our program. A package is a container of a group of related classes where some of the classes
UNIT 4: Inheritance, Packages & Interfaces
are accessible are exposed and others are kept for internal purpose.
We can reuse existing classes from the packages as many time as we need it in our program.

How packages work?

Package names and directory structure are closely related. For example if a package name is college.staff.cse, then
there are three directories, college, staff and cse such that cse is present in staff and staff is present inside college.
Also, the directory college is accessible through CLASSPATH variable, i.e., path of parent directory of college is
present in CLASSPATH. The idea is to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is college.tech.cse,
college.tech.ee, college.art.history, etc.

Adding a class to a Package : We can add more classes to a created package by using package name at the top of the
program and saving it in the package directory. We need a new java file to define a public class, otherwise we can
add the new class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the subpackages. These are not imported by default,
they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered
as different package for protected and default access specifiers.
Example :

import java.util.*;

util is a subpackage created inside java package.

Accessing classes inside a package

Consider following two statements :

// import the Vector class from util package.

import java.util.vector;

// import all the classes from util package

import java.util.*;

 First Statement is used to import Vector class from util package which is contained inside java.

 Second statement imports all the classes from util package.

// All the classes and interfaces of this package

// will be accessible but not subpackages.

import package.*;

// Only mentioned class of this package will be accessible.

import package.classname;

// Class name is generally used when two packages have the same

// class name. For example in below code both packages have


UNIT 4: Inheritance, Packages & Interfaces
// date class so using a fully qualified name to avoid conflict

import java.util.Date;

import my.package.Date;

// Java program to demonstrate accessing of members when

// corresponding classes are imported and not imported.

import java.util.Vector;

public class ImportDemo

public ImportDemo()

// java.util.Vector is imported, hence we are

// able to access directly in our code.

Vector newVector = new Vector();

// java.util.ArrayList is not imported, hence

// we were referring to it using the complete

// package.

java.util.ArrayList newList = new java.util.ArrayList();

public static void main(String arg[])

new ImportDemo();

Types of packages:
UNIT 4: Inheritance, Packages & Interfaces
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in
packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations).
This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for
Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus
etc).
6) java.net: Contain classes for supporting networking operations.

User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name should be same
as the name of the package). Then create the MyClass inside the directory with the first statement being
the package names.

// Name of the package must be same as the directory

// under which this file is saved

package myPackage;

public class MyClass

public void getNames(String s)

System.out.println(s);

Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */

import myPackage.MyClass;

public class PrintName

public static void main(String args[])

// Initializing the String variable

// with a value

String name = "GeeksforGeeks";


UNIT 4: Inheritance, Packages & Interfaces

// Creating an instance of class MyClass in

// the package.

MyClass obj = new MyClass();

obj.getNames(name);

Using Static Import

Static import is a feature introduced in Java programming language ( versions 5 and above ) that allows members (
fields and methods ) defined in a class as public static to be used in Java code without specifying the class in which
the field is defined.
Following program demonstrates static import :

// Note static keyword after import.

import static java.lang.System.*;

class StaticImportDemo

public static void main(String args[])

// We don't need to use 'System.out'

// as imported using static.

out.println("GeeksforGeeks");

Output:

GeeksforGeeks

Handling name conflicts

The only time we need to pay attention to packages is when we have a name conflict . For example both, java.util
and java.sql packages have a class named Date. So if we import both packages in program as follows:

import java.util.*;

import java.sql.*;

//And then use Date class, then we will get a compile-time error :
UNIT 4: Inheritance, Packages & Interfaces

Date today ; //ERROR-- java.util.Date or java.sql.Date?

The compiler will not be able to figure out which Date class do we want. This problem can be solved by using a
specific import statement:

import java.util.Date;

import java.sql.*;

If we need both Date classes then, we need to use a full package name every time we declare a new object of that
class.
For Example:

java.util.Date deadLine = new java.util.Date();

java.sql.Date today = new java.sql.Date();

Directory structure

The package name is closely associated with the directory structure used to store the classes. The classes (and other
entities) belonging to a specific package are stored together in the same directory. Furthermore, they are stored in a
sub-directory structure specified by its package name. For example, the class Circle of package
com.zzz.project1.subproject2 is stored as “$BASE_DIR\com\zzz\project1\subproject2\Circle.class”, where
$BASE_DIR denotes the base directory of the package. Clearly, the “dot” in the package name corresponds to a sub-
directory of the file system.

The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime
must be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an
environment variable called CLASSPATH. CLASSPATH is similar to another environment variable PATH, which is used
by the command shell to search for the executable programs.

Setting CLASSPATH:
CLASSPATH can be set by any of the following ways:

 CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ?
Advanced ? Environment Variables ? choose “System Variables” (for all the users) or “User Variables” (only
the currently login user) ? choose “Edit” (if CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the
variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g.,
“.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to include the current
working directory (denoted by ‘.’) in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:

 > SET CLASSPATH

 CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

 > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

 Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath
or -cp of the javac and java commands, for example,

 > java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

Illustration of user-defined packages:


Creating our first package:
File name – ClassOne.java
UNIT 4: Inheritance, Packages & Interfaces
package package_name;

public class ClassOne {

public void methodClassOne() {

System.out.println("Hello there its ClassOne");

Creating our second package:


File name – ClassTwo.java

package package_one;

public class ClassTwo {

public void methodClassTwo(){

System.out.println("Hello there i am ClassTwo");

Making use of both the created packages:


File name – Testing.java

import package_one.ClassTwo;

import package_name.ClassOne;

public class Testing {

public static void main(String[] args){

ClassTwo a = new ClassTwo();

ClassOne b = new ClassOne();

a.methodClassTwo();

b.methodClassOne();

Output:

Hello there i am ClassTwo


UNIT 4: Inheritance, Packages & Interfaces
Hello there its ClassOne

Now having a look at the directory structure of both the packages and the testing class file:

Important points:

1. Every class is part of some package.

2. If no package is specified, the classes in the file goes into a special unnamed package (the same
unnamed package for all files).

3. All classes/interfaces in a file are part of the same package. Multiple files can specify the same
package name.

4. If package name is specified, the file must be in a subdirectory called name (i.e., the directory name
must match the package name).

5. We can access public classes in another (named) package using: package-name.class-name

How to Implement Multiple Inheritance by Using Interfaces in Java?

Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than
one parent class. The problem occurs when methods with the same signature exist in both the superclasses and
subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling
which class method gets the priority.
UNIT 4: Inheritance, Packages & Interfaces

Interface is just like a class, which contains only abstract methods. In this article, we will discuss How to Implement
Multiple Inheritance by Using Interfaces in Java.

Syntax:

Class super

---

----

class sub1 Extends super

----

----

class sub2 Extend sub1

-----

-----

}
UNIT 4: Inheritance, Packages & Interfaces
Implementation

Multiple inheritances can be achieved through the use of interfaces. Interfaces are similar to classes in that they
define a set of methods that can be implemented by classes. Here’s how to implement multiple inheritance using
interfaces in Java.

Step 1: Define the interfaces

interface Interface1 {

void method1();

interface Interface2 {

void method2();

Step 2: Implement the interfaces in the class

public class MyClass implements Interface1, Interface2 {

public void method1() {

// implementation of method1

public void method2() {

// implementation of method2

Step 3: Create an object of the class and call the interface methods

MyClass obj = new MyClass();

obj.method1();

obj.method2();
UNIT 4: Inheritance, Packages & Interfaces
Example:

// Declare the interfaces

interface Walkable {

void walk();

interface Swimmable {

void swim();

// Implement the interfaces in a class

class Duck implements Walkable, Swimmable {

public void walk()

System.out.println("Duck is walking.");

public void swim()

System.out.println("Duck is swimming.");

// Use the class to call the methods from the interfaces

class Main {

public static void main(String[] args)

Duck duck = new Duck();

duck.walk();

duck.swim();

}
UNIT 4: Inheritance, Packages & Interfaces
Output:

Duck is walking.

Duck is swimming.
UNIT 5: Exception Handling & Multithreaded Programming
Types of Errors:

1. Compilation Errors:

 Compilation errors occur when the Java compiler encounters code that violates the syntax rules of
the Java programming language. These errors prevent the code from being compiled into bytecode.

 Examples include missing semicolons, undefined symbols, and syntax violations.

2. Runtime Errors:

 Runtime errors occur during the execution of a Java program. These errors can result from invalid
user input, incorrect logic, or unexpected environmental conditions.

 Examples include arithmetic exceptions (e.g., division by zero), array index out of bounds, and null
pointer exceptions.

3. Logical Errors:

 Logical errors, also known as semantic errors, occur when the program compiles and runs without
error but does not produce the expected output due to flawed logic or incorrect algorithms.

 Identifying and fixing logical errors often requires careful analysis and debugging.

Types of Exceptions:

1. Checked Exceptions:

 Checked exceptions are exceptions that must be either caught or declared by the method in which
they may occur. These exceptions are subclasses of Exception but not subclasses of
RuntimeException.

 Examples include IOException, SQLException, and FileNotFoundException.

2. Unchecked Exceptions:

 Unchecked exceptions, also known as runtime exceptions, do not need to be caught or declared
explicitly. They extend the RuntimeException class or one of its subclasses.

 Examples include NullPointerException, ArrayIndexOutOfBoundsException, and


ArithmeticException.

3. Errors:

 Errors represent serious problems that are typically beyond the control of the application. They
usually denote problems with the runtime environment rather than the application itself.

 Examples include OutOfMemoryError, StackOverflowError, and VirtualMachineError.

Exception Handling in Java:

Java provides mechanisms for handling exceptions using try, catch, finally, and throw keywords. Exception handling
allows developers to gracefully handle errors and failures, ensuring the stability and reliability of Java applications.
Here's a basic example:

try {

// Code that may throw an exception

int result = divide(10, 0);

System.out.println("Result: " + result);


UNIT 5: Exception Handling & Multithreaded Programming
} catch (ArithmeticException e) {

// Handle the exception

System.err.println("Error: Division by zero");

} finally {

// Code that always executes, regardless of whether an exception occurs

System.out.println("Finally block");

// Method that may throw an exception

public static int divide(int dividend, int divisor) {

return dividend / divisor;

Java Try Catch Block

In Java exception is an “unwanted or unexpected event”, that occurs during the execution of the program. When an
exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use
try catch block in Java. In this article, we will learn about Try, catch, throw, and throws in Java.

Why Does an Exception occur?

An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user,
Opening a non-existing file in your program, etc

Blocks and Keywords Used For Exception Handling

1. try in Java

The try block contains a set of statements where an exception can occur.

try
{
// statement(s) that might cause exception
}

2. catch in Java

The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch
block, which handles the exception that occurs in the associated try block.

catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
UNIT 5: Exception Handling & Multithreaded Programming
3. throw in Java

The throw keyword is used to transfer control from the try block to the catch block.

Below is the implementation of the above approach:

// Java program that demonstrates the use of throw

class ThrowExcep {

static void help()

try {

throw new NullPointerException("error_unknown");

catch (NullPointerException e) {

System.out.println("Caught inside help().");

// rethrowing the exception

throw e;

public static void main(String args[])

try {

help();

catch (NullPointerException e) {

System.out.println(

"Caught in main error name given below:");

System.out.println(e);

Output

Caught inside help().

Caught in main error name given below:


UNIT 5: Exception Handling & Multithreaded Programming
java.lang.NullPointerException: error_unknown

4. throws in Java

The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a
method can throw to the caller and does not handle itself.

Below is the implementation of the above approach:

// Java program to demonstrate working of throws

class ThrowsExecp {

// This method throws an exception

// to be handled

// by caller or caller

// of caller and so on.

static void fun() throws IllegalAccessException

System.out.println("Inside fun(). ");

throw new IllegalAccessException("demo");

// This is a caller function

public static void main(String args[])

try {

fun();

catch (IllegalAccessException e) {

System.out.println("caught in main.");

Output

Inside fun().

caught in main.
UNIT 5: Exception Handling & Multithreaded Programming
5. finally in Java

It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an
exception has occurred or not ) when there are multiple catch blocks.

An example of an exception generated by the system is given below:

Exception in thread "main"


java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number

Below is the implementation of the above approach:

// Java program to demonstrate working of try,

// catch and finally

class Division {

public static void main(String[] args)

int a = 10, b = 5, c = 5, result;

try {

result = a / (b - c);

System.out.println("result" + result);

catch (ArithmeticException e) {

System.out.println("Exception caught:Division by zero");

finally {

System.out.println("I am in final block");

}
UNIT 5: Exception Handling & Multithreaded Programming
Output

Exception caught:Division by zero

I am in final block

Java Catch Multiple Exceptions

Java Multi-catch block

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.

Points to remember

ADVERTISEMENT

ADVERTISEMENT

o At a time only one exception occurs and at a time only one catch block is executed.

o All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.

Flowchart of Multi-catch Block

Example 1

Let's see a simple example of java multi-catch block.


UNIT 5: Exception Handling & Multithreaded Programming
MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {

2.

3. public static void main(String[] args) {

4.

5. try{

6. int a[]=new int[5];

7. a[5]=30/0;

8. }

9. catch(ArithmeticException e)

10. {

11. System.out.println("Arithmetic Exception occurs");

12. }

13. catch(ArrayIndexOutOfBoundsException e)

14. {

15. System.out.println("ArrayIndexOutOfBounds Exception occurs");

16. }

17. catch(Exception e)

18. {

19. System.out.println("Parent Exception occurs");

20. }

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

22. }

23. }

Output:

Arithmetic Exception occurs

rest of the code

throw and throws in Java

In Java, Exception Handling is one of the effective means to handle runtime errors so that the regular flow of the
application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

In this article, we will learn about throw and throws in Java which can handle exceptions in Java.
UNIT 5: Exception Handling & Multithreaded Programming
Java throw

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can
throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Syntax in Java throw

throw Instance

Example:

throw new ArithmeticException("/ by zero");

But this exception i.e., Instance must be of type Throwable or a subclass of Throwable.

For example, an Exception is a sub-class of Throwable and user-defined exceptions typically extend the Exception
class. Unlike C++, data types such as int, char, floats, or non-throwable classes cannot be used as exceptions.

The flow of execution of the program stops immediately after the throw statement is executed and the nearest
enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a
match, controlled is transferred to that statement otherwise next enclosing try block is checked, and so on. If no
matching catch is found then the default exception handler will halt the program.

Java throw Examples

Example 1:

Java

// Java program that demonstrates the use of throw

class ThrowExcep {

static void fun()

try {

throw new NullPointerException("demo");

catch (NullPointerException e) {

System.out.println("Caught inside fun().");

throw e; // rethrowing the exception

public static void main(String args[])

try {

fun();
UNIT 5: Exception Handling & Multithreaded Programming
}

catch (NullPointerException e) {

System.out.println("Caught in main.");

Output

Caught inside fun().

Caught in main.

Example 2

Java

// Java program that demonstrates

// the use of throw

class Test {

public static void main(String[] args)

System.out.println(1 / 0);

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

Java throws

throws is a keyword in Java that is used in the signature of a method to indicate that this method might throw one of
the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

Syntax of Java throws

type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the

exceptions which a method might throw.

In a program, if there is a chance of raising an exception then the compiler always warns us about it and
compulsorily we should handle that checked exception, Otherwise, we will get compile time error saying unreported
exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the
exception in two ways:
UNIT 5: Exception Handling & Multithreaded Programming
1. By using try catch

2. By using the throws keyword

We can use the throws keyword to delegate the responsibility of exception handling to the caller (It may be a
method or JVM) then the caller method is responsible to handle that exception.

Java throws Examples

Example 1

// Java program to illustrate error in case

// of unhandled exception

class tst {

public static void main(String[] args)

Thread.sleep(10000);

System.out.println("Hello Geeks");

Output

error: unreported exception InterruptedException; must be caught or declared to be thrown

Explanation

In the above program, we are getting compile time error because there is a chance of exception if the main thread is
going to sleep, other threads get the chance to execute the main() method which will cause InterruptedException.

Example 2

// Java program to illustrate throws

class tst {

public static void main(String[] args)

throws InterruptedException

Thread.sleep(10000);

System.out.println("Hello Geeks");

Output

Hello Geeks
UNIT 5: Exception Handling & Multithreaded Programming
Explanation

In the above program, by using the throws keyword we handled the InterruptedException and we will get the output
as Hello Geeks

Example 3

// Java program to demonstrate working of throws

class ThrowsExecp {

static void fun() throws IllegalAccessException

System.out.println("Inside fun(). ");

throw new IllegalAccessException("demo");

public static void main(String args[])

try {

fun();

catch (IllegalAccessException e) {

System.out.println("caught in main.");

Output

Inside fun().

caught in main.

Exceptions in Java

Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the
application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

What are Java Exceptions?

In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run
time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the
program. When an exception occurs within a method, it creates an object. This object is called the exception object.
UNIT 5: Exception Handling & Multithreaded Programming
It contains information about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.

Major reasons why an exception Occurs

 Invalid user input

 Device failure

 Loss of network connection

 Physical limitations (out-of-disk memory)

 Code errors

 Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks,
stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.

Difference between Error and Exception

Let us discuss the most important part which is the differences between Error and Exception that is as follows:

 Error: An Error indicates a serious problem that a reasonable application should not try to catch.

 Exception: Exception indicates conditions that a reasonable application might try to catch.

Exception Hierarchy

All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One
branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an
example of such an error.
UNIT 5: Exception Handling & Multithreaded Programming

Java Exception Hierarchy

Types of Exceptions

Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their
own exceptions.
UNIT 5: Exception Handling & Multithreaded Programming
Exceptions can be categorized in two ways:

1. Built-in Exceptions

 Checked Exception

 Unchecked Exception

2. User-Defined Exceptions

Let us discuss the above-defined listed exception that is as follows:

1. Built-in Exceptions

Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain
certain error situations.

 Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.

 Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler
will not check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program would not give a compilation error.

Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions

2. User-Defined Exceptions:

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also
create exceptions, which are called ‘user-defined Exceptions’.

The advantages of Exception Handling in Java are as follows:

1. Provision to Complete Program Execution

2. Easy Identification of Program Code and Error-Handling Code

3. Propagation of Errors

4. Meaningful Error Reporting

5. Identifying Error Types

Methods to print the Exception information:

1. printStackTrace()

This method prints exception information in the format of the Name of the exception: description of the exception,
stack trace.
UNIT 5: Exception Handling & Multithreaded Programming
Example:

//program to print the exception information using printStackTrace() method

import java.io.*;

class GFG {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);

catch(ArithmeticException e){

e.printStackTrace();

Output

java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)

2. toString()

The toString() method prints exception information in the format of the Name of the exception: description of the
exception.
UNIT 5: Exception Handling & Multithreaded Programming
Example:

//program to print the exception information using toString() method

import java.io.*;

class GFG1 {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);

catch(ArithmeticException e){

System.out.println(e.toString());

Output

java.lang.ArithmeticException: / by zero

3. getMessage()

The getMessage() method prints only the description of the exception.


UNIT 5: Exception Handling & Multithreaded Programming
Example:

//program to print the exception information using getMessage() method

import java.io.*;

class GFG1 {

public static void main (String[] args) {

int a=5;

int b=0;

try{

System.out.println(a/b);

catch(ArithmeticException e){

System.out.println(e.getMessage());

Output

/ by zero

How Does JVM Handle an Exception?

Default Exception Handling: Whenever inside a method, if an exception has occurred, the method creates an Object
known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name
and description of the exception and the current state of the program where the exception has occurred. Creating
the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of
the methods that had been called to get to the method where an exception occurred. This ordered list of methods is
called Call Stack. Now the following procedure will happen.

 The run-time system searches the call stack to find the method that contains a block of code that can handle
the occurred exception. The block of the code is called an Exception handler.

 The run-time system starts searching from the method in which the exception occurred and proceeds
through the call stack in the reverse order in which methods were called.

 If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler means
the type of exception object thrown matches the type of exception object it can handle.

 If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate
handler, then the run-time system handover the Exception Object to the default exception handler, which is
part of the run-time system. This handler prints the exception information in the following format and
terminates the program abnormally.
UNIT 5: Exception Handling & Multithreaded Programming
Exception in thread "xxx" Name of Exception : Description
... ...... .. // Call Stack

Look at the below diagram to understand the flow of the call stack.

Illustration:

// Java Program to Demonstrate How Exception Is Thrown

// Class

// ThrowsExecp

class GFG {

// Main driver method

public static void main(String args[])

// Taking an empty string

String str = null;

// Getting length of a string

System.out.println(str.length());

}
UNIT 5: Exception Handling & Multithreaded Programming
Output

Let us see an example that illustrates how a run-time system searches for appropriate exception handling code on
the call stack.

Example:

// Java Program to Demonstrate Exception is Thrown

// How the runTime System Searches Call-Stack

// to Find Appropriate Exception Handler

// Class

// ExceptionThrown

class GFG {

// Method 1

// It throws the Exception(ArithmeticException).

// Appropriate Exception handler is not found

// within this method.

static int divideByZero(int a, int b)

// this statement will cause ArithmeticException

// (/by zero)

int i = a / b;

return i;

}
UNIT 5: Exception Handling & Multithreaded Programming

// The runTime System searches the appropriate

// Exception handler in method also but couldn't have

// found. So looking forward on the call stack

static int computeDivision(int a, int b)

int res = 0;

// Try block to check for exceptions

try {

res = divideByZero(a, b);

// Catch block to handle NumberFormatException

// exception Doesn't matches with

// ArithmeticException

catch (NumberFormatException ex) {

// Display message when exception occurs

System.out.println(

"NumberFormatException is occurred");

return res;

// Method 2

// Found appropriate Exception handler.

// i.e. matching catch block.

public static void main(String args[])

{
UNIT 5: Exception Handling & Multithreaded Programming
int a = 1;

int b = 0;

// Try block to check for exceptions

try {

int i = computeDivision(a, b);

// Catch block to handle ArithmeticException

// exceptions

catch (ArithmeticException ex) {

// getMessage() will print description

// of exception(here / by zero)

System.out.println(ex.getMessage());

Output

/ by zero

How Programmer Handle an Exception?

Customized Exception Handling: Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using
catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the
Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of
a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block
completes is put in a finally block.

Tip: One must go through control flow in try catch finally block for better understanding.

Need for try-catch clause(Customized Exception Handling)

Consider the below program in order to get a better understanding of the try-catch clause.
UNIT 5: Exception Handling & Multithreaded Programming
Example:

// Java Program to Demonstrate

// Need of try-catch Clause

// Class

class GFG {

// Main driver method

public static void main(String[] args)

// Taking an array of size 4

int[] arr = new int[4];

// Now this statement will cause an exception

int i = arr[4];

// This statement will never execute

// as above we caught with an exception

System.out.println("Hi, I want to execute");

Output

Output explanation: In the above example, an array is defined with size i.e. you can access elements only from index
0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it is throwing an exception. In this
case, JVM terminates the program abnormally. The statement System.out.println(“Hi, I want to execute”); will never
execute. To execute it, we must handle the exception using try-catch. Hence to continue the normal flow of the
program, we need a try-catch clause.
UNIT 5: Exception Handling & Multithreaded Programming
How to Use the Try-catch Clause?

try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try block ends
}

Certain key points need to be remembered that are as follows:

 In a method, there can be more than one statement that might throw an exception, So put all these
statements within their own try block and provide a separate exception handler within their own catch block
for each of them.

 If an exception occurs within the try block, that exception is handled by the exception handler associated
with it. To associate the exception handler, we must put a catch block after it. There can be more than one
exception handler. Each catch block is an exception handler that handles the exception to the type indicated
by its argument. The argument, ExceptionType declares the type of exception that it can handle and must be
the name of the class that inherits from the Throwable class.

 For each try block, there can be zero or more catch blocks, but only one final block.

 The finally block is optional. It always gets executed whether an exception occurred in try block or not. If an
exception occurs, then it will be executed after try and catch blocks. And if an exception does not occur,
then it will be executed after the try block. The finally block in Java is used to put important codes such as
clean-up code e.g., closing the file or closing the connection.

 If we write System.exit in the try block, then finally block will not be executed.

The summary is depicted via visual aid below as follows:


UNIT 5: Exception Handling & Multithreaded Programming
Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

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:

ADVERTISEMENT

ADVERTISEMENT

o Thread()

o Thread(String name)

o Thread(Runnable r)

o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.

8. public String getName(): returns the name of the thread.

9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently executing thread.

11. public int getId(): returns the id of the thread.

12. public Thread.State getState(): returns the state of the thread.

13. public boolean isAlive(): tests if the thread is alive.

14. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.

15. public void suspend(): is used to suspend the thread(depricated).

16. public void resume(): is used to resume the suspended thread(depricated).

17. public void stop(): is used to stop the thread(depricated).


UNIT 5: Exception Handling & Multithreaded Programming
18. public boolean isDaemon(): tests if the thread is a daemon thread.

19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

20. public void interrupt(): interrupts the thread.

21. public boolean isInterrupted(): tests if the thread has been interrupted.

22. public static boolean interrupted(): tests if the current thread has been interrupted.

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:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

ADVERTISEMENT

o A new thread starts(with new callstack).

o The thread moves from New state to the Runnable state.

o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

1. class Multi extends Thread{

2. public void run(){

3. System.out.println("thread is running...");

4. }

5. public static void main(String args[]){

6. Multi t1=new Multi();

7. t1.start();

8. }

9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{

2. public void run(){

3. System.out.println("thread is running...");

4. }
UNIT 5: Exception Handling & Multithreaded Programming
5.

6. public static void main(String args[]){

7. Multi3 m1=new Multi3();

8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)

9. t1.start();

10. }

11. }

Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to
explicitly create the Thread class object. We are passing the object of your class that implements Runnable so that
your class run() method may execute.

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors defined above.

FileName: MyThread1.java

1. public class MyThread1

2. {

3. // Main method

4. public static void main(String argvs[])

5. {

6. // creating an object of the Thread class using the constructor Thread(String name)

7. Thread t= new Thread("My first thread");

8.

9. // the start() method moves the thread to the active state

10. t.start();

11. // getting the thread name by invoking the getName() method

12. String str = t.getName();

13. System.out.println(str);

14. }

15. }

Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.


UNIT 5: Exception Handling & Multithreaded Programming
FileName: MyThread2.java

1. public class MyThread2 implements Runnable

2. {

3. public void run()

4. {

5. System.out.println("Now the thread is running ...");

6. }

7.

8. // main method

9. public static void main(String argvs[])

10. {

11. // creating an object of the class MyThread2

12. Runnable r1 = new MyThread2();

13.

14. // creating an object of the class Thread using Thread(Runnable r, String name)

15. Thread th1 = new Thread(r1, "My new thread");

16.

17. // the start() method moves the thread to the active state

18. th1.start();

19.

20. // getting the thread name by invoking the getName() method

21. String str = th1.getName();

22. System.out.println(str);

23. }

24. }

Output:

My new thread

Now the thread is running ...

Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

1. New

2. Active

3. Blocked / Waiting
UNIT 5: Exception Handling & Multithreaded Programming
4. Timed Waiting

5. Terminated

Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has
not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state
contains two states within it: one is runnable, and the other is running.

ADVERTISEMENT

ADVERTISEMENT

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the
thread may be running or may be ready to run at any given instant of time. It is the duty of the thread
scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and
every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily
gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever
such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the
runnable state. In the runnable state, there is a queue where the threads lie.

o Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the
most common change in the state of a thread is from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in
the blocked state or is in the waiting state.

For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same
time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait
for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to
perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say
that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main
thread then waits for the child threads to complete their tasks. When the child threads complete their job, a
notification is sent to the main thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine
which thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the
critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is
B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B.
Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state.
After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.

o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
UNIT 5: Exception Handling & Multithreaded Programming
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no
way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States

In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These
constants are:

1. public static final Thread.State NEW

It represents the first state of a thread that is the NEW state.

1. public static final Thread.State RUNNABLE

It represents the runnable state.It means a thread is waiting in the queue to run.

1. public static final Thread.State BLOCKED

It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final Thread.State WAITING

It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or
Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to complete its
task.

1. public static final Thread.State TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint.
Waiting has no time constraint, whereas timed waiting has the time constraint. A thread invoking the following
method reaches the timed waiting state.

o sleep

o join with timeout

o wait with timeout

o parkUntil

o parkNanos
UNIT 5: Exception Handling & Multithreaded Programming
1. public static final Thread.State TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its
execution.

Java Program for Demonstrating Thread States

The following Java program shows some of the states of a thread defined above.

FileName: ThreadState.java

ADVERTISEMENT

1. // ABC class implements the interface Runnable

2. class ABC implements Runnable

3. {

4. public void run()

5. {

6.

7. // try-catch block

8. try

9. {

10. // moving thread t2 to the state timed waiting

11. Thread.sleep(100);

12. }

13. catch (InterruptedException ie)

14. {

15. ie.printStackTrace();

16. }

17.

18.

19. System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -
"+ ThreadState.t1.getState());

20.

21. // try-catch block

22. try

23. {

24. Thread.sleep(200);

25. }

26. catch (InterruptedException ie)


UNIT 5: Exception Handling & Multithreaded Programming
27. {

28. ie.printStackTrace();

29. }

30. }

31. }

32.

33. // ThreadState class implements the interface Runnable

34. public class ThreadState implements Runnable

35. {

36. public static Thread t1;

37. public static ThreadState obj;

38.

39. // main method

40. public static void main(String argvs[])

41. {

42. // creating an object of the class ThreadState

43. obj = new ThreadState();

44. t1 = new Thread(obj);

45.

46. // thread t1 is spawned

47. // The thread t1 is currently in the NEW state.

48. System.out.println("The state of thread t1 after spawning it - " + t1.getState());

49.

50. // invoking the start() method on

51. // the thread t1

52. t1.start();

53.

54. // thread t1 is moved to the Runnable state

55. System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());

56. }

57.

58. public void run()

59. {
UNIT 5: Exception Handling & Multithreaded Programming
60. ABC myObj = new ABC();

61. Thread t2 = new Thread(myObj);

62.

63. // thread t2 is created and is currently in the NEW state.

64. System.out.println("The state of thread t2 after spawning it - "+ t2.getState());

65. t2.start();

66.

67. // thread t2 is moved to the runnable state

68. System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());

69.

70. // try-catch block for the smooth flow of the program

71. try

72. {

73. // moving the thread t1 to the state timed waiting

74. Thread.sleep(200);

75. }

76. catch (InterruptedException ie)

77. {

78. ie.printStackTrace();

79. }

80.

81. System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );

82.

83. // try-catch block for the smooth flow of the program

84. try

85. {

86. // waiting for thread t2 to complete its execution

87. t2.join();

88. }

89. catch (InterruptedException ie)

90. {

91. ie.printStackTrace();

92. }
UNIT 5: Exception Handling & Multithreaded Programming
93. System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());

94. }

95.

96. }

Output:

The state of thread t1 after spawning it - NEW

The state of thread t1 after invoking the method start() on it - RUNNABLE

The state of thread t2 after spawning it - NEW

the state of thread t2 after calling the method start() on it - RUNNABLE

The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING

The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING

The state of thread t2 when it has completed it's execution - TERMINATED

Explanation: Whenever we spawn a new thread, that thread attains the new state. When the method start() is
invoked on a thread, the thread scheduler moves that thread to the runnable state. Whenever the join() method is
invoked on any thread instance, the current thread executing that statement has to wait for this thread to finish its
execution, i.e., move that thread to the terminated state. Therefore, before the final print statement is printed on
the console, the program invokes the method join() on thread t2, making the thread t1 wait while the thread t2
finishes its execution and thus, the thread t2 get to the terminated or dead state. Thread t1 goes to the waiting state
because it is waiting for thread t2 to finish it's execution as it has invoked the method join() on thread t2.

Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the 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. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority

Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the
priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out
of the range, which is 1 (minimum) to 10 (maximum).

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.

Example of priority of a Thread:


UNIT 5: Exception Handling & Multithreaded Programming
FileName: ThreadPriorityExample.java

1. // Importing the required classes

2. import java.lang.*;

3.

4. public class ThreadPriorityExample extends Thread

5. {

6.

7. // Method 1

8. // Whenever the start() method is called by a thread

9. // the run() method is invoked

10. public void run()

11. {

12. // the print statement

13. System.out.println("Inside the run() method");

14. }

15.

16. // the main method

17. public static void main(String argvs[])

18. {

19. // Creating threads with the help of ThreadPriorityExample class

20. ThreadPriorityExample th1 = new ThreadPriorityExample();

21. ThreadPriorityExample th2 = new ThreadPriorityExample();

22. ThreadPriorityExample th3 = new ThreadPriorityExample();

23.

24. // We did not mention the priority of the thread.

25. // Therefore, the priorities of the thread is 5, the default value

26.

27. // 1st Thread

28. // Displaying the priority of the thread

29. // using the getPriority() method

30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());

31.

32. // 2nd Thread


UNIT 5: Exception Handling & Multithreaded Programming
33. // Display the priority of the thread

34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());

35.

36. // 3rd Thread

37. // // Display the priority of the thread

38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());

39.

40. // Setting priorities of above threads by

41. // passing integer arguments

42. th1.setPriority(6);

43. th2.setPriority(3);

44. th3.setPriority(9);

45.

46. // 6

47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());

48.

49. // 3

50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());

51.

52. // 9

53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());

54.

55. // Main thread

56.

57. // Displaying name of the currently executing thread

58. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());

59.

60. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

61.

62. // Priority of the main thread is 10 now

63. Thread.currentThread().setPriority(10);

64.

65. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());


UNIT 5: Exception Handling & Multithreaded Programming
66. }

67. }

Output:

Priority of the thread th1 is : 5

Priority of the thread th2 is : 5

Priority of the thread th2 is : 5

Priority of the thread th1 is : 6

Priority of the thread th2 is : 3

Priority of the thread th3 is : 9

Currently Executing The Thread : main

Priority of the main thread is : 5

Priority of the main thread is : 10

We know that a thread with high priority will get preference over lower priority threads when it comes to the
execution of threads. However, there can be other scenarios where two threads can have the same priority. All of
the processing, in order to look after the threads, is done by the Java thread scheduler. Refer to the following
example to comprehend what will happen if two threads have the same priority.

FileName: ThreadPriorityExample1.java

1. // importing the java.lang package

2. import java.lang.*;

3.

4. public class ThreadPriorityExample1 extends Thread

5. {

6.

7. // Method 1

8. // Whenever the start() method is called by a thread

9. // the run() method is invoked

10. public void run()

11. {

12. // the print statement

13. System.out.println("Inside the run() method");

14. }

15.

16.

17. // the main method


UNIT 5: Exception Handling & Multithreaded Programming
18. public static void main(String argvs[])

19. {

20.

21. // Now, priority of the main thread is set to 7

22. Thread.currentThread().setPriority(7);

23.

24. // the current thread is retrieved

25. // using the currentThread() method

26.

27. // displaying the main thread priority

28. // using the getPriority() method of the Thread class

29. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

30.

31. // creating a thread by creating an object of the class ThreadPriorityExample1

32. ThreadPriorityExample1 th1 = new ThreadPriorityExample1();

33.

34. // th1 thread is the child of the main thread

35. // therefore, the th1 thread also gets the priority 7

36.

37. // Displaying the priority of the current thread

38. System.out.println("Priority of the thread th1 is : " + th1.getPriority());

39. }

40. }

Output:

Priority of the main thread is : 7

Priority of the thread th1 is : 7

Explanation: If there are two threads that have the same priority, then one can not predict which thread will get the
chance to execute first. The execution then is dependent on the thread scheduler's algorithm (First Come First Serve,
Round-Robin, etc.)

Example of IllegalArgumentException

We know that if the value of the parameter newPriority of the method getPriority() goes out of the range (1 to 10),
then we get the IllegalArgumentException. Let's observe the same with the help of an example.

FileName: IllegalArgumentException.java

1. // importing the java.lang package


UNIT 5: Exception Handling & Multithreaded Programming
2. import java.lang.*;

3.

4. public class IllegalArgumentException extends Thread

5. {

6.

7. // the main method

8. public static void main(String argvs[])

9. {

10.

11. // Now, priority of the main thread is set to 17, which is greater than 10

12. Thread.currentThread().setPriority(17);

13.

14. // The current thread is retrieved

15. // using the currentThread() method

16.

17. // displaying the main thread priority

18. // using the getPriority() method of the Thread class

19. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

20.

21. }

22. }

When we execute the above program, we get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException

at java.base/java.lang.Thread.setPriority(Thread.java:1141)

at IllegalArgumentException.main(IllegalArgumentException.java:12)
Unit 6: File Handling
File handling in Java using FileWriter and FileReader

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character
Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read
and write any textual information as these are Byte stream classes.

FileWriter
FileWriter is useful to create a file writing characters into it.

 This class inherits from the OutputStream class.

 The constructors of this class assume that the default character encoding and the default byte-buffer size are
acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

 FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.

 FileWriter creates the output file if it is not present already.

Constructors:

 FileWriter(File file) – Constructs a FileWriter object given a File object.

 FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.

 FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.

 FileWriter (String fileName) – constructs a FileWriter object given a file name.

 FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a
Boolean indicating whether or not to append the data written.

Methods:

 public void write (int c) throws IOException – Writes a single character.

 public void write (char [] stir) throws IOException – Writes an array of characters.

 public void write(String str)throws IOException – Writes a string.

 public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here off is
offset from which to start writing characters and len is the number of characters to write.

 public void flush() throws IOException flushes the stream

 public void close() throws IOException flushes the stream first and then closes the writer.

Reading and writing take place character by character, which increases the number of I/O operations and affects the
performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
Unit 6: File Handling
// Creating a text File using FileWriter

import java.io.FileWriter;

import java.io.IOException;

class CreateFile

public static void main(String[] args) throws IOException

// Accept a string

String str = "File Handling in Java using "+

" FileWriter and FileReader";

// attach a file to FileWriter

FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write

// into FileWriter

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

fw.write(str.charAt(i));

System.out.println("Writing successful");

//close the file

fw.close();

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file.

 This class inherited from the InputStreamReader Class.

 The constructors of this class assume that the default character encoding and the default byte-buffer size are
appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

 FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a
FileInputStream.
Unit 6: File Handling
Constructors:

 FileReader(File file) – Creates a FileReader , given the File to read from

 FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from

 FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from

Methods:

 public int read () throws IOException – Reads a single character. This method will block until a character is
available, an I/O error occurs, or the end of the stream is reached.

 public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block
until some input is available, an I/O error occurs, or the end of the stream is reached.

 public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of
an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is
reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read

 public void close() throws IOException closes the reader.

 public long skip(long n) throws IOException –Skips characters. This method will block until some characters
are available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip

The following program depicts how to read from the ‘text’ file using FileReader
Unit 6: File Handling
// Reading data from a file using FileReader

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

class ReadFile

public static void main(String[] args) throws IOException

// variable declaration

int ch;

// check if File exists or not

FileReader fr=null;

try

fr = new FileReader("text");

catch (FileNotFoundException fe)

System.out.println("File not found");

// read from FileReader till the end of file

while ((ch=fr.read())!=-1)

System.out.print((char)ch);

// close the file

fr.close();

Java I/O Tutorial


Unit 6: File Handling
Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required
for input and output operations.

We can perform file handling in Java by Java I/O API.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream
of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");

2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character

2. System.out.println((char)i);//will print the character

ADVERTISEMENT

Do You Know?

o How to write a common data to multiple files using a single stream only?

o How can we access multiple files by a single stream?

o How can we improve the performance of Input and Output operation?

o How many ways can we read data from the keyboard?

o What does the console class?

o How to compress and uncompress the data of a file?

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or
socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or
socket.

Let's understand the working of Java OutputStream and InputStream by the figure given below.
Unit 6: File Handling

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An
output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException is used to write an array of byte to the current output stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy
Unit 6: File Handling
InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 at the
IOException end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be read from the
IOException current input stream.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy

You might also like