Object Oriented Programming Using Java
Object Oriented Programming Using 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
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.”);
}
};
If everything is OK, the “javac” compiler creates a file called “Test.class” containing byte code of the program.
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.
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.
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.
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
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.
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.
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
Java
import java.io.*;
class GFG {
System.out.println("GFG!");
Output
GFG!
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:
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.
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 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.)
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.)
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.
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.
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
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.
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.
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.
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, 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
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:
protected: Accessible within the package in which it is defined and in its subclass(es) (including
subclasses declared outside the package).
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
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.
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.
Java
Employee_name = n;
Employee_salary = p;
GFG.get();
}
UNIT 1: Introduction to Java
Output
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.
Java
//abstract class
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
//Employee class contains private data called employee id and employee name
class Employee {
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.
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
class A{
void method1(){}
void method2(){}
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
1. Overloading
2. Overriding
UNIT 1: Introduction to Java
Example
Java
// Overloaded sum().
return (x + y);
// Overloaded sum().
return (x + y + z);
// Overloaded sum().
return (x + y);
// Driver code
UNIT 1: Introduction to Java
public static void main(String args[])
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));
Output
30
60
31.0
Implementation of a Java application program involves the following step. They include:
class Test
};
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.
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++).
Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
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
// FileName : "HelloWorld.java".
class HelloWorld {
System.out.println("Hello, World");
Output
Hello, World
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:
static: The main method is to be called without an object. The modifiers are public and static can be written
in either order.
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
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).
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
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 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
twos-
complement 0 8 bits (none) -128 to 127
byte integer
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;
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;
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;
Syntax:
int intVar;
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.
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.
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;
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.
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
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
// Class
class GFG {
char a = 'G';
int i = 89;
// if memory is a constraint
byte b = 4;
// byte b1 = 7888888955;
short s = 56;
// short s1 = 87878787878;
UNIT 2: Building Blocks of the Language
// by default fraction value
// is double in java
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
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.
Example:
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.
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.
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.
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.
boolean
byte
char
short
int
long
float
double
Primitive data types are the types in java that can store a single value and do not provide any special capability.
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.
int a
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.
a: variable name.
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.
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
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.
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.
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.
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.
// 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
System.out.println(ch);
System.out.println(b);
System.out.println(c);
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
System.out.println(s);
System.out.println(s1);
UNIT 2: Building Blocks of the Language
}
}
Output
101.230
123.222
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
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 = '\n';
UNIT 2: Building Blocks of the Language
Example:
Java
char ch = 'a';
char b = 0789;
// Unicode representation
char c = '\u0061';
System.out.println(ch);
System.out.println(b);
System.out.println(c);
System.out.println("\" is a symbol");
Output
" is a symbol
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:
Java
// ASCII value of 7 is 55
int second = ‘7’;
System.out.println(“Geeks!” + first +
‘2’ + second);
}
}
Output
Hello
Boolean literals
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
Java
Output
true
false
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
// ASCII value of 0 is 48
// ASCII value of 7 is 55
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!48" + '2' + 55
"Geeks!482" + 55
"Geeks!48255"
Illustration 1:
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:
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
// Constants or Singletons
// Main class
// StringSingleton
// Strings
if (string1 == string2) {
// Returns true
System.out.println("True");
else {
// Returns false
System.out.println("False");
// Returns false
System.out.println("True");
else {
System.out.println("False");
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
// Constants or Singletons
// Main class
// StringSingleton
// Strings
// Displays true
System.out.println(string1.equals(string3));
// Displays false
System.out.println(string1 == string3);
Output
true
false
An element of program whose value can not be changed at the time of execution of program is called
constant.
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.
Variables in Java are only a name given to a memory location. All the operations done on the variable affect
that memory location.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
Variable Initialization
Illustrations:
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
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.
Java
// Local Variables
import java.io.*;
class GFG {
Output
Local Variable: 10
Example :
Java
package a;
// x is a local variable
int x = 10;
// variable
if (x > 5) {
// result is a
// local variable
System.out.println(result);
String loopMessage
= "Iteration "
System.out.println(loopMessage);
// compile-time error
// System.out.println(loopMessage);
Output :
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.
We initialize instance variables using constructors while creating an object. We can also use instance
blocks to initialize the instance variables.
Java
// Instance Variables
import java.io.*;
class GFG {
public int i;
public Integer I;
public GFG()
// Default Constructor
// Main Method
UNIT 2: Building Blocks of the Language
public static void main(String[] args)
// Object Creation
// Displaying O/P
+ name.i);
+ name.I);
Output
3. Static 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.
Java
// Static variables
import java.io.*;
class GFG {
// static variable
// declared locally.
Output
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.
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
Widening conversion takes place when two data types are automatically converted. This happens when:
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
// Main class
class GFG {
int i = 100;
long l = i;
float f = l;
Output
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
// Main class
char ch = 'c';
// Declaringinteger variable
ch = num;
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?
// Main class
// Double datatype
double d = 100.04;
long l = (long)d;
int i = (int)l;
// Print statements
}
UNIT 2: Building Blocks of the Language
Output
Note: While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).
Example:
Java
// Main class
class GFG {
byte b;
int i = 257;
double d = 323.142;
// Display message
// i % 256
b = (byte)i;
// Print commands
System.out.println(
UNIT 2: Building Blocks of the Language
"\nConversion of double to byte.");
// d % 256
b = (byte)d;
// Print commands
Output
i = 257 b = 1
d = 323.142 b= 67
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
// Main class
class GFG {
{
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
Output
result = 626.7784146484375
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
// in Integer to Byte
// Main class
class GFG {
byte b = 50;
b = (byte)(b * 2);
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:
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:
Syntax:
Java
import java.io.*;
class GFG {
int i = 10;
long l = i;
double d = i;
}
UNIT 2: Building Blocks of the Language
Output
Integer: 10
Long: 10
Double: 10.0
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:
Example:
Java
import java.io.*;
class GFG {
double i = 100.245;
short j = (short)i;
int k = (int)i;
UNIT 2: Building Blocks of the Language
+ i);
+ j);
+ k);
Output
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
import java.io.*;
class Animal {
}
UNIT 2: Building Blocks of the Language
class GFG {
{ // Upcasting
animal.makeSound();
// animal.fetch();
Output
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:
import java.io.*;
class Animal {
class GFG {
animal.eat();
// Explicit downcasting
cat.meow();
Output
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:
int a;
private String b;
char c;
Access specified of member variables doesn’t affect scope of them within a class.
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.
void method1()
int x;
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;
this.x = x;
The above code uses this keyword to differentiate between the local and class variables.
Java
this.x = 22;
y = 44;
UNIT 2: Building Blocks of the Language
t.method1(5);
Output:
Test.x: 22
t.x: 22
t.y: 33
y: 44
Java
// brackets
int x = 10;
System.out.println(x);
}
UNIT 2: Building Blocks of the Language
// System.out.println(x);
Output:
10
Java
class Test
System.out.println(x);
System.out.println(x);
Output:
System.out.println(x);
class Test
int 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
int a = 5;
System.out.println(a);
UNIT 2: Building Blocks of the Language
}
Output :
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.
class Test
int x = 5;
int x = 10;
System.out.println(x);
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:
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.
Below are given examples of wrapper classes in Java with their corresponding Primitive data types in Java.
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
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:
import java.util.ArrayList;
class Autoboxing {
char ch = 'a';
// conversion
Character a = ch;
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(25);
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
import java.util.ArrayList;
class Unboxing {
Character ch = 'a';
// conversion
char a = ch;
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);
// object
System.out.println(num);
}
UNIT 2: Building Blocks of the Language
Output
24
Java
// in Classes
import java.io.*;
class GFG {
byte a = 1;
int b = 10;
float c = 18.6f;
double d = 250.5;
char e = 'a';
Character charobj = e;
System.out.println(
+ byteobj);
+ intobj);
+ floatobj);
+ doubleobj);
+ charobj);
// types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
System.out.println(
Output
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
import java.io.*;
// wrapper class
class Maximum {
this.size++;
if (x <= this.maxi)
return;
this.maxi = x;
};
//
class GFG {
x.insert(3);
x.insert(23);
+ x.elementNumber());
Output
Maximum element: 23
A Wrapper class in Java is a class whose object wraps or contains primitive data types.
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.
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.
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:
Example:
Java
class Scomment
Output:
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
class Scomment
/*Comment line 1
Comment line 2
Output:
We can also accomplish single line comments by using the above syntax as shown below:
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
*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 {
/**
comment line 1
comment line 2
*/
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.
@return Adds a “Returns” section with the description text. @return description
@serial field-description |
@serial Used in the doc comment for a default serializable field.
include | exclude
@throws class-name
@throws The @throws and @exception tags are synonyms.
description
Implementation:
// Comment tags
/**
* @version 1.0
* @since 2017-02-18
*/
/**
*/
}
UNIT 2: Building Blocks of the Language
/**
* @return Nothing.
*/
Output:
For the above code documentation can be generated by using the tool ‘javadoc’:
javadoc FindAvg.java
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.
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.
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.
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.
i = null;
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.
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.
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.
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.
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.
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. A parameterized constructor to initialize name and age. The ID should be initialized in this constructor.
Now any beginner, who doesn’t know Garbage Collector in Java will code like this:
Java
// of employees working
// in a company
class Employee {
this.name = name;
this.age = age;
this.ID = nextId++;
{
UNIT 2: Building Blocks of the Language
System.out.println("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
+ nextId);
class UseEmployee {
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
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,
E.showNextId();
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
2. Call, System.gc();
3. Call, System.runFinalization();
Now the correct code for counting the number of employees(excluding interns)
class Employee {
this.name = name;
this.age = age;
this.ID = nextId++;
+ "\nAge=" + age);
+ nextId);
--nextId;
// In this case,
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
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
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Arrays in Java
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].
One-Dimensional Arrays
-- 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:
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.
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:
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.
In a situation where the size of the array and variables of the array are already known, array literals can be used.
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.
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.
class GFG {
int[] arr;
arr[0] = 10;
arr[1] = 20;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
}
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
You can also access java arrays using for each loops.
An array of objects is created like an array of primitive-type data items in the following way.
Syntax:
Example 1:
class GFG {
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:
// an array of objects
class Student {
this.roll_no = roll_no;
this.name = name;
Student[] arr;
// so on...
+ 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:
Example 3
Java
// an array of objects
class Student
Student(String name)
this.name = name;
@Override
return name;
System.out.println(m);
Output
Dharma
sanvi
Rupa
Ajay
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
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
System.out.println(
System.out.println(arr[5]);
}
UNIT 2: Building Blocks of the Language
Output
Java
arr[0] = 10;
arr[1] = 20;
System.out.println(arr[i]);
Output
10
20
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.
import java.io.*;
// Driver class
class GFG {
// Syntax
// 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
Example 1:
Java
// Driver Class
// main function
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
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
// Driver method
int arr[] = { 3, 1, 2, 5, 4 };
sum(arr);
int sum = 0;
sum += arr[i];
Output
As usual, a method can also return an array. For example, the below program returns an array from method m1.
Java
class Test {
// Driver method
// returning array
Output
123
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 Test {
// array of Strings
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;
1. The string “[I” is the run-time type signature for the class object “array with component type int.”
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.
Object Type Arrays Either declared type objects or it’s child class objects.
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.
Java
class Test {
int intArray[] = { 1, 2, 3 };
System.out.println(intArray == cloneArray);
Output
false
123
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
class Test {
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };
System.out.println(intArray == cloneArray);
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
No we can’t specify the size of array as long but we can specify it as int or short.
The size of the array cannot be altered(once initialized). However, an array reference can be made to point to
another array.
Creating a String
1. String literal
String s = “GeeksforGeeks”;
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:
Construct a new String by decoding the byte array. It uses the char_set for decoding.
Example:
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:
Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).
Example:
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:
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:
7. String(char[] char_arr)
Example:
Allocates a String from a given character array but choose count characters from the start_index.
Example:
Allocates a String from a uni_code_array but choose count characters from the start_index.
Example:
Example:
Example:
1. int length()
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i)
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.
Returns the index within the string of the first occurrence of the specified string, starting at the specified index.
Returns the index within the string of the last occurrence of the specified string.
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksforgeeks”
String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true
String s1="geeksforgeeks";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]
String s1="geeksforgeeks";
String s2="geeks";
s1.startsWith(s2) // return true
// String class.
import java.io.*;
import java.util.*;
// Driver Class
class Test
// main function
String s= "GeeksforGeeks";
+ s.charAt(3));
// to end of string
String s1 = "Geeks";
String s2 = "forGeeks";
s4.indexOf("Share"));
System.out.println("Index of a = " +
s4.indexOf('a',3));
out = "Geeks".equals("Geeks");
//If ASCII difference is zero then the two strings are similar
// Converting cases
word1.toLowerCase());
// Converting cases
UNIT 2: Building Blocks of the Language
String word2 = "GeekyME";
word2.toUpperCase());
// Replacing characters
Output
String length = 13
Substring ksforGeeks
Substring = eks
Index of Share 6
Index of a = 8
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.
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
// Arithmetic Operators
import java.io.*;
// Drive Class
class GFG {
// Main Function
// Arithmetic operators
int a = 10;
int b = 3;
UNIT 2: Building Blocks of the Language
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 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.
– – : 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.
// Uniary Operators
import java.io.*;
// Driver Class
class GFG {
// main function
// Interger declared
int a = 10;
int b = 10;
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.
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:
// Assignment Operators
import java.io.*;
// Driver Class
class GFG {
// Main Function
// Assignment operators
int f = 7;
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,
==, 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:
// Relational Operators
import java.io.*;
// Driver Class
class GFG {
// main function
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
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
&&, Logical AND: returns true when both conditions are true.
Example:
Java
// Logical operators
import java.io.*;
// Driver Class
class GFG {
// Main Function
// Logical operators
boolean x = true;
boolean y = false;
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 above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else
execute the statements after the ‘:’.
Example:
Java
// ternary operator.
// numbers
result
+ result);
Output
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 operators
import java.io.*;
// Driver class
class GFG {
// main function
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
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-
<<, 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
// shift operators
import java.io.*;
// Driver Class
class GFG {
// main function
int a = 10;
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-
// instance of operator
class operators {
class Person {
interface MyInterface {
Output
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
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.
// (* = / = %) > (+ = -)
// prints a+(b/d)
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.
// a=b+++c is compiled as
// b++ +c
a = b++ + c;
// a=b+++++c is compiled as
// b++ ++ +c
// a=b+++++c;
// System.out.println(b+++++c);
}
UNIT 2: Building Blocks of the Language
Output
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.
int x = 5, y = 8;
// concatenates x and y as
// addition of x and y
Output
Concatenation (x+y)= 58
Addition (x+y) = 13
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
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.
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.
if
if-else
nested-if
if-else-if
switch-case
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 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
import java.util.*;
class IfDemo {
int i = 10;
if (i < 15)
Output
Inside If block
10 is less than 15
I am Not in if
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)
// condition is true
else
// condition is false
}
UNIT 2: Building Blocks of the Language
Example:
Java
import java.util.*;
class IfElseDemo {
int i = 10;
if (i < 15)
else
}
UNIT 2: Building Blocks of the Language
Output
i is smaller than 15
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)
if (condition2)
}
UNIT 2: Building Blocks of the Language
Example:
import java.util.*;
class NestedIfDemo {
int i = 10;
if (i == 10 || i<15) {
// First if statement
if (i < 15)
// Nested - if statement
// it is true
if (i < 12)
System.out.println(
} else{
Output
i is smaller than 15
if (condition)
statement;
else if (condition)
statement;
else
statement;
UNIT 2: Building Blocks of the Language
Example:
import java.util.*;
class ifelseifDemo {
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
Output
i is 20
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;
import java.io.*;
class GFG {
int num=20;
switch(num){
break;
break;
break;
break;
}
UNIT 2: Building Blocks of the Language
Output
It is 20
The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7,
the expression can also be of type String.
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.
To exit a loop.
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:
// continue in an if statement
import java.util.*;
class ContinueDemo {
if (i % 2 == 0)
continue;
Output
13579
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:
import java.util.*;
boolean t = true;
if (t)
return;
// after return
Output
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.
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Data member
Method
Constructor
Nested Class
Interface
data member;
method;
constructor;
nested class;
interface;
}
UNIT 3: Object Oriented Programming Concepts
Example of Java Class
class Student {
int id;
String name;
// creating an object of
// Student
System.out.println(s1.id);
System.out.println(s1.name);
Output 1
null
Output 2
GeeksForGeeks
Output 3
GeeksForGeeks
1. Modifiers: A class can be public or has default access (Refer this for details).
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.
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 :
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.
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.
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:
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.
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
// Instance Variables
String name;
String breed;
int age;
String color;
String color)
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
// method 1
// method 2
// method 3
// method 4
+ "," + this.getColor());
Dog tuffy
System.out.println(tuffy.toString());
Output
Hi my name is tuffy.
// sw=software
sw_name = n;
sw_price = p;
+ sw_price);
GFG.get();
Output
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:
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).
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.
Example:
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.
clone() method is present in the Object class. It creates and returns a copy of the 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
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:
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 {}
{
UNIT 3: Object Oriented Programming Concepts
// using Dog object
Anonymous objects are objects that are instantiated but are not stored in a reference variable.
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()
System.out.println("Hello World!");
});
UNIT 3: Object Oriented Programming Concepts
Difference between Java Class and Objects
Class Object
No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.
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.
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
class Test
// static method
System.out.println("from m1");
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.
class Test
// static variable
static int b;
// static block
static {
b = a * 4;
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
Output
from main
Value of a : 10
Value of b : 40
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.
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.
class Test
// static variable
// static block
static {
// static method
System.out.println("from m1");
return 20;
System.out.println("Value of a : "+a);
System.out.println("from main");
}
UNIT 3: Object Oriented Programming Concepts
Output
from m1
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:
Java
class Test
// static variable
// instance variable
int b = 20;
// static method
a = 20;
System.out.println("from m1");
// instance method
void m2()
System.out.println("from m2");
// main method
Output:
prog.java:22: error: non-static method m2() cannot be referenced from a static context
prog.java:25: error: non-static variable super cannot be referenced from a static context
symbol: variable a
4 errors
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
// Student class
class Student {
String name;
int rollNo;
// static variable
this.name = name;
this.rollNo = setRollNo();
counter++;
return counter;
// static method
// instance method
void getStudentInfo()
// Driver class
Student.setCllg("XYZ");
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:
import java.io.*;
// Static class
// non-static method
System.out.println(str);
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 ExampleClass() {
count++;
id = count;
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.
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.
Java
// overloading in Java
return (x + y + z);
}
UNIT 3: Object Oriented Programming Concepts
// parameters
return (x + y);
// Driver code
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));
Output
30
60
31.0
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:
import java.io.*;
// Class 1
// Helper class
class Product {
// Method 1
int prod = a * b;
return prod;
// Method 2
int prod = a * b * c;
return prod;
// Class 2
// Main class
class GFG {
// method
System.out.println(
System.out.println(
Output
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:
import java.io.*;
// Class 1
// Helper class
class Product {
int prod1 = a * b * c;
return prod1;
double prod2 = a * b * c;
return prod2;
class GFG {
System.out.println(
UNIT 3: Object Oriented Programming Concepts
"Product of the three integer value :" + prod1);
System.out.println(
Output
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.
import java.io.*;
// Class 1
// Helper class
class Student {
// Method 1
}
UNIT 3: Object Oriented Programming Concepts
// Method 2
// Class 2
// Main class
class GFG {
// Main function
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
Output
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
Java
// Demo Class
class Demo {
class UseDemo {
UNIT 3: Object Oriented Programming Concepts
public static void main(String[] args)
byte a = 25;
// it will go to
// byte argument
obj.show(a);
// String
obj.show("hello");
// Int
obj.show(250);
// Since char is
// range is int.
obj.show('A');
// String
obj.show("A");
// will be an error.
obj.show(7.5);
}
UNIT 3: Object Oriented Programming Concepts
Output
obj.show(7.5);
1 error
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 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 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.
// Main class
class GFG {
// a final variable
// direct initialize
// direct initialize
// initializing CAPACITY
UNIT 3: Object Oriented Programming Concepts
{
CAPACITY = 25;
// initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
// 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:
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.
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:
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:
// Main class
class GFG {
System.out.println(sb);
sb.append("ForGeeks");
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:
// Main class
class GFG {
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:
// Main class
class GFG {
final int i;
i = 20;
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:
// Main class
class GFG {
int arr[] = { 1, 2, 3 };
// legal statement
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:
System.out.println(MESSAGE);
myObj.printMessage();
myObj.printFinalMessage();
// MyOtherClass extends MyClass {} // uncommenting this line will cause a compiler error
class MyClass {
void printMessage() {
System.out.println(message);
void printFinalMessage() {
System.out.println(finalMessage);
}
UNIT 3: Object Oriented Programming Concepts
// ...
Output
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).
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
class B extends 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.
class A
{
UNIT 3: Object Oriented Programming Concepts
System.out.println("This is a final method.");
class B extends A
void m1()
System.out.println("Illegal!");
Advantages:
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.
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.
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:
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
// specified
width = w;
height = h;
depth = d;
double volume()
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.
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.
// Constructor Overloading
class Box {
// specified
width = w;
height = h;
depth = d;
// specified
// Driver code
// constructors
UNIT 3: Object Oriented Programming Concepts
Box mybox1 = new Box(10, 20, 15);
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
vol = mycube.volume();
Output
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:
// Constructor Overloading
int boxNo;
// boxNo specified
width = w;
height = h;
depth = d;
boxNo = num;
Box()
// an empty box
Box(int num)
this();
boxNo = num;
UNIT 3: Object Oriented Programming Concepts
}
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;
statement in a constructor */
this(); /*ERROR*/
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
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.
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
Types of Inheritance
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
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.
ADVERTISEMENT
Executive.java
1. class Employee
2. {
3. float salary=34534*12;
4. }
6. {
7. float bonus=3000*6;
9. {
13. }
14. }
Output:
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.
MultilevelInheritanceExample.java
1. //super class
2. class Student
3. {
4. int reg_no;
6. {
7. reg_no=no;
8. }
9. void putNo()
10. {
12. }
13. }
16. {
UNIT 4: Inheritance, Packages & Interfaces
17. float marks;
19. {
20. marks=m;
21. }
23. {
25. }
26. }
29. {
32. {
33. score=scr;
34. }
36. {
38. }
39. }
41. {
43. {
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:
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.
ADVERTISEMENT
HierarchicalInheritanceExample.java
1. //parent class
2. class Student
3. {
5. {
7. }
8. }
10. {
14. }
15. }
17. {
19. {
21. }
22. }
24. {
26. {
28. }
29. }
31. {
33. {
37. //all the sub classes can access the method of super class
38. sci.methodStudent();
39. comm.methodStudent();
40. art.methodStudent();
41. }
42. }
Output:
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.
Daughter.java
1. //parent class
2. class GrandFather
3. {
5. {
6. System.out.println("I am grandfather.");
7. }
8. }
11. {
UNIT 4: Inheritance, Packages & Interfaces
12. public void show()
13. {
15. }
16. }
19. {
21. {
23. }
24. }
27. {
29. {
31. }
33. {
35. obj.show();
36. }
37. }
Output:
I am daughter.
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. {
11. {
13. }
14. }
16. {
18. {
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.
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:
class A
void m1()
class B extends A
// overriding m1()
void m1()
}
UNIT 4: Inheritance, Packages & Interfaces
}
class C extends A
// overriding m1()
void m1()
// Driver class
class Dispatch
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
A ref;
ref = a;
ref = b;
ref.m1();
ref = c;
ref.m1();
Output:
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.
5. Now a reference of type A, called ref, is also declared, initially it will point to null.
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.
In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be
achieved by data members. For example :
// by data members
// class A
class A
int x = 10;
// class B
class B extends A
int x = 20;
// Driver class
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.
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 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.
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.
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.*;
import java.util.vector;
import java.util.*;
First Statement is used to import Vector class from util package which is contained inside java.
import package.*;
import package.classname;
// Class name is generally used when two packages have the same
import java.util.Date;
import my.package.Date;
import java.util.Vector;
public ImportDemo()
// package.
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.
package myPackage;
System.out.println(s);
import myPackage.MyClass;
// with a value
// the package.
obj.getNames(name);
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 :
class StaticImportDemo
out.println("GeeksforGeeks");
Output:
GeeksforGeeks
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
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:
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:
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:
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,
package package_one;
import package_one.ClassTwo;
import package_name.ClassOne;
a.methodClassTwo();
b.methodClassOne();
Output:
Now having a look at the directory structure of both the packages and the testing class file:
Important points:
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).
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
---
----
----
----
-----
-----
}
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.
interface Interface1 {
void method1();
interface Interface2 {
void method2();
// implementation of method1
// implementation of method2
Step 3: Create an object of the class and call the interface methods
obj.method1();
obj.method2();
UNIT 4: Inheritance, Packages & Interfaces
Example:
interface Walkable {
void walk();
interface Swimmable {
void swim();
System.out.println("Duck is walking.");
System.out.println("Duck is swimming.");
class Main {
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.
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.
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.
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.
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 {
} finally {
System.out.println("Finally 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.
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
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.
class ThrowExcep {
try {
catch (NullPointerException e) {
throw e;
try {
help();
catch (NullPointerException e) {
System.out.println(
System.out.println(e);
Output
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.
class ThrowsExecp {
// to be handled
// by caller or caller
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.
class Division {
try {
result = a / (b - c);
System.out.println("result" + result);
catch (ArithmeticException e) {
finally {
}
UNIT 5: Exception Handling & Multithreaded Programming
Output
I am in final 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.
Example 1
2.
4.
5. try{
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
16. }
17. catch(Exception e)
18. {
20. }
22. }
23. }
Output:
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.
throw Instance
Example:
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.
Example 1:
Java
class ThrowExcep {
try {
catch (NullPointerException e) {
try {
fun();
UNIT 5: Exception Handling & Multithreaded Programming
}
catch (NullPointerException e) {
System.out.println("Caught in main.");
Output
Caught in main.
Example 2
Java
class Test {
System.out.println(1 / 0);
Output
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.
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
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.
Example 1
// of unhandled exception
class tst {
Thread.sleep(10000);
System.out.println("Hello Geeks");
Output
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
class tst {
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
class ThrowsExecp {
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.
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.
Device failure
Code errors
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.
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
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
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.
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’.
3. Propagation of Errors
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:
import java.io.*;
class GFG {
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:
import java.io.*;
class GFG1 {
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()
import java.io.*;
class GFG1 {
int a=5;
int b=0;
try{
System.out.println(a/b);
catch(ArithmeticException e){
System.out.println(e.getMessage());
Output
/ by zero
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:
// Class
// ThrowsExecp
class GFG {
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:
// Class
// ExceptionThrown
class GFG {
// Method 1
// (/by zero)
int i = a / b;
return i;
}
UNIT 5: Exception Handling & Multithreaded Programming
int res = 0;
try {
// ArithmeticException
System.out.println(
"NumberFormatException is occurred");
return res;
// Method 2
{
UNIT 5: Exception Handling & Multithreaded Programming
int a = 1;
int b = 0;
try {
// exceptions
// of exception(here / by zero)
System.out.println(ex.getMessage());
Output
/ by zero
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.
Consider the below program in order to get a better understanding of the try-catch clause.
UNIT 5: Exception Handling & Multithreaded Programming
Example:
// Class
class GFG {
int i = arr[4];
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
}
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.
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.
ADVERTISEMENT
ADVERTISEMENT
o Thread()
o Thread(String name)
o Thread(Runnable r)
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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user 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().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
ADVERTISEMENT
o When the thread gets a chance to execute, its target run() method will run.
FileName: Multi.java
3. System.out.println("thread is running...");
4. }
7. t1.start();
8. }
9. }
Output:
thread is running...
FileName: Multi3.java
3. System.out.println("thread is running...");
4. }
UNIT 5: Exception Handling & Multithreaded Programming
5.
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.
We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
2. {
3. // Main method
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
8.
10. t.start();
13. System.out.println(str);
14. }
15. }
Output:
My first thread
2. {
4. {
6. }
7.
8. // main method
10. {
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
22. System.out.println(str);
23. }
24. }
Output:
My new thread
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
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.
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:
It represents the runnable state.It means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
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.
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 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.
The following Java program shows some of the states of a thread defined above.
FileName: ThreadState.java
ADVERTISEMENT
3. {
5. {
6.
7. // try-catch block
8. try
9. {
11. Thread.sleep(100);
12. }
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.
22. try
23. {
24. Thread.sleep(200);
25. }
28. ie.printStackTrace();
29. }
30. }
31. }
32.
35. {
38.
41. {
45.
49.
52. t1.start();
53.
55. System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
56. }
57.
59. {
UNIT 5: Exception Handling & Multithreaded Programming
60. ABC myObj = new ABC();
62.
65. t2.start();
66.
68. System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());
69.
71. try
72. {
74. Thread.sleep(200);
75. }
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.
84. try
85. {
87. t2.join();
88. }
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 while it invoked the method join() on thread t2 -TIMED_WAITING
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.
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.
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).
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY
is 10.
2. import java.lang.*;
3.
5. {
6.
7. // Method 1
11. {
14. }
15.
18. {
23.
26.
31.
35.
39.
42. th1.setPriority(6);
43. th2.setPriority(3);
44. th3.setPriority(9);
45.
46. // 6
48.
49. // 3
51.
52. // 9
54.
56.
59.
61.
63. Thread.currentThread().setPriority(10);
64.
67. }
Output:
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
2. import java.lang.*;
3.
5. {
6.
7. // Method 1
11. {
14. }
15.
16.
19. {
20.
22. Thread.currentThread().setPriority(7);
23.
26.
30.
33.
36.
39. }
40. }
Output:
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
3.
5. {
6.
9. {
10.
11. // Now, priority of the main thread is set to 17, which is greater than 10
12. Thread.currentThread().setPriority(17);
13.
16.
20.
21. }
22. }
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.
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.
Constructors:
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, 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 (char [] stir) throws IOException – Writes an array of characters.
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 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
// Accept a string
// into FileWriter
fw.write(str.charAt(i));
System.out.println("Writing successful");
fw.close();
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
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(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 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
// variable declaration
int ch;
FileReader fr=null;
try
fr = new FileReader("text");
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
fr.close();
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.
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.
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");
ADVERTISEMENT
Do You Know?
o How to write a common data to multiple files using a single stream only?
OutputStream vs InputStream
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.
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.
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.
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.
InputStream Hierarchy