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

Full Java Notes

Uploaded by

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

Full Java Notes

Uploaded by

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

1 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 bulega666@gmail.

com

WHAT IS JAVA?
Java is an object-oriented programming language and a platform. It was made by the company
named Sun MicroSystems which was later acquired by Oracle Corporation. Today oracle manages
and releases different versions of java. Java was made by a team led by James Gosling at Sun
MicroSystems. As a programming language, we can write programs in java using English based
commands which can be executed on different types of devices. Some basic examples of programs
are "Addition of two number", "Multiplication of two number" "Printing a string" etc.
WHAT IS PROGRAM? A program is a group of instructions written with the help of a programming
language syntax. It performs a specific task when executed on any device E.g., "adding two number",
"multiplication of two number" etc.
WHAT IS SYNTAX IN JAVA? Like grammar in English, Java also has a set of defined rules that
must be followed while writing the programs. These rules are known as Syntax in java. A programmer
should know these syntaxes before writing. The image below shows a very basic java program written
inside a file.

In above image, the program has English based words also known as commands). These words
have special meaning in java programming language. low shows some of the devices where java
programs are executed to perform specific tasks.

IS JAVA A HIGH-LEVEL LANGUAGE? Yes, java is a high-level language. You can ably write
computer instructions using English based commands instead of writing instructions in low level
language (machine code or assembly language). At the time of execution, these commands
or high-level instructions are translated into low level instructions that computer can understand
and execute.
JAVA PLATFORM: Java is also a Platform. When you run a java program or application, java
creates a runtime environment where your java programs or application runs. Generally operating
systems like Microsoft Windows, Linux, Solaris, Mac OS etc. are known as platforms. These platforms
give you an environment where you can run different types of softwares or applications, similarly java
creates an environment at runtime where you only can run java programs or applications. Java
2 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
platform is a software-only platform that runs on top of a hardware-based platforms (OS) and they,
Java platforms, have a Java Virtual Machine (JVM) and application programming interface (API).
HOW DOES A COMPUTER UNDERSTAND A JAVA PROGRAM?
Computer doesn't understand java program directly as it's written in
English based commands. Computer understands only low-level
instructions (machine code or assembly language). Java program is
converted into low level instructions using java software (JDK and JRE)
which is then executed by a computer.

TYPES OF JAVA PLATFORMS


Java platforms are basically java softwares that is used in development and execution of java programs
or applications. You can download and use these softwares. There are four types of java platforms:
1.Java Platform, Standard Edition (Java SE). 2.Java Platform, Enterprise Edition (Java EE)
3.Java Platform, Micro Edition (Java ME). 4.JavaFX
WHY DOES JAVA PROVIDES DIFFERENT TYPES OF PLATFORMS?
As a developer or enterprise, you may want to develop different categories of applications
like desktop application, web application, gaming applications etc. To do so java provides different
types of platforms.
1.Java SE:This is the most basic or core platform. It defines basics of java language like data
types, syntaxes, classes, objects, interfaces etc. It also includes some high-level classes that
are used for security, networking, database access etc. All stand-alone or desktop applications
are developed using this platform. AWT and Swing used for developing desktop applications are
also part of a Java SE. You can also consider Java SE's API as Java programming language.
Apart from core API's, it also consists of a java virtual machine (JVM), development tools, and
other class libraries which are commonly used in Java applications.
2.Java EE: platform is built on top of Java SE platform. It also entails of an API and runtime
environment that is used for developing and running large-scale, multi-tiered, reliable, scalable and
secure network applications. All the java web and enterprise applications are developed using this
platform. Technologies like servlet, jsp, struts, JPA, EJB etc are part of this platform.
3.Java ME: This platform also consists of an API and a small virtual machine for running Java
programs and applications on small devices like mobile phones. This API is a subset of the Java
SE API, along with some additional class libraries that is useful for small device application
development. All java mobile applications and games are developed using this platform.
4.JavaFX: has a set of graphics and media packages to design rich client applications
that can run consistently on different platforms. The basic intent was to replace Swing because it
was bit complex. JavaFX offers a much simpler way to create desktop applications as well as rich
internet applications because it provides the facility to develop user interfaces as well. JavaFX
Scene Builder provides drag and drop UI component feature to develop applications.
USAGE OF JAVA LANGUAGE
With time the use of java has increased significantly which makes it one of the most ideal languages for
programmers and enterprises. According to Oracle, more than 3 billion devices run java. Some of the
3 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
devices that uses java include; ATMs, Smartcards, Routers, Switches, Smart Meters, Access
Control System, Medical Devices etc. There are several applications and softwares that use java in
one way or the other. Some of the uses of java are:
 Android operating system is developed using java. Most games and softwares running on
android are developed using java technologies.
 Popular desktop applications like acrobat reader, antiviruses softwares, media players are
developed using java language.
 Popular web applications like Linkedin.com, twitter.com are also using java in one way or other.
 Due to enhanced security of java, most of the banking applications are developed using java.
 Big Data technologies like Hadoop, HBase, ElasticSearch etc are also using java.
 Programmer's text editor like eclipse, Netbeans, JEdit etc are also developed using java.

HISTORY OF THE JAVA LANGUAGE


Java was made by a company called Sun MicroSystems. James Gosling is known as the maker
of java language. In 1991, a team named Green team, led by James Gosling started working on
java language project. Their intention was to develop the language that can be used for digital devices
like cell phones, televisions, set-top boxes etc. Sun Microsystems released the first version as
Java 1.0 in 1995, and its main focus had shifted to use on the Internet. Firstly, the name of language
was Oak, a tree name which was outside of Gosling office. Later it was renamed as Green and was
finally renamed as Java. Gosling designed the syntaxes of Java similar to C/C++, so that programmers
could find it easy to use as these languages were already being used by most of the programmers at
that time. On Nov 13, 2006, Sun Microsystems released most of its Java virtual machine (JVM)
as free and open-source software under the terms of a GNU General Public License (GPL). On May
8, 2007, Sun made all its JVM's core code available under free software/open-source distribution terms.
WHAT IS OPEN-SOURCE SOFTWARE?
Open-source software is a software whose source code is also released along with software so that
you can read or change the source code as per your needs and can re-distribute the software as well.
You can download and use it without any cost. Java is not completely open-source software. In 2009-
10 Oracle acquired Sun Microsystems, since then all major versions and updates are handled by
Oracle. With time Java has evolved as a very successful language to be used on and off the Internet.
Today many of the applications and devices which we use on daily basis are using java.
IS JAVA SE 11 FREE OR PAID?
If you want to use java 11 for commercial purpose then yes, you will have to pay and buy license from
oracle. But for development and testing purposes, it's free, you can download and use it without any
cost. The table below shows the list of other java versions and their release dates. The latest stable
release of java is Java SE 16 as of now (March 2021).
JAVA VERSION RELEASE DATE
Java SE 12 March 19, 2019

Java SE 13 September 17, 2019


4 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Java SE 14 March 17, 2020

Java SE 15 September 15, 2020

Java SE 16 March 16, 2021

HARDWARE AND SOFTWARE REQUIREMENTS FOR JAVA


It's easy to start programming in java, you just need to have the following hardware and software needs
in order to create and run java program in your system. Hardware requirements for java programming.
The hardware requirement actually depends on the version of java you want to use. Java 16 version
requires following hardware configuration:
 Processor: 1.8 GHz or faster processor.
 RAM: 2 GB of RAM; 4 GB of RAM recommended (2.5 GB minimum if use on a virtual machine)
 Disk Space: up to 130 GB of available space, depending on features installed; typical
installations require 20-50 GB of free space.
SOFTWARE REQUIREMENTS FOR JAVA PROGRAMMING
1.An editor like notepad, notepad++, TextPad etc. for windows operating system and Vim, Notepadqq,
Geany etc for linux based operating system to write the java program. The notepad editor comes by
default with windows operating system. The programmer can choose the editor of their choice.

An Editor A Terminal
2.Any terminal like cmd shell etc. to compile and run java program. By default, CMD is available in
windows OS while shell is available in Linux based OS. Programmer can use PowerShell(if available)
and in windows to compile and run java programs. WHAT IS TERMINAL? A terminal is a program
or software which offers a user interface where you can execute commands for e.g. CMD in Window
OS and Secure Shell Client in Linux based OS are terminals.
3.Java development kit (JDK) is a software that is used to develop and execute of java programs
or applications. If JDK is not already installed in your system then download and install it (JDK as per
your OS) first. Which JDK version should i use? It's completely your choice. Just to add a point, from
JDK 11 and onward java is licensed, you can use it free only for development and testing purposes
not for commercial purposes. If you are starting to learn java, JDK 8 is still a good choice.
That's all you need to enter in the world of java. By default, Notepad and CMD is available in windows
operating system. You just have to download and install JDK if not already installed.
5 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
HOW TO INSTALL JDK IN WINDOWS
The first step is to decide which version of jdk you want to download. Once you have decided the
version, just search on internet like " jdk 8 download" or " jdk 11 download" or " jdk 16 download".
After that open and follow the oracle download link to download the JDK.
Just to note, you will have to create an oracle account first to download it
from oracle site. You can also refer to the Oracle JDK link to download the
JDK. If available, you can download it from another site as well. The image
link below downloads JDK 8 for windows 64-bit OS. Once you downloaded
it, probably you have got an exe file. Now just double click on this file and
then follow the instructions given in new pop-up window to install JDK in
your system.
NOTE: Make sure you download the right JDK for your operating system. If you are using windows OS,
download a JDK for windows, similarly for other OS, download respective JDK. Also download the 32-
bit JDK if your OS is 32 bits else download 64-bit JDK if your OS is 64-bit operating system. Latest
downloads of JDK's includes 32- and 64-bit’s packages in same exe or zip file.
PATH AND CLASSPATH IN JAVA
Once you have installed java, you may need to set a Path variable. A Path is an environment variable
in an operating system. This Path variable stores a list of directories separated by semicolons (;)
as value. These directories points to locations where executable files are available. Once a command
is executed in a terminal e.g. cmd, the OS looks for the corresponding executable in these directories.
In java, executable files are found in the bin e.g. C:\Program Files\Java\jdk1.8.0_102\bin folder of
the java installation. Folder has executables; javac.exe, java.exe, javap.exe, javadoc.exe etc.
These executables are used for different types of tasks in java e.g. javac.exe is used for compilation
of java programs, java.exe used for execution of java programs. If Path variable is not set, you will
have to go to the directory with the executables to execute a command in terminal. Once Path variable
is set, java commands or JDK tools can be executed from any directory in a terminal. Let's see how to
set Path variable in different operating system.
HOW TO VERIFY JAVA VERSION AND JAVA INSTALLATION
Once you have installed java in your system, check whether it has been installed properly or not. It
covers both the cases, first if Path variable for java is not set and second if Path variable for java is set
after installation. 1. If a Path variable is not set, to check if java is installed properly or not, open a
command terminal like cmd etc. and change or move to the java installation directory the bin folder,
now execute the command java -version. It will display the installed java version and other relevant
data about java. Java compiler version can also be checked by executing javac -version command.
6 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The image above shows the steps for checking a java installation in Windows operating system using
cmd terminal. Similarly, for Linux based operating system, execute the same command in any linux
based terminal to check java installation.
2. If Path is set, there is no need to move to java installation directory, just execute the command java -
version in any directory. It will display the installed java version and other relevant information about
java. For compiler version execute javac -version command.

If any of the above methods returns the version correctly, which means java is installed properly. Now
you can start your first program in java.
HOW DO I KNOW IF JAVA IS INSTALLED ON WINDOWS 10?
The steps are same irrespective of which version of windows you are using. Just follow above steps to
check if java is installed on windows 10 or not. If java is not installed, it will display an error message in
Windows like "java is not recognized as internal or external command, operable program or batch file"
after executing the command.

HOW DO I KNOW IF I HAVE A JAVA JDK INSTALLED?


Just execute java -version and javac -version command as given above inside a terminal to see
if java jdk is installed or not. If these commands return version of java and java compiler, it means java
jdk is installed on your system. NOTE: You must be in the bin folder of the JDK to check the java
installation if Path variable is not set. As a good practice you should always set your path variable first
before you start writing programs in java. You can execute java -help command on terminal to get
different usage of java command. Once you set the path of java, you need to restart the cmd (if already
open) to get the correct result of java -version or javac -version command.
7 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

WHAT IS A SYNTAX IN THE JAVA LANGUAGE


It is a serious requirement for a programmer to first know the syntax of writing a program in a specific
programming language. Sometimes it gets confusing for beginners to know what exactly a syntax
is. Every programming language has a set of rules for writing programs in that programming language.
The rules are called syntax. Java also has a set of rules for defining different types of members(class,
variable, methods etc) in a program, we call these rules as syntax in java. A java programmer should
know these syntaxes before writing program in java. Our real-life languages also have defined sets of
rules in order to write sentences in them e.g. English language has also defined a set of rules, which
we call as Grammar. You should know the grammar first in order to write sentences in english, the
same applies with programming languages as well. In java, a program commonly contains a class. A
class has variables, methods, constructors etc in it. A program may also have looping statements,
arrays, objects, if else statements etc. Each of these members has some syntax which must be
followed while writing them inside a program. Let's see the basic syntax of some members one by one.
SYNTAX OF CLASS IN JAVA
In order to create a class in java, we should follow below syntax :
class ClassName {
// Define class members like variables, method, constructors etc.
}
Example:
class MyFirstJavaProgram {
// Define members of class.
}
// The class declaration below is wrong because the keyword,
must be in small letter.
Class Test {
// Define members of class.
}
Here class is a keyword, used to define a class in java. ClassName is the name of class, given by
the programmer. After the class name, it's the class body given inside { }. You can define variables,
methods, constructors etc of this class inside the { }. So in order to create a class in java you
have to follow the above syntax.
IS CLASS KEYWORD CASE-SENSITIVE ?
All keywords in java are case-sensitive and they must be in small letter. So, you can’t use the
class keyword as Class, CLASS, clAss etc, it must be in small letters.
SYNTAX OF VARIABLE IN JAVA
In java if you have to create a variable, you have to follow below syntax:
DataType variable_name = value;
Example:
int age = 20;
8 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

// Below variable declaration are incorrect


// variable name should not start with digits.
String 12message = "ISBAT University";
// Variable name should come after data type
year int = 2021;
Every variable in java must have a data type. The data type of a variable tells what type of data
that variable can store e.g. int type of variable stores only integer type value, similarly float type of
variable stores float type of values only. A name of variable is given by the programmer which
must be a valid identifier. There are java rules and conventions defined by for naming variables.
SYNTAX OF A METHOD IN JAVA
In java if you want to create a method, you have to follow below syntax:
Return_Type methodName(DataType param1, DataType param2 ...) {
// method logic or code.
return some_value;
}
Example:
int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
// The method declaration below is incorrect, the ( ) must follow the method name.
void test {
// method logic or code.
}
A method must have a return type which tells what type of value it returns. The Return_Type of a
method can be primitive or non-primitive data type. If a method doesn't return a value, it's return type
must be void. After the return type, is a method name given by the programmer. After the method
name, are the parameters given inside ( ) which are mostly variables. Parameters are optional
which means a method may or may not have parameters. You can access these parameters within the
method body only, not outside the method body. Data type of parameters can also be primitive
or non-primitive. After parameters, it's the method body given inside { }. Everything given inside { }
after method name are the part of that method.

WHAT IS SYNTAX VALIDATION IN JAVA


Syntax validation is a process where a java compiler (javac) validates whether the members of a
program are defined as per the syntax or not. If it's not as per the syntax, the java compiler will show a
syntax error for that member while compiling a program. In java, once a program is written, its compiled
first using java compiler before it can be executed.
9 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

If there is an error in compilation, a java programmer must fix that error first and then recompile the
program. Only after successful compilation, will the compiler create a .class file of that program which
is then used for execution of that program. What is syntax error in Java? When a member of a
program is not defined as per the syntax of that member, the java compiler generates an error while
compiling that program. We call such an error, a syntax error. How do you find syntax errors?
By compiling the program using java compiler we get the syntax errors of a program. How do you fix a
syntax error? Just follow the correct syntax of defining that member which is giving the syntax error.
Now let us write our first program in java which will help us to understand how to write program in java.
MY FIRST JAVA PROGRAM - HOW TO COMPILE AND RUN JAVA PROGRAM
It's easy to start writing program in java. To write your first java program, open an editor like notepad,
notepad++ or any other editor and write bellow line of code.
class MyFirstProgram
{
public static void main(String [] args)
{
System.out.println("ISBAT University");
}
}

The program given above is a basic


java program which will just print a
string message in console after
execution. The image given below
shows the above program written in
Notepad editor.

After writing a JAVA code in an editor, save the file as per the convention given by java which says
the file name should be the same as the class name with .java extension. So, let's save the above
program file as MyFirstProgram.java. Above, the program class name is MyFirstProgram.
10 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Is it a must to save a file name as a class name? No, if it doesn't have a class declared along with
public keyword. If it has a public class then it must be saved with public class name. It's good to follow
the convention given by java. The keyword public is an access modifier. What does a .java file
contain? A .java file contains the source code written in java of a program.
HOW TO COMPILE JAVA PROGRAM
After saving a java file, compile the java program using the javac command. Before compiling,
set the Path variable for java on your PC. To compile the program, open a terminal (e.g. cms in
windows) and move to the directory where above program is saved. Here our program is saved
on D:\JavaPrograms directory. Now run this command:
javac MyFirstProgram.java

Once the programmer has executed above command, java compiler will check for any syntax error in
the program, if it does not find any error, a .class file as MyFirstProgram.class will be generated
at the same location where program is saved. In successful compilation, compiler does not display any
message on command prompt instead a .class file is made. Recall you need to write the program file
name with a .java extension after the javac command while compiling a program. What is .class
11 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
file? A .class file is a compiled code of a java program into Bytecode. It's a middle representation of
your java program. Where does a Java program begin its execution? From main method, it's the
starting point of a program execution. Does java use the .java file while running a program? No, it
only uses the .class file while running a program. If delete a .java file after its made .class file, can
I run my program? Yes, you can, because the .java file is not needed at runtime. Only .class file is
needed while running the program.
NOTE:
 In java, every program must have at least one class, but it can have more than one class.
 There should be only one main method having argument type as String [ ] in a class.
 If there are multiple classes in a program, it must be saved by class name having public
access modifier if any.
 Every starting { must have a balanced } for it.

THE BASIC OR COMMON TERMS USED IN A JAVA PROGRAMS.


A description of each term is given to beginners because it's necessary to understand these terms in
order to start writing program in java.

●Keywords - All programming language defines a set of words which have a predefined meaning in
them. These words are called keywords. You cannot use these words for variable names, method
names, class names or other identifier names in your program, since these are reserved words.
Java also has reserved words. E.g. You cannot use the int keyword as a variable, method or class
names. Similarly, the words class, public, static, void are java keywords in above program.
// Following are incorrect declaration since final and switch are keyword in java.
int final = 20; // final cannot be used as variable name
switch { } // switch cannot be used as class name
Are java keywords case sensitive? Yes, keywords in java are case sensitive. All letters of keyword
must be small. What if I use keywords as my variable, class or method name? Your program won't
compile, java compiler will throw compilation error.
●class - The class is a keyword in java which is used to define a class. In java, every program must
have a class. A class holds set of methods and variables. After a class keyword, programmers need
12 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
to write the name of the class which is used to refer that class within or outside the class. In above
program MyFirstProgram is the name of a class, everything that is inside the { } after the class name
are the part of class.
●Statement - A statement is like to a sentence in english language. As sentences makes a complete
idea. A java statement makes a complete unit of execution. In above program line 5,7,8 are statements.
●Method - A method is set of statements that performs specific task or call other methods. A method
has a name and return type. The name of the method is used to refer that method within or outside
a class. A class can have multiple methods. In above program main is the method name. Everything
that comes between the { } after method name are part of the method. Every java program must have
a main method if it needs to be run independently. The main method is the starting point of execution
of a program in java.
●block - A block is a group of zero or more statements. It starts with curly braces { and ends with
balanced }. All statements inside balanced { } are part of a block. A block is used to group several
statements as a single unit. A block can have another block inside it. Blocks do not have a name, they
are just logical grouping of statements inside { }. Refer static and instance initializer blocks in java
to get more detail about blocks in java.
●public - The keyword public is an access modifier that decides the visibility or accessibility of
a member. Variables or methods declared with a public keyword can be accessed outside the
class. Since main method is called by the JVM at the time of program execution that is why it must
be declared as public, otherwise JVM won't be able to find the main method in your program and your
program will not execute. Refer access modifiers in java to get more data.
●static - The static is a keyword in java. A method or variable declared with static keyword can
be called without creating an object of that class. Since a JVM calls the main method without creating
the object of the class, that is why it must be declared as static, otherwise JVM won't be able to call
the main method.
●return - The return is also a keyword in java. It is used to return value from the method to the caller
of the method. Every method must have a return type, if it's not returning any value then the return
type of that method must be void. Since main method doesn't return any value, that's why it's return
type is void.
●Variable & Data type – A Variable in java is used to store a value. A Data type of a variable
defines what type of data that variable can store. In above program a is a variable and int is its data
type, which means a can only hold an integer type value.
●Parameter - A parameter is special kind of variable which receives a value from the caller of a
method. A parameter can be used in a method where it’s declared. In the above example, args is
a parameter of type String array. Any arguments passed to a program while running the program is
stored in the args parameter.
●System.out.println() – It’s used to print the output string or variable of a program on console.
Anything passed to the println method will be printed on the console. A console is a window or
13 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
terminal where you can pass input to a program or print a programs output. Command prompt
(cmd) in windows is an example of console.

COMPILE TIME AND RUNTIME IN JAVA


Runtime and compile time, these are two programming terms that are more often used in
java programming language. Programmers especially beginners find it so difficult to know what exactly
they are. In java, running a program occurs in two steps, compilation and then execution. The image
below shows where does compile time and runtime takes place in execution of a program.

WHAT IS COMPILE TIME IN JAVA


After writing the program, programmer needs to compile their programs. As soon as the programmer
starts compiling a program using javac compiler, the compile time gets started, and it ends when
either a .class file is generated after successful compilation or an error is thrown in compilation. In
other words, the process of compiling a program is referred as compile time. For an example if you
wrote a program and saved it as MyFirstProgram.java, if you compile it using a javac command
as javac MyFirstProgram.java, the compile time gets started and it ends when a .class file
as MyFirstProgram.class is made or any error is thrown in compilation.
WHAT HAPPENS AT COMPILE TIME IN JAVA?
At compile time, a java compiler(javac) takes the source code(.java file) and checks if there
is any syntax, type-checking or any semantic errors inside the program. If there is no error,
the compiler generates a .class(bytecode) file for that .java file. If there is any compilation error,
java compiler displays that error in command window (eg cmd).
WHAT IS COMPILE TIME ERROR IN JAVA?
If a program element(class, method, variable, statements etc) is not written as per it's syntax in java,
the compiler throws an error for that element while compiling the program. We call these errors
compile time errors as these errors are detected at compile time by the java compiler. Does java
compiler generate a .class file even if it throws compilation error? No, it will not generate .class file, it
will only display the compilation error in console(eg. cmd) window. Let us see compile time error by an
example. The most common mistake that beginners do is, they forget to add semicolon(;) at the end of
a statement which results as a compilation error while compiling the program.
class MyFirstProgram {
public static void main(String [] args) {
14 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("first statement") // missing semicolon(;)
System.out.println("second statement");
}
}
Once you compile above program as javac MyFirstProgram.java, it will display a compilation error in
console window like below :
Compile time Error:
MyFirstProgram.java:3: error: ';' expected
System.out.println("first statement") // missing semicolon(;)
^
1 error
WHAT IS RUNTIME IN JAVA?
As soon as the programmer starts executing the program using java command, runtime gets started
and it ends when execution of program ended either successfully or unsuccessfully. In other way the
process of running a program is known as runtime. For an example if you wrote a program and saved it
as MyFirstProgram.java. After compilation when you execute the command java MyFirstProgram for
running the program, runtime gets started and it ends when either the output of program is generated
or any runtime error is thrown.
WHAT IS RUNTIME ERROR IN JAVA?
Errors which come during the execution(runtime) of a program are known as runtime errors. If a
program contains a runtime error, it won't run successfully, rather that runtime error will be shown in
command window(eg. cmd) at the time of execution. Imagine you wrote a program MyFirstProgram.java
like below, After compilation when you run the below program using java MyFirstProgram command,
it will throw a runtime error.
class MyFirstProgram {
public static void main(String [] args) {
int num1 = 10;
int num2 = 0;
System.out.println(num1/num2); // Runtime error: Divide by zero exception
}
}
Runtinme Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at MyFirstProgram.main(MyFirstProgram.java:5)

DIFFERENCE BETWEEN RUNTIME AND COMPILE TIME


Compile time is a process where a java compiler compiles a java program and makes a .class file.
In other way, in compile time java source code(.java file) is converted in to .class file using
java compiler. While in runtime, the java virtual machine JDK loads the .class file in memory
and executes that class to generate the output of program.
15 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
DIFFERENCE BETWEEN COMPILE TIME ERROR AND RUNTIME ERROR
Compile time errors are errors that arise when compiling a program while runtime errors are
errors that comes at the time of execution(run-time) of a program. An example of a compile time error
is “not adding a semicolon (;) at the end of a statement” in your java program while “dividing a
number by zero” is an example of runtime error.

BYTECODE IN JAVA
Bytecode: In java when you compile a program, the java compiler(javac) converts or rewrites your
program in machine language form called bytecode. A .class file that is generated after compilation
are the bytecode instructions of a program. Bytecode and .class are used interchangeably, so if
someone says bytecode, it simply means the .class file of program.

At runtime Java virtual machine takes the bytecode(.class) as an input and convert this into
machine(windows, Linux, MacOS etc) specific code for further execution. So, bytecode in java
is just an intermediate representation or code of a java program in form of a .class file. We call
it intermediate representation/code because it lies between source and machine code.
Source code → Bytecode → Machine code
Bytecode is also one of java's magic since this along with java virtual machine (JVM) makes
java platform independent and a secure language. It becomes platform independent because
you can run the bytecode made on one PC on any other PC without the need of the original .java file,
all you need is a JVM or JRE installed on a computer e.g. .class file generated on windows machine
can be run on Linux machine. Bytecode also makes java secure because it can be run by java virtual
machine only. Also, any explicit edit in .class file breaks down the class meaning you will not be able
to run your program through the edited .class file.
Does a PC understand bytecode? No, Computers don’t understand bytecode directly. At runtime, the
bytecode is converted into machine specific code by a java interpreter. This machine code is then
executed by the PC CPU to make the output of a program. Is bytecode human readable? No, bytecode
is not human readable. What makes bytecode in java? It's a java compiler(javac). Is bytecode machine
16 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
dependent or independent code? Bytecode is machine independent code, it can be run on any
machine, you just need the JRE/JVM of corresponding machine. How does java bytecode work? The
image below shows the execution flow of a program in java.

In java language, a source program(.java file) is first compiled using a java compiler(javac).
After successful compilation, the bytecode(.class file) of that program is generated. When you run
the program using the java command, the java virtual machine(JVM) loads the .class file inside
memory and then gets converted(by a java interpreter) the instructions of .class file into machine
executable code and finally executes that machine code in order to generate the output of program.

WHAT IS WRITE ONCE RUN ANYWHERE (WORA) IN JAVA


Write Once Run Anywhere (WORA) is a feature in java which says write your program once and
then execute it anywhere (OS). In java it is attained with the help of the bytecode. Programmer needs
to write the program once and can execute the .class file generated from it anywhere and any number
of times. What is the use of bytecode in Java? The main reason to use bytecode in java is to make
java platform independent and secure. The bytecode of a program can be run on any machine which is
why java is called platform independent. Also, the use of bytecode makes java a secure language,
any external edit in bytecode of a program fails its execution. It's the bytecode of a program which is
used for running a java program. At runtime java virtual machine loads the bytecode of a program
inside the memory and converts into machine code and then executes that machine code.
ADVANTAGES OF BYTECODE
 Bytecode helps java to be a platform independence language. This is one of the main
advantages of bytecode in java.
 It helps java to be a secure programming language, as it can be run by java virtual machine
only. Also, at runtime bytecode is validated by bytecode verifier, any explicit edit in bytecode
fails it's execution.
 It makes java portable which helps to achieve the "Write once, run anywhere" feature. It
simply means you need to write the program once, and execute it anywhere (OS), all you need
to have is the .class of that program generated on any machine.
 Generally, the size of bytecode is less than the source code, thus it is easy and fast to
transport them over the network/internet.
 Another advantage of bytecode is, one can exchange it to others without disclosing the logic
implemented in the program.
BYTECODE VS MACHINE CODE
Bytecode is an intermediate code, it can’t be run directly on any machine (computer, laptop etc). It
must first be converted into machine code before it can be executed. In java, a java interpreter(part of
JVM) converts the bytecode into machine code. Machine code is a native or low-level code that
17 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
machine can understand and execute. They are generally binary or hexadecimal instructions which can
be executed directly by computers CPU.
DIFFERENCE BETWEEN SOURCE CODE AND BYTECODE
Source codes are code written inside a program by following the syntax of a programming language.
In java, code written inside a .java file are known as source codes. While bytecode is the code
which is generated after compiling the java program. In java, .class files are referred as bytecodes.
WHAT IS A BYTECODE VERIFIER IN JAVA?
Bytecode verifier is a special java runtime module or program which verifies the bytecode(.class)
before its run. Bytecode verifier traverses the bytecodes and checks if the bytecode loaded are
valid and it does not breach java's security restrictions. Think of a bytecode verifier as a gatekeeper
who ensures that the code passed to the java interpreter is in a correct state to be executed and can
run without fear of breaking the Java interpreter. As soon as you run a program, the classloader(part
of JVM) loads the .class file in memory. After that the bytecode verifier verifies if the bytecode is valid
or not. If it's valid then only it is passed to java interpreter for further execution.
WHAT IS A JDK JRE AND JVM?
The terms JDK JRE and JVM are used very often in java programming. Some programmers find it a
little difficult to understand what exactly they are, the differences in them and which one is needed for
their needs. JDK JRE and JVM are java software packages or part of the packages which
have tools and libraries needed to compile and execute java programs. Once you install java,
these tools and libraries get installed in your PC which allows you to compile and run java programs.
WHAT ARE TOOLS IN JAVA?
A tool is a program which helps programmer to accomplish a task for example javac, java, javap etc
are tools. javac is used to compile a program, java is used to run a program. If you install java, you
can see the tools(available as .exe files in windows) inside the bin folder of java installation.
SAMPLE JAVA CODE TO BE RUN IN A NOTEPAD
public class HelloWorld {
public static void main(String[] args) {
// Creates a reader instance which takes
// input from standard input - keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
// nextInt() reads the next integer from the keyboard
int number = reader.nextInt();
// println() prints the following line to the output screen
System.out.println("You entered: " + number);
}
}
A Java Code to print an Integer entered by a user
public class SwapNumbers {
18 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

public static void main(String[] args) {


float first = 1.20f, second = 2.45f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
float temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which has the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
A Java code to Swap two numbers using temporary
public class Main {
public static void main(String[] args) {
// year to be checked
int year = 1900;
boolean leap = false;
// if the year is divided by 4
if (year % 4 == 0) {
// if the year is century
if (year % 100 == 0) {
// if year is divided by 400
// then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}
// if the year is not century
else
leap = true;
}
else
leap = false;
19 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
A Java Code to Check if its a Leap Year
public class StringEg
{ public static void main(String[ ] args)
{ String s1 = "Computer Science";
int x = 307;
String s2 = s1 + " " + x;
String s3 = s2.substring(10,17);
String s4 = "is fun";
String s5 = s2 + s4;
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
System.out.println("s4: " + s4);
System.out.println("s5: " + s5);
//showing effect of precedence
x = 3;
int y = 5;
String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";
System.out.println("s6: " + s6);
System.out.println("s7: " + s7);
System.out.println("s8: " + s8);
}
}
A Java Code to show how a string works
public class EnhancedFor
{
public static void main(String[] args)
{ int[] list ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = sumListEnhanced(list);
System.out.println("Sum of elements in list: " + sum);
System.out.println("Original List");
printList(list);
System.out.println("Calling addOne");
addOne(list);
System.out.println("List after call to addOne");
20 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
printList(list);
System.out.println("Calling addOneError");
addOneError(list);
System.out.println("List after call to addOneError. Note elements of list did not change.");
printList(list);
}
// pre: list != null
// post: return sum of elements
// uses enhanced for loop
public static int sumListEnhanced(int[] list)
{ int total = 0;
for(int val : list)
{ total += val;
}
return total;
}
// pre: list != null
// post: return sum of elements
// use traditional for loop
public static int sumListOld(int[] list)
{ int total = 0;
for(int i = 0; i < list.length; i++)
{ total += list[i];
System.out.println( list[i] );
}
return total;
}

// pre: list != null


// post: none.
// The code appears to add one to every element in the list, but does not
public static void addOneError(int[ ] list)
{ for(int val : list)
{ val = val + 1;
}
}

// pre: list != null


// post: adds one to every element of list
public static void addOne(int[] list)
{ for(int i = 0; i < list.length; i++)
{ list[i]++;
}
}
21 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
public static void printList(int[] list)
{ System.out.println("index, value");
for(int i = 0; i < list.length; i++)
{ System.out.println(i + ", " + list[i]);
}
}
}

WHAT ARE LIBRARIES IN JAVA?


Libraries are a group of related classes and interfaces contained inside packages. In java,
libraries come as .jar files. If you extract a jar file, you see all the .class(compiled classes and
interfaces) files included in that jar.
WHAT IS A JDK IN JAVA?
JDK stands for java development kit. JDK helps programmers in development (compilation
and execution) of java programs. JDK a software package that contains tools and libraries needed
for compilation and execution of java programs. If you are a programmer then you must need to install
JDK first in your PC in order to start programming in java. For windows OS, this software generally
comes in the form of .exe or .zip file.

A JDK is a superset of JRE, which means it holds the JRE in itself. Apart from the JRE, it has tools
for developing, debugging, and monitoring java applications. Some of the significant tools
are java(Java application launcher), javac(java compiler), javap(java disassembler), javadoc(java
documentation tool) etc. JDK = JRE + Development tools(eg. javac, javap, java, javadoc etc)
Does JDK exist physically in a PC? Yes, JDK exists physically in computer. If java is installed in
your PC, you can see the jdk in java installation directory. In windows OS, by default it get's installed
in C: directory as given in below image.
22 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Can we run a java program without a JDK? Yes, we can run a program without JDK if we have
already compiled the program. If it’s not compiled, then we can’t run it without a JDK since our java
compiler(javac) is in a JDK, not in a JRE. A compiled program(.class file) can be run with JRE only.

WHAT IS JRE IN JAVA?


JRE stands for java runtime environment. it provides a runtime environment to your program for
it's execution. As soon as you start running your program using the java command, the job of a JRE
starts and it ends when either the program ran successfully or a error is thrown. JRE is also a software
package which has JVM, runtime libraries and other supporting files needed to run a program.
JRE does not have tools like javac, javap etc but it has tools like java, javaw etc since they are
needed to run java programs. For windows OS, a software comes in the form of .exe or .tar file. JRE is
a superset of JVM, as it contains JVM in itself. At runtime, JVM loads the required runtime libraries and
files of JRE in memory in order to execute the program and generate the output.
JRE = JVM + runtime libraries(contains packages like util, math, lang etc.)+ runtime files
Does JRE physically exist? Yes, JRE also exists physically in a PC. If java is installed in a PC, you
can see the JRE in the java installation directory. It exists inside the JDK folder.
WHAT IS JVM IN JAVA
JVM stands for java virtual machine, a virtual machine which loads and executes java programs in
memory. When you run a program by using java command, a java virtual machine is created which
has some default size of memory available for loading and executing classes, objects, variables etc
of a program. The JVM loads your class(program) and other required classes and libraries
as well which are needed to execute the program. It's a virtual machine because you cannot see
this in your computer. Also, it can execute only java programs and applications. JVM is not a separate
software package, instead it comes as part of JRE package. If you have installed JDK or JRE then you
don't have to do anything else for JVM. it will be there. Let's see some of the tasks performed by JVM:
 Loads code - Loads .class files in memory.
 Verifies code - Verifies the bytecode.
 Interprets code - Converts bytecode into machine specific code.
 Provides runtime environment - Makes availability of dependent classes and libraries.
 Executes code - Executes the code and generate the output.
 Memory management - Manages memory for classes, objects etc. by using garbage collection.
IS JVM PLATFORM INDEPENDENT?
23 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
No, JVM is platform dependent. There are different JVM implementations for different OSs(windows,
linux, MacOs etc) from different vendors. JVM along with bytecode makes java as WORA(write once,
run anywhere) language.
DIFFERENCE BETWEEN JDK JRE AND JVM

JDK JRE JVM

JDK stands for java JRE stands for java runtime JVM stand for java virtual
development kit. environment. machine.
JVM is not a separate software
JDK is a software package. JRE is also a software package.
package, it's part of JRE.
Using JDK you can do both, JVM is part of JRE, responsible
Using JRE you can do only
compilation and execution of for execution of your java
execution of java programs.
java programs. programs.
JDK exists physically in your JRE also exists physically in JVM does not exist physically in
computer. your computer. your computer.
You can download and install JRE can also be downloaded
JVM comes as part of JRE.
JDK in your computer. and installed in your computer.
JRE is a subset of JDK but
JDK is a superset of JRE. JVM is a subset of JRE.
superset of JVM.
JDK contains tools like javac, JRE contains runtime tools JVM doesn't contains any such
javap, java, javadoc etc. like java, javaw etc. tools.

BASIC EXAMPLE PROGRAMS IN JAVA


Here are some basic examples of java programs, especially for beginners to get some more idea about
execution flow in java programs. The programs given below demonstrates the execution flow of java
programs.
class FirstProgramFlow {
public static void main(String [] args) {
System.out.println("first ");
System.out.print("second ");
System.out.println("third ");
}
}
As you can see, the program executes from top to bottom starting from main method. It executes
first line then moves to second line, executes second line then move to third line and so on.
WHAT IS THE DIFFERENCE BETWEEN PRINT AND PRINTLN IN JAVA?
24 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
println("...") method prints a string in it and moves the execution pointer to the new line, while
print("...") method prints the string inside it and keeps the pointer in same line. This program will give
you more idea about execution flow in java.
class SecondProgramFlow {
public static void main(String [] args) {
// calling firstMethod
firstMethod();
System.out.println("main method");
}
public static void firstMethod() {
System.out.println("first method");
// calling secondMethod and assigning return value in i
int i = secondMethod();
System.out.println("After second method call, i = "+i);
}
public static int secondMethod() {
System.out.println("second method");
return 1;
}
}
Once a method is called, it finishes all its statement unless a return or method call statement is
encountered. If a return statement is encountered, the execution moves back to the line from where
this method was called and if a method call is encountered, the execution moves into the new method.
WHAT IS COMMAND LINE ARGUMENTS IN JAVA
A command line argument is an argument passed onto a program while running that program
using java command. The argument gets stored in the args (the name can be different) parameter
of the main method. You can access your argument using args parameter inside main method. E.g. if
you want to pass a command line argument "firstArgument" to a program MyFirstProgram.java given
below, you need to run the program using java command like below:
java MyFirstProgram firstArgument
Here firstArgument is the argument passed to MyFirstProgram and it’s stored in the args variable
of main method. Anything that is passed after the class name in java command acts as command line
argument and can be accessed using args variable.
WHAT IS A VARIABLE?
Variables in computer are memory locations used to store data of a particular data type. Think of
variable as a “Bucket” or “Envelope” where you can store data. This bucket has a name called
as variable name. The information stored in a bucket can be accessed later in program by it's name.
They are called variables because the data stored in it can be changed. Basic syntax of declaring a
variable in java is:
Data_Type variable_name = value;
25 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

In place of the Data_Type you specify the data type of the variable, after the name of the variable
and then the variable value at right side of the = operator with a semicolon(;) at the end of the
declaration. For example:
int age = 20; // variable name age with data type as int and value as 20

Now let's understand the different components of a variable declaration:


 Data_Type of variable - Mandatory
 Name of variable - Mandatory
 Value of variable - Optional
●Each variable must have a Data Type, it can be a primitive or a non-primitive data type. The data
type of a variable represents what type of data that variable can store. E.g. int data type can store
integer type values like 10, 20, 1000 etc while float data type can store float type values like 1.2, 10.5,
0.25 etc.
●Every variable must also have a Name. The name of a variable is used to refer that variable value
inside the program. The name of a variable must be unique. There are some rules and convention for
writing variable names, you will get the detail about this in naming convention for identifiers section.
●Every variable will also have a value, either it is given by programmer or a default value is assigned
by java as per it's data type. So, if you declare a variable like below java will assign a default value.
int num1; Here we have not assigned any value to variable num1, java assigns a default value which
is 0 for int data type.
VARIABLE DECLARATION AND INITIALIZATION IN JAVA
Declaration and initialization of variable are terms used often with variables. Declaration means
declaring or creating a variable while Initialization means assigning some value to that variable.
int speed; // Declaring or creating a variable name speed
speed = 100; // Initializing variable speed with value as 100
int num1, num2; // Declaring variable num1 and num2
num1 = 10; num2 = 20 // Initializing variable num1 and num2
int count = 10; // Declaration and initialization together of variable count
double a= 10.5, b = 20.25; // Declaration and initialization together of variable a and b
WHAT IS DIFFERENCE BETWEEN DECLARATION AND INITIALIZATION?
26 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
In declaration we only tell the name and data type of the variable that we are going to create, we don't
specify any value to that variable. While in initialization we provide some value to the declared variable.
For example, int speed; is a declaration while speed = 100 is initialization.

VARIABLE PROGRAM IN JAVA


class VariableProgram {
public static void main(String [] args) {
// declaring single variable
int a = 20;
// declaring multiple variable
int b = 30, c = a, d;
d = a + b;
System.out.println("d = " +d);
double pi = 3.14159;
System.out.println("value of pi = " +pi);
boolean e = true, f = a>c;
System.out.println(“e = "+e+ "\nf = "+f);
}
}
The following are some of the common mistakes in declaring variables in java:
int a = 20 // missing semicolon(;) at the end. Correct is -> int a = 20;
int b c; // two variables must be separated by comma(,) if declared in same line. Correct is -> int b, c;
int d = 20.5; // Can't assign float value in int data type
int p, int q; // Correct is -> int p; int q; or int p, q;
int p = int q; // Right side of = operator must be an expression or value, not variable declaration
Variables are declared in diverse program places e.g., class, methods, constructors, blocks etc.
As per the declaration places, variables are divided in different types. We can use access modifiers
with variable declarations which decides the accessibility of variables in java.
VARIABLE TYPES IN JAVA WITH EXAMPLE
These notes explain different types of variables in java, differences between them and their allocations
in memory. They help beginners to use correct variable type for their need in programs. In java there
are three categories of variables:
1.Local variable 2.Instance variable 3.Static or Class variable
JAVA LOCAL VARIABLE
Variables defined in methods, constructors or blocks are called local variables. They
are created in memory(stack memory) when execution of that method, constructor or block starts
in which they are declared. These variables are accessible only within the method, constructor or block
in which they are created. Local variables must be initialized with some value before their use
otherwise compiler throws an error.
HOW TO DECLARE AND ACCESS LOCAL VARIABLE IN JAVA
27 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The declaration of local variable is same as normal variable, the only thing is that they are declared
in method, constructor or block. In other way if you have declared variables in method, constructor or
block they are basically the local variables in java. To access a local variable, you just have to use it's
name. The program below shows how to create and access local variables in java.
LOCAL VARIABLE PROGRAM IN JAVA
class LocalVariable {
public LocalVariable() {
int a = 10; // local variable a, created inside constructor
System.out.println("a = "+a);
}
{
int b = 30; // local variable b, created inside block
System.out.println("b = "+b);
}
public static void main(String [] args) {
int c = 20; // local variable c, created inside method
System.out.println("c = "+c);
// Constructor and block will be executed by below line
LocalVariable lv = new LocalVariable();
int d; // local variable d, created inside method
// Below code will throw error if uncommented, as d is not initialized.
// System.out.println("d = "+d);
}
}

When memory is allocated for local variables in Java? Memory for local variables is allocated as soon
as the method, constructor or block containing the variable is executed. What is a local variable default
value in Java? Local variables don't have any default values in java, they must be initialized before they
can be used.

JAVA INSTANCE VARIABLE


Variables defined inside a class but outside any method, constructor or block are known as instance
variable. Initialization of instance variable is not compulsory, if not initialized, these variables will have
default values as per their data type. Instance variables, belongs to the instance or object of
a class. Instance variables are created in memory(heap memory) as soon as an object of
the class holding the instance variable is created. Every object of a class has its own copy of the
instance variables, changes made to the variable value of one object doesn't reflect in other object.

HOW TO DECLARE AND ACCESS INSTANCE VARIABLE IN JAVA.


The declaration of an instance variable is same as normal variable, the only difference is that they are
declared inside class directly. if you declare variables inside a class directly, they are basically instance
variables. Instance variables are accessed using object name like objName.instanceVarName.
You can also access the instance variable directly as well, in this case java internally applies the object
28 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
name for you. The good practice is to always use the object name for accessing the instance variable.
The program below shows how to declare and access instance variables in java.
INSTANCE VARIABLE PROGRAM IN JAVA
class InstanceVariable {
int age = 20; // instance variable age, created inside class
String name = "Rahul"; // instance variable name, created inside class
public static void main(String [] args) {
InstanceVariable iv = new InstanceVariable();
System.out.println("Age = " +iv.age);
System.out.println("Name = " +iv.name);
}
}
CLASS VARIABLE IN JAVA
Variables defined inside a class(not inside a method, constructor or block) using static keyword
are known as static or class variables. Initialization of a class variable is also not compulsory, if
not initialized, these variables will have default values as per their data type. They are known as class
variables since they belong to a class, not objects. Class variables as the name suggests,
belongs to class and is common to all objects of that class. These variables are created in memory as
soon as the class containing the variable is loaded inside memory.
HOW TO DECLARE AND ACCESS CLASS VARIABLE IN JAVA
A declaration of a static or a class variable is similar to an instance variable, except that they are
declared along with the static keyword. Static variable can be accessed using the class name
as className.staticVarName or use any of the object instances like objName.staticVarName . The
program below shows how to declare and access class variable in java.

CLASS VARIABLE PROGRAM IN JAVA


class ClassVariable {
static String classVar = "Class variable Test"; // class variable classVar
public static void main(String [ ] args) {
System.out.println(ClassVariable.classVar);
}
}

DIFFERENCE BETWEEN LOCAL, INSTANCE AND STATIC VARIABLES IN JAVA

FEATURES LOCAL VARIABLE INSTANCE VARIABLE STATIC VARIABLE


29 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Declaration Inside a method, constructor, or Inside the class. Inside the class
point block. using static keyword.

Lifetime Created when method, Created when instance Created when the
constructor or block is entered or of class is created program starts.
executed. with new keyword.
Destroyed when the
Destroyed on exit of method, Destroyed when object program execution
constructor or block. is available for garbage completed.
collection.

Scope/Visibility Visible only in the method, Visible to all methods in Same as instance
constructor or block in which they the class. It could be variable
are declared. visible to other classes
as well according to it's
access modifier.

Initial value None. Must be assigned a value Default value as Same as instance
before it's use. per Data Type. 0 for variable.
integers, false for
booleans, or null for
object references etc.

Use of Access Access Can be used. Can be used


Modifier modifier(public, private, protected)
can not be used with local
variables

Access from Not possible, Local variable can Instance variables can Same as instance
outside be accessed within the method, be accessed outside variable. It can be
constructor or block in which they depending upon it's accessed using object
are declared. access modifier. It can or class name.
be accessed using
object of that class.
30 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Memory Area Stack memory. Heap memory Heap memory

Use Used for local computations Used when value of Generally used for
variable must be declaring constants
referenced by more
than one method

JAVA PROGRAM OF LOCAL, INSTANCE AND STATIC VARIABLE


class Student
{
static String college = "SUMVS"; // static or class variable college
int rollNo; // instance variable rollNo
String name; // instance variable name
public static void main(String [] args)
{
Student s1 = new Student(); // local variable s1
s1.rollNo = 1;
s1.name = "Ram";
Student s2 = new Student(); // local variable s2
s2.rollNo = 2;
s2.name = "Shyam";
s1.printDetail();
s2.printDetail();
int count = 2; // local variable count
System.out.println("Total students = "+ count);
}
void printDetail()
{
int count2 = 2; // local variable count2
System.out.println(rollNo +", "+ name+", "+ Student.college+", "+ count2);
}
}

MEMORY ALLOCATION FOR LOCAL, INSTANCE AND STATIC VARIABLES IN JAVA


The image below shows where the memory is allocated for the different types of java variables used in
above program. The variable count and count2 are local variables, rollNo and Name are instance
variables whereas college is a class variable.
31 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

CAN A LOCAL VARIABLE HAVE THE SAME NAME AS AN INSTANCE VARIABLE OR STATIC
VARIABLE? Yes, you can declare a local variable with same name as an instance or static variable.
When accessed within the local block, method or constructor, local variable will take precedence over
instance or static variable.
JAVA VARIABLE NAMING RULES AND CONVENTIONS
Identifiers are the names of variables, methods, classes, packages and interfaces. The
name of variable identifiers must be written according to the rules and conventions given by the
programming language. Rules are mandatory to follow while conventions are optional, but it's good
to follow them. Like every programming language, java has it's own set of rules and conventions that
we should follow while writing the identifiers name.
The rules and conventions for naming your variables in java can be summarized as follows :
 Every variable name should start with either alphabets, underscore ( _ ) or dollar ( $ )
symbol. It should not start with number or any other special symbols. But, the convention is to
always begin the variable names with a letter, not "$" or "_". Conventionally the dollar sign
should never be used at all. So variable names like age, _age, $age are valid names in java.
 Variable names are case-sensitive. Names like age, Age, aGe, agE are different variables.
These names can be used together in same program, but doing so is not a good practice.
 Spaces are not allowed in the variable names. For eg. int bike speed = 100; is not a valid
declaration. It should be like int bikespeed = 100; or int bike_speed = 100; etc.
 Other characters apart from first character can be alphabets, numbers, $, or _ characters. For
eg. user_age, a12$_ge, _$1age2 etc are valid names of variables.
 When choosing a name for your variables, the convention is to use full words instead of short
forms, doing so will make your code easier to read and understand. Names like age,
height and speed are easier to understand than using short forms like a, h and s.
 The variable name you choose must not be a keyword(reserved word) of java. Java has defined
some keywords like int, double, float, char, if, else etc. These keywords cannot be used as your
variable names. Refer java keyword table given below to see the list of all keywords in java.
 Variable name should always exist in the left-hand side of assignment operator. int height = 5 is
correct while 5 = int height is incorrect.
 One more convention is, if the name you choose consists of only one word, use that word in
lower case letters. If it consists of more than one word, use first letter of each subsequent word
32 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
as capital letter. The variable names like userName, minHeight and maxHeight are good
examples of this convention.

LIST OF JAVA KEYWORDS


Table below shows a list of all java keywords that programmers cannot use for naming their variables,
methods, classes etc.

The keywords const and goto are reserved, but they are not used. The words true, false, and null might
seem like keywords, but they are actually literals, you cannot use them as identifiers in your programs.
What is literal in java programming? Any constant value which can be assigned to the variable or can
be used in an expression is called literal/constant. For example 10, 20.5f, 'a', true, "RefreshJava" etc
are literals.How many keywords are there in Java? In java there are 50 keywords(reserved words).
Refer the table above to see all the keywords in java. Can keywords be used as variable names in
Java? No, you can't use keywords as your variable name in java, doing so will result in compilation
error. Can I use java keywords in upper case as my variable names? Yes you can definitely use, as
keywords in java are case-sensitive but that's not a good programming style. If you want you can use
them along with other words like intVal, floatVal, charValue, doubleVar etc are valid identifier names.
JAVA IDENTIFIER RULES PROGRAM
class NamingConvention {
public static void main(String [] args) {
byte $num1=20, _num2 = 10, num3$_ = 25;
System.out.println("$num1 = "+ $num1 +", _num2 = "+ _num2 +", num3$_ = "+ num3$_);
byte age=20, Age = 30, agE = 40;
System.out.println("age = "+ age +", Age = "+ Age +", agE = "+ agE);
int For = 15, If = 30, Byte = 50;
System.out.println("For = "+ For +", If = "+ If +", Byte = "+ Byte);
int bike_speed = 50;
System.out.println("bike_speed = "+ bike_speed);
int minSpeed = 10, maxSpeed = 80;
33 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("minSpeed = "+ minSpeed +", maxSpeed = "+ maxSpeed);
}
}
Following are some incorrect variable naming which will result in compile time error.
int 2num1 = 40, 12num = 10; // digits not allowed as first character
int @num = 40, &num = 10; // only $ and _ are allowed as first character
int bike speed = 30; // Space cannot be used in variable name
int byte = 20, float = 30, for = 40; // keywords cannot be used as variable names

PRIMITIVE AND NON-PRIMITIVE DATA TYPES IN JAVA


Data is simply an instruction, it could be 123, -125, 3.14, "hello" etc. A data type is classification of
these data. Data can be divided in different data types like integer number, float number, character etc.
In java there are basically two types of data types: Primitive Data Type & Non Primitive Data Type
PRIMITIVE DATA TYPE
Primitive data type deals on basic data like 123, -125, 3.14 etc. Primitive data types are predefined by
the java language itself. Considering size and type of data, java has defined eight types of primitive
data type.

Data types byte, short, int, long is also known as Integer data type because they can contain only
integer type values while data types float, double is also known as Floating point data type because
they are used to store float type values.
HOW DO YOU FIND THE RANGE OF INTEGER DATA TYPES IN JAVA?
The range of integer data type values is calculated as -(2n-1) to (2n-1)-1, where n is the number of bits
required. For example the byte data type requires 1 byte(8 bits). Therefore, the range of values that can
be stored in byte data type is -(28-1) to (28-1)-1 = -27 to (27) -1 = -128 to 127
34 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Primitive types are also called value types in java since variables of primitive data types directly
hold the values rather than the reference(address) of that value in memory. That is why if you access a
primitive type variable, you directly get value rather than the reference of that value in memory.
PRIMITIVE DATA TYPE PROGRAM IN JAVA
class PrimitiveDataTypeExample {
public static void main(String[] args) {
byte byteVar = 123;
short shortVar = 1234;
int intVar = 123456;
long longVar = 3124567891L; // Must end with l or L
float floatVar = 123.45f; // Must end with f or F
double doubleVar = 12345.6789d; // d or D is optional
double doubleVar2 = 125.67;
boolean booleanVar = true;
char charVar = 65; // code for A
char charVar2 = 'C';
// Some incorrect declaration
// long longVar2 = 34287; Must end with l or L
// float floatVar2 = 123.45; Must end with f or F
System.out.println("byteVar = "+ byteVar);
System.out.println("shortVar = "+ shortVar);
System.out.println("intVar = "+ intVar);
System.out.println("longVar = "+ longVar);
System.out.println("floatVar = "+ floatVar);
System.out.println("doubleVar = "+ doubleVar);
System.out.println("doubleVar2 = "+ doubleVar2);
System.out.println("booleanVar = "+ booleanVar);
System.out.println("charVar = "+ charVar);
System.out.println("charVar2 = "+ charVar2);
}
}

WHICH DATA TYPE IS BEST FOR STORING INTEGER NUMBERS?


It completely depends on an integer number. As a good programming style always prefer lower size
data type over higher size data type if the value that need to be stored comes within the range of that
data type. For eg. any value from range -128 to 127 can be stored in short, byte, int, long data type but
prefer short data type over others as it takes less space in memory.

NON PRIMITIVE DATA TYPE


Non-primitive data types are generally created by the programmer. In java every class or interface acts
like a data type. Classes, interfaces, arrays etc defined by java or by programmer is basically the
non-primitive data type. Non primitive data types are built using primitive data types, for example
classes with primitive variables. Variables of non-primitive data type don’t contain the value directly,
35 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
instead they contain a reference(address) to an object in memory. That is why non primitive types are
also called as reference types. If you access a non-primitive variable, it will return a reference not the
value. The objects of non-primitive type may contain any type of data, primitive or non-primitive. Except
primitive data type everything is non-primitive data type in java. If I create a class MyFirstProgram,
would it be a non-primitive data type? Yes, MyFirstProgram will be a non-primitive data type.
Is string a primitive data type in java? No, String is a non-primitive data type as it stores references.
Why String is not a primitive data type? Because String is a class defined in java language, it has it's
own methods to manipulate and operate over object of String class. Every class in java, whether it is
defined by java or by programmer is a non-primitive data type.
NON PRIMITIVE DATA TYPE PROGRAM IN JAVA
class NonPrimitiveDataTypeExample {
public static void main(String[] args) {
// String is a non primitive data type define in Java
String nonPrimStr = "String is a non primitive data type";
System.out.println("nonPrimStr = "+ nonPrimStr);
// Integer is a non primitive data type define in Java
Integer intVal = new Integer(10);
System.out.println("intVal = "+ intVal);
// This class itself is a non primitive data type
NonPrimitiveDataTypeExample np = new NonPrimitiveDataTypeExample();
System.out.println("np = "+ np.toString());
}
}
Note: The value of np variable in last line of output could be different in your case as it depends on
specific machine. What are examples of java non primitive data types? Any class or interface created
by you or already created in java are non-primitive data types. Some of the examples of non-primitive
data type in java are String, StringBuilder, Arrays, Integer, Character etc.
DIFFERENCE BETWEEN PRIMITIVE AND NON-PRIMITIVE DATA TYPES IN JAVA
Primitive data types are predefined by java itself while non primitive data types are the classes
or interfaces defined by the programmer or java. Variables of primitive type holds the values directly,
if you access a primitive type variable you get the value directly. Variables of non-primitive types
holds the references(address), if you access a non-primitive type variable you get a reference.
Primitive data types are also known as value types since the variable of such types holds the values
directly while non primitive data types are also known as reference types since variable of such
types holds the references, not the values. Every primitive type variable has a default value, if no value
is assigned whereas a non-primitive type variable points to null if no object is assigned. Non primitive
type variables can call methods of that type(class or interface) while it's not possible with primitive
variables.
WHAT IS OPERATOR IN JAVA
36 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
In computer programming languages, an operator is a special symbol which tells the computer to
perform specific operation on one, two or three operands and then return a result.

WHAT IS OPERAND IN JAVA?


An operand is simply a value on which the operation is performed. This value can be in the form of
constant, variable, expression or any method which returns a value. E.g. in expression 2+3, 2 and 3 are
operands and + is an operator that performs addition operation. Also in expression a+b, a and b are
operands and + is an operator.

WHAT IS AN EXPRESSION IN JAVA?


An expression is a construct made up of variables, operators and method invocations, these
expressions are constructed as per the syntax of the programming language and evaluates to a single
value. For example a+b, a+b*c, a = 10, c = a + b, a > b, sqrt(4), (a+b)*(c-d) etc. An expression may
contain sub-expressions within it.
DIFFERENT TYPES OF OPERATORS IN JAVA
There are following types of operators in java, you can refer the specific section of these operator types
to see the details like what all operators are, what they do and their example programs.
●Assignment operator (=) ●Arithmetic Operators (+, -, *, /, %)
●Unary Operators (+, -, ++, --, !) ●Relational Operators (==, !=, >, >=, <, <=)
●Conditional Operators (&&, ||, ?:) ●Bitwise Operators (~, &, ^, |)
●Bit Shift Operators (<<, >>, >>>)
Operators can also be categorized by the number of operands they operate on. Most operator requires
one or two operands except ternary operator which requires three operands. So we can categorize
above operators in three types as well: UNARY OPERATOR, BINARY OPERATOR TERNARY OPERATOR
WHAT IS UNARY OPERATOR IN JAVA?
An operator which operates on one operand is known as unary operator. For example +, -,
++ etc are unary operators, usage example +2, -3, ++a etc.
WHAT IS BINARY OPERATOR IN JAVA?
An operator which operates on two operands is known as binary operator. For example +, -,
* etc are binary operators, usage example 2+3, 5-3, a*b etc.
WHAT IS TERNARY OPERATOR IN JAVA?
An operator which operates on three operands is known as ternary operator. There is only one
ternary operator in java which is ?:, also known as if then else operator.
JAVA OPERATORS LIST
The table below shows the list of all operators in java which you can use in your programs. For this
table let's assume we have operands or variables a, b and c.
OPERATOR
OPERATOR NAME EXAMPLE TYPE OF
SYMBOL
37 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

= Assignment operator a = b; Assignment Operator

+ Additive operator a+b


- Subtraction operator a-b
* Multiplication operator a*b Arithmetic Operator

/ Division operator a/b


% Remainder or Modulo operator a%b
+ Unary plus operator +a, +5
- Unary minus operator -a, -3
++ Increment operator a++, ++a Unary Operator

-- Decrement operator a--, --a


! Logical complement operator !(a>b)
== Equal to operator a==b
!= Not equal to operator a!=b
> Greater than operator a>b
Relational Operator
>= Greater than or equal to operator a>=b
< Less than operator a<b
<= Less than or equal to operator a<=b
&& Conditional-AND operator (a==1 && b==5)
|| Conditional-OR operator (a==1 || b==5) Conditional Operator

?: Ternary operator c = a>b ? a : b


Unary bitwise complement
~ operator ~a
Bitwise Operator

& Bitwise AND a&b


38 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

^ Bitwise exclusive OR operator a^b


| Bitwise inclusive OR operator a|b
<< Signed left shift operator a << 2
>> Signed right shift operator a >> 2 Bit Shift Operator

>>> Unsigned right shift operator a >>> 2

Note : Apart from above operators, the instanceof keyword in java is also considered as an operator. It
compares an object to a specified type(class).Note : Spaces are not allowed inside multi-
character(eg. &&, >=, == etc) operators. For example a > = b, a = = b, a & & b etc are incorrect and will
result in compilation error.
HOW MANY OPERATORS DOES JAVA HAVE?
There are 28 operators in java including the instanceof operator.
If an expression has many operators, then it must be evaluated as per the operator precedence in java.
OPERATOR PRECEDENCE IN JAVA WITH EXAMPLE
When we solve an expression with many operators, we follow some rules. E.g. an expression 2+3*4,
we do multiplication first before addition since the multiplication operator has higher precedence
than addition operator. The same applies in java. In java, operator precedence is a rule that tells
us the precedence of different operators. Operators with higher precedence are evaluated before
those operators with lower precedence. E.g., in an expression a+b*c, the operator * will be evaluated
before + operator, since the operator * has higher precedence than + operator. Table below shows
the precedence of operators in decreasing order,

JAVA OPERATOR PRECEDENCE TABLE


39 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

A programmer should remember bellow rules while evaluating an expression in java.


 The operands of operators are evaluated from left to right. For example, in expression ++a + b--
, the operand ++a is evaluated first then b-- is evaluated.
 Every operand of an operator (except the conditional operators &&, ||, and ? :) are evaluated
completely before any part of the operation itself is performed. For example in expression ++a +
b--, the addition operation will take place only after ++a and b-- is evaluated.
 The left-hand operand of a binary operator are evaluated completely before any part of the right-
hand operand is evaluated.
 Order of evaluation given by parenthesis () get's preference over operator precedence.
 The prefix version of ++ or -- evaluates/uses the incremented value in an expression while
postfix version of ++ or -- evaluates the current value, then increases/decreases the operand
value.
 All binary operators are evaluated from left to right except assignment operator.
40 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

What changes the precedence of the operators in Java? Parentheses "( )" are used to alter the
order of evaluation. E.g. in an expression a+b*c, if you want the addition operation to take place first,
then rewrite the expression as (a+b)*c.
Java Program of Operator Precedence
class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
System.out.println("5 + 2 * 3 - 1 = " +result);
result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);
result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
System.out.println("result = " +result);
}
}
1.ASSIGNMENT OPERATOR IN JAVA WITH EXAMPLE
Assignment operator is one of the simplest and most used operators in java programming language.
As the name itself suggests, the assignment operator is used to assign value inside a variable. In java
we can divide assignment operator in two types:
 Assignment operator or simple assignment operator
 Compound assignment operators
WHAT IS ASSIGNMENT OPERATOR IN JAVA
The = operator in java is known as assignment or simple assignment operator. It assigns the value on
its right side to the operand(variable) on its left side. For example:
int a = 10; // value 10 is assigned in variable a
double d = 20.25; // value 20.25 is assigned in variable d
char c = 'A'; // Character A is assigned in variable c
a = 20; // variable a is reassigned with value 20
The left-hand side of an assignment operator must be a variable while the right side of it should be a
value which can be in the form of a constant value, a variable name, an expression, a method call
returning a compatible value or a combination of these.
int a = 10, b = 20; // right side can be a constant value
int c = a; // right side can be a variable
int d = a+b; // right side can be an expression
int e = sum(a,b) // right side can be a method(sum) call
41 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// Following are incorrect declarations
a + b = 20; // Left side of = operator can't be an expression
1 = a; // Left side of = operator must be a variable
A value at right side of assignment operator must be compatible with the data type of left side variable,
otherwise compiler will throw compilation error. Following are incorrect assignment:
int a = 2.5; // value 10.5 can't be assigned in int variable
char c = 2.5; // value 2.5 can't be assigned in char variable
Another important thing about assignment operator is that, it is evaluated from right to left. If there is
an expression at right side of assignment operator, it is evaluated first then the resulted value is
assigned in left side variable.
int a = 10, b = 20, c = 30;
int x = a + b + c; // value of x will be 60
a = b = c; // value of a and b will be 30
Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted
value(60) is assigned into x. Similarly in statement a = b = c, first the value of c which is 30 is assigned
into b and then the value of b which is now 30 is assigned into a. A variable on the left side of an
assignment operator can also be a non-primitive variable. E.g. if we have a class MyFirstProgram, we
can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.
MyFirstProgram mfp = new MyFirstProgram();
Is == an assignment operator ?
No, it's not an assignment operator, it's a relational operator used to compare two values. Is
assignment operator a binary operator. Yes, as it requires two operands.
ASSIGNMENT OPERATOR PROGRAM IN JAVA
class AssignmentOperator {
public static void main (String[] args) {
int a = 2;
int b = a;
int c = a + b;
int d = sum(a,b);
boolean e = a>b;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
static int sum(int x, int y) {
return x+y;
}
42 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
JAVA COMPOUND ASSIGNMENT OPERATORS
The assignment operator can be mixed or compound with other operators like addition, subtraction,
multiplication etc. We call such assignment operators as compound assignment operator. E.g.:
int a = 10, b = 20;
a += 10; // is same as a = a + 10; // += is a compound assignment
b *= 5; // is same as b = b * 5; // *= is a compound assignment
Here the statement a += 10; is a short version of a = a + 10; the operator += is addition compound
assignment operator. Also, b *= 5; is short version of b = b * 5; the operator *= is multiplication
compound assignment operator. The compound assignment can be in more complex form as well, like
below:
a -= a+b; // is same as a = a - (a+b);
b *= a*b+c; // is same as b = b * (a*b+c);

How many assignment operators are there in Java? Including simple and compound assignment
we have total 12 assignment operators in java as given in above table. What is shorthand operator in
Java? Shorthand operators are not new, they are just a shorter way to write something that is already
available in java language. E.g. the code a += 5 is shorter way to write a = a + 5, so += is a shorthand
operator. In java all compound assignment operators and the increment / decrement operators are
basically shorthand operators.
COMPOUND ASSIGNMENT OPERATOR PROGRAM IN JAVA
43 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class CompoundAssignmentOperator {
public static void main (String[] args) {
int a = 10;
a += 10;
int b = 100;
b -= 20;
int c = 3;
c *= 10;
short s = 200;
s &= 100;
short s2 = 100;
s2 ^= 10;
byte b2 = 127;
b2 >>= 3;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("s = " + s);
System.out.println("s2 = " + s2);
System.out.println("b2 = " + b2);
}
}
What is the difference between += and =+ in Java? An expression a += 1 will result as a = a + 1 while
the expression a =+ 1 will result as a = +1. The correct compound statement is +=, not =+, so do not
use the later one.

2.ARITHMETIC OPERATORS IN JAVA WITH EXAMPLES


Arithmetic operators perform arithmetic operations e.g. addition, subtraction, multiplication and
division. Table below shows the list of all arithmetic operators. Consider a and b as two operands or
variables.
44 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

The symbol " % " is also the part of arithmetic operator, it divides one operand by another operand and
returns the remainder as it's result. It is also known as modulo operator. The code below shows how to
use these operators in java.
int a = 10, b = 20;
int c = a + b; // value of c = 30
c = b - a; // c = 10
c = a * b; // c = 200
c = b / a; // c = 2
c = 15 % 2; // c = 1
Can we use spaces before and after arithmetic operators? Yes, that won't be a problem. For example
expressions 5+10; 5 + 10; 5 + 10; are same and will run without any error. Each operand in an
arithmetic operation can be a constant value, a variable/expression, a function call returning a
compatible value or a combination of all these.
int a = 10, b = 20;
int c = 5 + 10; // operands can be a constant value
c = a + b; // operands can be a variable/expression
c = (a - b) + c; // operands can be a variable/expression
c = a + sum(5,10); // operands can be a function call
The addition(+) operator in java is also used for string concatenation. Two strings in java can be
concatenated using + operator like below:
String s1 = "herbert", s2 = "java";
String s3 = s1 + s2; // s3 = "herbertjava"
Results of arithmetic operations mare assigned to a variable, not doing so results in compilation error.
int a = 10, b = 20;
a + b; // Compilation error, result must be assigned in a variable eg. a = a + b;
The operands in an arithmetic operation can be of different data types as well, except the boolean data
type. The result of such operation must be assigned in a compatible data type.
int a = 10, double b = 20.5;
double d = a + b; // d = 30.5
d = a * b; // d = 205
char c = 'a' + 5; // c = f
Arithmetic operators can also be combined with assignment operator to create a compound
assignment like below:
int a = 10, b = 20;
a += 10; // is same as a = a + 10; // += is addition compound assignment operator
b *= 5; // is same as b = b * 5; // *= is multiplication compound assignment operator
The arithmetic operations must be performed with primitive data type variables only. Performing
any arithmetic operations on non primitive data type variables will result as compilation error, except
one exception which is the addition operator which can be used with the String data type only for string
concatenation.
String s1 = "herbert", s2 = "java";
String s3 = s1 - s2; // Compilation error
45 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
s3 = s1 * s2; // Compilation error
s3 = s1 + s2; // s3 = "herbertjava"
How many arithmetic operators are there in java? Are 5 arithmetic operators in java, + - * / and %.
JAVA MODULO OR REMAINDER OPERATOR
The % operator in java is known as modulo or remainder operator. This operator divides one operand
by another operand and returns the remainder as it's result. E.g. in expression 8%3, 8 is divided
by 3 and the remainder 2 is returned as result.
int a = 10 % 3 // a = 1
a = 10 % 2; // a = 0
a = 23 % 7; // a = 2
The modulo operator can be used with other primitive data types as well except the boolean data type.
double a = 10.5 % 3; // a = 1.5
double b = 10.5 % 3.5; // b = 0.0
float f = 20.5f % 3.5f; // f = 3.0
ARITHMETIC OPERATORS PROGRAM IN JAVA
class ArithmeticOperator {
public static void main (String[] args) {
int num1 = 20, num2 = 10, result;
result = 5 + 10;
System.out.println("5 + 10 = " + result);
result = num1 + num2;
System.out.println(num1 + " + "+num2+" = " + result);
result = num1 + add(2,3);
System.out.println("result with method call = " + result);
result = num1 - num2;
System.out.println(num1 + " - "+num2+" = " + result);
result = num1*num2;
System.out.println(num1 + " * "+num2+" = " + result);
result = num1/num2;
System.out.println(num1 + " / "+num2+" = " + result);
result = num1 % 7;
System.out.println(num1 + " % 7 = " + result);
result += 2; // Equivalent to result = result+2;
System.out.println("result = " + result);
}
static int add (int a, int b) {
return a + b;
}
}
Modulo operator is also useful in some cases, for example using modulo operator we can check or
find, if a number is even or odd, the last digit of a number, if a number is divisible by another number
etc. The program below shows how we can check or find these things using modulo operator.
JAVA MODULO OPERATOR PROGRAM
46 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class ModuloOperator {
public static void main (String[] args) {
int num1 = 118, num2 = 3;
// Check if a number is even/odd
if(num1 % 2 == 0)
System.out.printf("%d is an even number %n", num1);
else
System.out.printf("%d is an odd number %n", + num1);
// To find the last digit of a number
int last_digit = num1 % 10;
System.out.printf("Last digit of number %d is %d %n", num1, last_digit);
// Check if a num1 is divisible by num2
if(num1 % 3 == 0)
System.out.printf("%d is divisible by %d", num1, num2);
else
System.out.printf("%d is not divisible by %d", num1, num2);
}
}

3 UNARY OPERATORS IN JAVA WITH EXAMPLES.


Unary simply means one, so unary operators are the operators which operates on only one operand.
These operators are also quite used by java programmers. The table below shows the list of all unary
operators in java. For this table let's assume we have an integer variable a and a boolean
variable isValid :

JAVA UNARY PLUS AND MINUS OPERATOR


Unary plus operator indicates that a number is positive. By default, numbers are positive, the number 2
and +2 are same, so it doesn't matter whether you have used or not used this operator with a variable /
value. The unary minus operator negates a variable/value, that means this operator makes a positive
number as negative and a negative number as positive. An operand in a unary plus and minus operator
can be a constant value, a variable, an expression or a function call returning a compatible value.
int a = +10, b = -20; // operand can be a constant value
int c = -a; // operand can be a variable
int d = -(a+b); // operand can be an expression
47 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
int e = -sum(a,b); // operand can be a method(sum) call
JAVA LOGICAL COMPLEMENT OPERATOR
The logical complement operator(!) inverts the boolean value, if the boolean value is true, it becomes
false and if it is false, it becomes true. The operand in logical complement operator must be a boolean
value, a boolean variable, a boolean expression or a method call returning a boolean value. The
operand cannot be a constant value.

Increment and decrement operators in Java


The unary increment(++) operator increments the value of a variable by 1 while unary decrement(--)
operator decrements the value of a variable by 1. For example a++ increases the value a by 1 and is
same as a = a + 1, similarly a-- decreases the value of a by 1 and is same as a = a - 1. Both these
operators can be used with a variable only, not with any constant value, expression or method calls.

A unary increment / decrement operator can be applied before(prefix) or after(postfix) the variable
name. Both versions, ++a and a++ will increase the value of a by one. The next section explains more
detail about both the operators.
PRE AND POST INCREMENT AND DECREMENT OPERATORS IN JAVA
If the unary ++ operator is used before the variable name, it is called pre-increment operator while if
it is used after the variable name, it is called post increment operator. Also, if the unary -- operator is
used before the variable name, it is called pre-decrement operator while if it is used after the variable
name, it is called post decrement operator. E.g. in code ++a; the operator ++ is a pre-increment
operator while in code a++; operator ++ is post increment operator, the same applies with -- operator
as well. In pre increment/decrement, the value of the variable is incremented/decremented first then it
is assigned or evaluated, that is why it is called pre-increment/decrement. While in post increment /
decrement the current value of a variable is assigned or evaluated, after that the increment / decrement
happens, that is why it is called post increment/decrement. Let's know this by the example below :
48 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

To understand it clearly let's see step by step how this expression is evaluated. Just remember in java
an expression is evaluated from left to right.

The diagram below demonstrates how the value of variable a is evaluated.

What are prefix and postfix operators in Java? The pre increment / decrement operator are also
known as prefix operators in java while the post increment / decrement operator is also known as
postfix operators in java. What is the difference between pre increment and post increment? As
mentioned above, in pre increment the value of the variable is increment first then it used or assigned
in an expression while in post increment the current value of the variable is used or assigned in an
expression then it is incremented.
JAVA PROGRAM OF UNARY OPERATORS
class UnaryOperator {
public static void main(String[] args) {
int result = +5;
49 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("result = "+result);
result--;
System.out.println("result = "+result);
result++;
System.out.println("result = "+result);
result = -result;
System.out.println("result = "+result);
int i = 5;
i++;
System.out.println("i = "+i); // prints 6
++i;
System.out.println("i = "+i); // prints 7
System.out.println("i = "+ ++i); // prints 8
System.out.println("i = "+ i++); // prints 8
System.out.println("i = "+i); // prints 9
System.out.println("i = "+ --i); // prints 8
boolean isValid = false;
System.out.println("isValid = "+ !isValid);
}
}
The program below demonstrates the pre and post increment/decrement operator in java, you
can evaluate the value of different expressions in this example by yourself first then match your result
with the output to see if you have understood it properly.
JAVA PROGRAM FOR INCREMENT AND DECREMENT OPERATORS

RELATIONAL AND CONDITIONAL OPERATORS IN JAVA


50 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Lets see the details about relational and conditional operators in java. We shall cover details like
what these operators are, how to use them, list of all relational/conditional operators and java programs
of these operators.
RELATIONAL OPERATORS IN JAVA
Relational operators are used to relate or compare if one operand is greater than, less than, equal to,
or not equal to another operand. Operators like >, >=, < etc are called as relational operators while
operator == is called as equality operator. All relational operators along with equality operator returns
either true or false. Table below shows the list of all relational operators in java.
List of Relational operators in Java

There can be spaces before and after all relational operator. Also remember that, in multi-character
relational operators like >=, <= ==, there should not be any space between the characters of the
operator. For example = =, > =, < = would result in compilation error.
51 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

All relational operators can be used with primitive data types only except equality(==) operator which
can be used with non primitive data types as well. The equality operators can be used to compare if
two objects have same references(address).

The result of a relational operator is always a boolean value that is true or false. So, they must be
assigned to a boolean type variable only, assigning in any other data type variable will result in
compilation error.
52 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
What is the difference between = and == operators in java? Operator = is an assignment
operator which is used to assign value in a variable while == is an equality operator which is used to
compare if two variables/values are equal or not.
CONDITIONAL OPERATORS IN JAVA
Following operators are conditional operators in java:

The result of conditional AND and conditional OR operators is also a boolean value which is true or
false. What is Logical AND and Logical OR operators in java? The conditional-AND (&&) and
conditional-OR (||) operators in java is also known as Logical AND(&&) and Logical OR(||) operators
respectively. Both these operators are also binary operators, since they operate on two operands /
expressions. The left and right expressions of these operators must be a boolean variable/value,
expression or a function returning a boolean value. The operands cannot be a constant value like 5, 10
etc.
int a = 10, b = 20, boolean b2 = true;
if(b2 && a > 5) // operand can be a boolean variable or expression
if(a > 5 || b > 20) // operands can be an expression
if(a > 5 && isValid()) // operands can be an expression or function returning a boolean value
if(5 && 10) // Incorrect, operands can not be a constant value.
The block below shows what would be the result of && and || operators when it's left and right
expressions/conditions returns true or false.
true && true => true; true || true => true;
true && false => false; true || false => true;
false && true => false; false || true => true;
false && false => false; false || false => false;
In conditional && and || operator the second expression is evaluated only if needed. For example if first
expression in && operator returns false, the second expression will not be evaluated because no matter
what is the result(true or false) of second expression, the && operator will return false. Similarly in case
of || operator if first expression returns true, the second expression will not be evaluated.
int a = 10, b = 20;
if(a > 12 && b > 15) // Here b > 15 won't be checked as a > 12 returns false
if(a > 5 || b > 20) // Here b > 20 won't be checked as a > 5 returns true
There should not be any space between the characters of conditional AND and OR operators. For
example & & or | | will result in compilation error.
int a = 10, b = 20;
if(a > 12 & & b > 15) // Incorrect, there should not be any space in &&
if(a > 5 | | b > 20) // Incorrect, there should not be any space in ||
These operators can also be repeated any number of times inside an expression and they can be
mixed as well.
53 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
int a = 10, b = 20;
if(a > 5 && a < 20 && b > 15) // returns true, as all conditions are true
if((a > 10 && a < 20) || b > 15) // returns true, as b > 15 returns true

JAVA TERNARY OPERATOR


The ternary operator( ?:) is another conditional operator in java. This operator is thought as a short
form of if-then-else statement. It is known as ternary operator since it uses three operands.
Line below shows how to use this operator.
variable = someCondition ? Expression1 : Expression2;
Here someCondition is a boolean expression that returns either true or false. You can read this
operator as "if someCondition is true, assign the value of Expression1 into the variable else assign the
value of Expression2 into the variable.
WHAT IS BOOLEAN EXPRESSION IN JAVA?
An expression which returns either true or false is known as boolean expression. For example a > b, a
== b, (a + b) < c etc are boolean expressions.
Here Expression1 and Expression2 can be a constant value, a variable or an expression like a+b,
a*b+c, a>b, "hello" etc. The value of these expressions must match with data type of the variable.
int a = 10, b = 20;
int result = a > b ? 5 : 1; // Expression can be a constant value
int result2 = a > b ? a : b; // Expression can be a variable
int result3 = a > b ? (a-b) : (b-a);
String str = (a == b) ? "Equal" : "Not Equal";
JAVA PROGRAM OF CONDITIONAL OPERATOR
class ConditionalOperator {
public static void main(String[] args) {
int num1 = 3, num2 = 5, num3 = 10;
if(num1 == 3 && num2 == 5)
System.out.println("num1 = 3 AND num2 = 5");
if(num1 > 0 && num2 > 1 && num3 >= 10)
System.out.println("num1 > 0 AND num2 > 1 and num3 >= 10");
if(num1 == 3 || num2 == 5)
System.out.println("num1 is 3 OR num2 is 5");
if((num1 > 0 || num2 > 1) && num3 >10)
System.out.println("Print me if condition is true");
int result = num1 < num2 ? num1 : num2;
String str = num1 == num2 ? "num1 and num2 is equal" : "num1 and num2 is not
equal";
System.out.println("result = "+result);
System.out.println("str = "+str);
}
}
54 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
JAVA BITWISE AND BIT SHIFT OPERATORS WITH EXAMPLES
Bitwise and Bit shift operators operates on bits(0 and 1). They operates on binary representation of
operands. These operators can be used with integer(byte, short, int and long) data type variables or
values only and they always returns a numerical value. Let's see these operator types one by one.
BITWISE OPERATORS IN JAVA
As the name itself suggests, bitwise operator performs operation bit by bit wise. Table below shows the
list of all bitwise operators in java. Consider a and b as two integer type variables.

All the bitwise operators except complement operator are binary operators. The bitwise complement
operator is a unary operator, as it needs only one operand to perform the operation. It belongs to
bitwise operator type because it works on bits.
Bitwise AND operator in Java
Bitwise AND(&) operator performs bitwise AND operation on corresponding bits of both the operands.
It returns 1 if both the bit's are 1 else it returns 0. For example & operation between two byte variable
with value as 53(00110101) and 79(01001111) will result in 5(00000101).

WHAT IS THE DIFFERENCE BETWEEN & AND && OPERATOR IN JAVA?


The & operator performs bitwise AND operation on bit representation of both operands and returns an
integer value while logical AND(&&) operator performs operation on two boolean expressions and
returns boolean value(true or false) as result.
Bitwise OR operator in Java
Bitwise OR(|) operator performs bitwise OR operation on corresponding bits of both the operands. It
returns 1 if any of the bit's is 1 else it returns 0. For example | operation between two byte variable with
value as 53(00110101) and 79(01001111) will result in 127(01111111).
55 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

What is the difference between bitwise OR(|) and logical OR(||) operator in java? The | operator
performs bitwise OR operation on bit representation of both operands and returns an integer value
while logical OR(||) operator performs operation on two boolean expressions and returns boolean
value(true or false) as result.

Bitwise Exclusive OR operator in Java


Bitwise XOR(^) operator performs bitwise exclusive OR operation on corresponding bits of both the
operands. It returns 1 if both bit's are different else it returns 0. For example XOR operation between
two byte variable with value as 53(00110101) and 79(01001111) will result in 122(01111010).

BITWISE COMPLEMENT OPERATOR


A unary bitwise complement operator ~ inverts a bit pattern of an operand. It converts 0 as 1
and 1 as 0. For example a byte data type contains 8 bits, using this operator with a byte variable with
value whose bit pattern is "00110101" would be changed as "11001010".

BITWISE OPERATOR PROGRAM IN JAVA


class BitwiseOperatorDemo {
public static void main(String[] args) {
byte num1 = 53;
byte num2 = 79;
int result;
result = num1 & num2;
System.out.println("num1 & num2 = " + result);
result = num1 | num2;
56 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("num1 | num2 = " + result);
result = num1 ^ num2;
System.out.println("num1 ^ num2 = " + result);
result = ~num1; /* 11001010(-54, 2's complement form) = ~00110101 */
System.out.println("~num1 = " + result );
}}
BIT SHIFT OPERATOR IN JAVA
As the name itself suggests, the bit shift operators shifts the bits of an operand to left or right depending
on the shift operator used. In bit shift operator, the bit pattern(operand) is given in left-side while the
number of positions to shift by is given in right side of the operator. All bit shift operators are binary
operators in java as they require two operands to operate. Table below shows the list of all bit shift
operators in java.

SIGNED LEFT SHIFT OPERATOR IN JAVA


The signed left shift operator "<<" shifts a bit pattern to the left by the number of positions given in
the right side of this operator. It places 0 on the right side for every shift. Java stores number's in 2's
complement notation, where the most significant bit(leftmost bit) is used for sign bit. In java, if sign bit
is 0, it means the number is positive and if it is 1, it means the number is negative. Using this operator
a negative number can become a positive number and vice-versa. If a 0 comes into sign bit after
shifting the bits of a negative number, then it becomes a positive number. Similarly if 1 comes into sign
bit after shifting the bits of a positive number, then it becomes a negative number. These conditions are
indications of underflow and overflow respectively.

SIGNED RIGHT SHIFT OPERATOR IN JAVA


The signed right shift operator ">>" shifts a bit pattern to the right by the number of positions given in
the right side of this operator. The signed right shift operator places 0(for +ve number) or 1(for -ve
number) in left side for every shift. That is why using this operator with a positive number will always be
positive while a negative number will always be negative.
57 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

UNSIGNED RIGHT SHIFT OPERATOR IN JAVA


The unsigned right shift operator ">>>" shifts a bit pattern to the right by the number of positions
given in the right side of this operator and places a 0 into the leftmost position in every shift, no matter
whether the number is negative or positive. That is why this operator always returns a positive number.

WHAT IS THE DIFFERENCE BETWEEN SIGNED AND UNSIGNED RIGHT SHIFT OPERATOR?
The only difference between signed and unsigned right shift operator is, signed right shift operator
places 0 or 1 into the leftmost position depending on whether the number is positive or negative while
the unsigned right shift operator always places 0, no matter the number is positive or negative. The
result of >>> operator is always a positive number while result of >> operator is positive for positive
numbers and negative for negative numbers.
BIT SHIFT OPERATORS PROGRAM IN JAVA
class BitShiftOperatorDemo {
public static void main(String[] args) {
byte num1 = 53;
byte num2 = -75;
byte result;
result = (byte)(num1 << 1); /* 01101010 = 00110101<<2 */
System.out.println("num1 << 1 = " + result);
result = (byte)(num1 << 2); /* 11010100 = 00110101<<2 */
System.out.println("num1 << 2 = " + result);
result = (byte)(num1 >> 2); /* 00001101 = 00110101>>2 */
System.out.println("num1 >> 2 = " + result);
result = (byte)(num1 >>> 2); /* 00001101 = 00110101>>>2 */
System.out.println("num1 >>> 2 = " + result);
}
}
58 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

OPERATOR PRECEDENCE IN JAVA


When we solve an expression containing multiple operators we follow some rules. For example in an
expression 2+3*4, we do the multiplication first before addition because the multiplication operator has
higher precedence than addition operator. The same applies in java. Operator precedence is a rule that
tells us the precedence of different operators. Operators with higher precedence are evaluated before
operators with lower precedence. For example in expression a+b*c, the operator * will be evaluated
before + operator, because operator * has higher precedence than + operator.
Table bellow shows the precedence of operators in decreasing order, the operators appearing first in
table have higher precedence than operators appearing later. Operators appearing in same row of
table have equal precedence. When operators of equal precedence appear in the same expression, a
rule governs the evaluation order which says, all binary operators except for the assignment operator
are evaluated from left to right while assignment operator is evaluated from right to left. For example in
expression 2+3-4, 2 and 3 is added first then 4 is subtracted from it. Consider a and b as two operands
for the examples given in below table.
JAVA OPERATOR PRECEDENCE TABLE

OPERATORS PRECEDENCE EXAMPLE

Postfix expr++ expr-- a++ , a--

Unary ++expr --expr +expr -expr ~ ! ++a , --a , !a

Multiplicative */% a*b , a/b , a%b

Additive +- a+b , a-b

Shift << >> >>> a<<2 , a>>1

Relational < > <= >= instanceof a<2 , a>1

Equality == != a==b , a!=b


59 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Bitwise AND & a&b

Bitwise
exclusive OR
^ a^b

Bitwise inclusive
| a|b
OR

Logical AND && a&&b

Logical OR || a||b

Ternary ? : a = a>2 ? a : b

= += -= *= /= %= &= ^= |= a=b, a+=b, a/=b,


Assignment
<<= >>= >>>= a>>=2

Which operator has highest precedence in java? The postfix operator(eg. a++, a--) has the highest
precedence in java. Which operator has the lowest precedence in java? Assignment operator and
its different forms has the lowest precedence in java.
A programmer should remember bellow rules while evaluating an expression in java.
 The operands of operators are evaluated from left to right. For example in expression ++a + b--,
the operand ++a is evaluated first then b-- is evaluated.
 Every operand of an operator (except the conditional operators &&, ||, and ? :) are evaluated
completely before any part of the operation itself is performed. For example in expression ++a +
b--, the addition operation will take place only after ++a and b-- is evaluated.
 The left-hand operand of a binary operator are evaluated completely before any part of the right-
hand operand is evaluated.
 Order of evaluation given by parenthesis () get's preference over operator precedence.
 The prefix version of ++ or -- evaluates/uses the incremented value in an expression while
postfix version of ++ or -- evaluates the current value, then increases/decreases the operand
value.
 All binary operators are evaluated from left to right except assignment operator.
JAVA PROGRAM OF OPERATOR PRECEDENCE
60 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
System.out.println("5 + 2 * 3 - 1 = " +result);
result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);
result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
System.out.println("result = " +result);
}
}
NOTE: Nested parentheses in an expression are evaluated from the innermost parentheses to the
outermost parenthesis. If evaluation of the left-hand operand of a binary operator does not complete
properly, no part of the right-hand operand will be evaluated. Arguments in a method are evaluated
from left to right.
OVERFLOW, UNDERFLOW, WIDENING AND NARROWING IN JAVA
important concepts related with variables and data types like Overflow, Underflow, Widening and
Narrowing in java. These are some useful concepts that a programmer must be aware of.
OVERFLOW AND UNDERFLOW IN JAVA
Every data type in java has a range of values that can be assigned into the variable of that data type.
For example a byte data type variable can store values from -128(min) to 127(max), if you try to store a
value which is not in this range then overflow or underflow takes place.
byte b1 = (byte)128; // Overflow, since assigned value is greater than max range of byte data type
byte b2 = (byte)(-129); // Underflow, since assigned value is less than min range of byte data type
So overflow and underflow in java is a condition where an operation returns a result that crosses the
range of data type. If a value crosses the maximum prescribed size of a data type, it is called an
Overflow and if the value crosses the minimum prescribed size, it is called as Underflow. Java does
not throw any error or exception in any of the above cases. For example, an int is of 32 bit in Java, any
value that crosses 32 bits gets rolled over, which means after incrementing 1 on max value of
int(2147483647), the returned value will be -2147483648 which is minimum value of int . Also, after
decrementing 1 from -2147483648, the result will be 2147483647 which is maximum value of int.
For float data types(float and double), overflow will result in infinity while underflow results in 0.0
OVERFLOW AND UNDERFLOW PROGRAM IN JAVA
class OverflowAndUnderflow {
public static void main(String args[]) {
int intOverflow = 2147483647 + 1;
System.out.println("int overflowed value = "+ intOverflow);
int intUnderflow = -2147483648 - 1;
61 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("int underflowed value = "+ intUnderflow);
// Compilation error in below code, Constant values are checked at compile time for size limit
// int overflow = 2147483648; // Crossed maximum prescribed value for int data type
double doubleOverflow = 1e308 * 10;
System.out.println("double overflowed value = " + doubleOverflow);
double doubleUnderflow = 4.9e-324 / 100000;
System.out.println("double underflowed value = " + doubleUnderflow);
}
}

WHAT IS THE DIFFERENCE BETWEEN OVERFLOW AND UNDERFLOW IN JAVA?


Overflow is a condition where a value assigned to a variable crosses the maximum range of variable's
data type while underflow is the condition when the value that we assign to the variable crosses the
minimum range of variable's data type. Refer the example above to understand it via program. Does
overflow and underflow happens with Non-Primitive data types as well? No, as it doesn't contain value,
it contains only reference.
WIDENING AND NARROWING IN JAVA
Widening is a process in which a smaller data type value is converted to wider/larger data type value.
It is done by java itself that is why we call it implicit/automatic conversion. This is also known
as Upcasting. Automatic conversion of a subclass reference variable to a superclass reference
variable is also part of widening. Let's understand this by an example :
byte b1 = 20;
int i = b1;
Here in line 2 the byte variable(b1) value is converted into int data type value. This is basically called
widening and it is done by java itself. In java, the following type of conversion comes under widening :
Widening or Upcasting. It happens automatically(Implicit Conversion)
byte → short → char → int → long → float → double
Subclass to superclass conversion is also widening. Refer inheritance for
subclass/superclass
Subclass → Superclass
So if you assign a byte variable into short, char, int, long, float or double variable, it will be widening,
similarly assigning any short variable to char, int, long, float or double variable will also be widening and
so on. Some specific type of conversion given above may result in loss of precision, refer this link for
more information.
Is int to double widening? Yes, int to double is widening, since the size of double data type is greater
than int data type. Narrowing is just opposite of widening, it's a process in which a larger data type
value is converted to smaller data type value. This is done explicitly by the programmer. This is also
known as Downcasting. Explicit conversion of a superclass reference variable to a subclass reference
variable is also part of narrowing. Let's understand this by an example:
int i = 20;
byte b1 = (byte)i;
Here in line 2 the int variable(i) value is converted into byte data type value. This is basically called
narrowing and it is done explicitly as you can see I have used (byte) before variable i to convert
the int value into byte value. In java, following type of conversion basically comes under narrowing :
62 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Narrowing or Downcasting. It is done Explicitly by the programmer
double → float → long → int → char → short → byte
Superclass to subclass conversion is also narrowing.
Superclass → Subclass
So if you assign a double variable into float, long, int, char, short or byte variable, it will be narrowing,
similarly assigning any float variable to long, int, char, short or byte variable will also be narrowing and
so on. Narrowing conversion may lose information about the overall magnitude of a numeric value and
may also lose precision and range.
WIDENING AND NARROWING PROGRAM IN JAVA
class WideningAndNarrowing {
public static void main(String [] args) {
byte b=20;
int i=b; //byte to int widening
long l=b; //byte to long widening
double d=b; //byte to double widening
System.out.println("int value after widening : "+ i);
System.out.println("long value after widening : "+ l);
System.out.println("double value after widening : "+ d);
double d2 =20.5;
byte b2 = (byte)d2; //Narrowing double to byte
// long ll=d2; //compile time error, must be explicitly casted
long l2= (long)d2; //Narrowing double to long
float f2= (float)d2; //Narrowing double to float
System.out.println("Narrowing double value to byte : "+ b2);
System.out.println("Narrowing double value to long : "+ l2);
System.out.println("Narrowing double value to float : "+ f2);
}
}

What is the difference between widening and narrowing in java? In widening, the smaller data type
value is automatically converted/accommodated into larger data type. It happens automatically, that
means it is done by java itself. Narrowing is just opposite of widening, in this the larger data type value
is converted/accommodated in smaller data type. It needs to be done explicitly by the programmer
itself. What is type casting in java? Widening and narrowing is also known as type casting in java.

NOTE:Every time you run Overflow or underflow program, it will return same result. Every programming
language has it's own way of handling overflow and underflow conditions. Overflow and Underflow
deals on min/max values of data types while Widening and Narrowing deals on conversion of data type.
JAVA SIMPLE PROGRAMS
Let us write some basic programs like sum, average, circle and rectangle area etc in java. We shall
covers some key concepts about variables and data types, let's see the basic programs first followed
by the key concepts. The program below shows how to add two number and also shows how to find
63 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
average of two number. Similarly, you can develop your own program to add multiple numbers or find
the average of multiple numbers.

The program below shows how to multiply and divide two numbers in java. Be careful to use the correct
data type for storing the result of these operations. For example if division of two number results as a
decimal(eg. 20.25, 245.3 etc) type value, then store it in any of the float(float, double) data types.

Program below shows how to find area of a circle for given radius and area of rectangle for given length
and width.
64 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

SOME KEY POINTS ABOUT VARIABLES & DATA TYPES


Following are some of the key points that we should be aware of :
 By default, operations on integer variables (eg 5+15, 2+3*5) returns an int type value, if result
needs to be assigned into any other integer data type(eg. byte or short) variable, it must be
casted explicitly.
 The value in a char variable must be a single character, assigning multiple character will result
in compilation error.
 A boolean variable value must be given as true or false. it should not be
like 'true',"true", "false" et.
WHAT DO \n AND \t DO IN
JAVA PROGRAM?
The \n and \t are part of escape
sequence characters in java. In
java \n is used to insert a
newline in the text at this point
which means anything that you
write after \n in a string that will
be printed in a new line. While \t
is used to insert a tab in the text
at this point which means
anything written after \t in a
string will be printed after a tab
space. Refer the program below.
Along with \n and \t there are
several more escape sequence
characters in java.
CHPT 3:JAVA SELECTION OR CONTROL FLOW STATEMENTS
●IF and IF-ELSE
65 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Sometime as a you may want to execute one or more lines of code on basis of certain condition. For an
example, you may want that if a number num1 is greater than 0, print a message in console as "num1
is a positive number" by executing code System.out.println("num1 is a positive number"); To do
such scenarios, java provides a keyword known as if keyword which allows programmers to execute
a set of statements on certain condition. The if statement asks the computer to execute the instructions
given inside it's block only when the condition is true. The syntax of if keyword is:

if(condition) {
// java code to run inside if block
}
Here, a condition is a boolean expression which returns either true or false. If it returns true, the
code written inside if block gets executed and if it returns false, if block code will not be executed. The
boolean expressions could look like a>0, (a+b)>10, (a-b)>0 etc. These such expressions returns
either true or false.
WHAT IS AN IF BLOCK IN JAVA?
Everything that comes inside matching curly brackets { } after if keyword is the part of if statement
which is also called as if block in java.

Flowchart of if statement in Java If statement program in Java


Can I write many conditions in an if statement in java? Yes, you can use many conditions in if
statement by using logical AND(&&) and logical OR(||) operator. For example if(a > 10 && a <
20) is a valid boolean condition. Can we use if statement without curly braces? Yes, we can if we
have only one line of code for the if statement. if we don't use the curly braces after if statement,
the if condition will be applied only on the first line of code after if statement. Refer the program given
below. What happens if we put semicolon after if statement in Java? Though it compiles well,
66 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
the if statement will end up there itself. It means the if condition won't be applied on the statements
of if block, so these statements will be executed always. Refer the program given below:
class IfStatementUsage {
public static void main(String [] args) {
int a = 15, b = 10;
if(a > 0) // no curly brances
System.out.println("a > 0"); // if condition is applied on this line only
System.out.println("a = "+a);
if(a > 10 && a < 20)
System.out.println("a > 10 and < 20");
if(a > 0 || b > 0)
System.out.println("a > 0 or b > 0");
if(a > 0 && a < 20 && a > b)
System.out.println("a > 0 and < 20 and a > b");
if(a < 0); { // semicolon ends the if statement
System.out.println("Printed even the if condition is false");
}
}
}

●IF-ELSE (IF-THEN-ELSE)
You may want to execute a set of statements when a condition is true and if that is not true then you
want to execute some other set of statements. To do this, java offers the if then else statement.
The else block gets executed only when the condition in if statement is false. You can also read
this as "if something is true execute this else execute that". The syntax of if-then-else statement is:
if(condition) {
// java code to run inside if block
}
else {
// java code to run inside else block
}
IF ELSE FLOWCHART IN JAVA
IF ELSE PROGRAM
class IfElseStatement {
public static void main(String [] args) {
int num1 = 20, num2 = 15;
if(num1 == num2) {
System.out.println("num1 is equal to num2");
}
else {
System.out.println("num1 is not equal to num2");
}
System.out.println("code after if else block");
}
67 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
JAVA IF...ELSE IF CONDITION AND NESTED IF ELSE
You may want to use set of conditions where your first condition is false then only move to check
the next condition, and if that is also false then only move to check the next condition and so on. To do
such scenarios, java offers an if then else if statement. You can specify another state with the else
if statement which is run only when it's previous if or else if condition is false. If the else if condition
returns true, then the else if block is executed, if it returns false, computer will move to next else
if statement and evaluates the condition expression. This process goes on until any of the expression
returns true or all the else if statements are finished. Once any of the expression returns true, the code
inside that conditional statement is executed and all other condition statements after that are not
executed. If all conditional statements returns false, then the final else block(if any) will be executed.
The syntax of if-then-else if statement is:
if(condition) {
// code to be executed inside if block
}
else if(condition-1) {
// code to be executed inside this else if block
}
else if(condition-2) {
// code to be executed inside this else if block
}
.
.
.
else if(condition-N) {
// code to be executed inside this else if block
}
else {
// code to be executed inside else block, it's optional
}
The last else statement in if else-if ladder is optional, it's programmer's choice whether to use or not.
What is if-else if ladder statement in Java? The if.. else if statement given above is also called
as else if ladder which is mostly used when programmer wants to select one block of code among
many. In if.. else if ladder only one block(the one whose condition is true) of code is executed.

FLOWCHART OF IF...ELSE IF STATEMENT


68 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

IF .. ELSE IF PROGRAM IN JAVA


public class IfElseIfStatement {
public static void main(String [ ] args) {
int num1 = 20, num2 = 20;
if(num1 > num2) {
System.out.println("num1 is greater than num2");
}
else if(num1 == num2) {
System.out.println("num1 is equal to num2");
}
else {
System.out.println("num1 is less than num2");
}
System.out.println("code to be executed after else if ladder");
}
}
Can we use an if inside an else if in Java? Yes, we can use if statement inside else if statement, the
program will run successfully.

●NESTED IF-ELSE
Nested if-else statement in Java
Java allows you to place or put an if else block inside another if or else block. This is called a
nested if else statement. You can do any nesting level in a program which means you can put
if else block inside another if or else block up to any number of times. Inner if block is executed only
when outer if condition is true.
if(condition-1) { public class NestedIfElseStatement {
69 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// code to be executed inside first if block public static void main(String [] args) {
if(condition-2) { int num1 = 20;
// code to be executed inside second if block if(num1 >= 10) {
if(condition-3) { if(num1 < 100) {
// code to be executed inside third if block System.out.println("num1 is a double digit
.....
number");
.....
} }
else { else {
// code to be executed inside else block System.out.println("num1 is not a double digit
} number");
// code to be executed inside second if block }
} }
// code to be executed inside first if block else {
} System.out.println("num1 is less than 10");
else { }
if(condition-4) { System.out.println("code after nested if else block");
// code to be executed inside this if block }
}
}
}
NESTED IF ELSE PROGRAM IN JAVA

●FOR LOOP IN JAVA


for loop in Java
Usually, each line of code in a program is executed only once. Sometime we meet a situation where in
we want to repeat the execution of one or more line of code more than once. To do such requirements
java, offers looping statements. Looping statements ask a PC to repeat an execution of instructions
written inside these statements as far as a given condition is true. Below are java looping statements to
repeat the execution of statements in a program.
1.for loop. 2.while loop. 3.do while loop
We have to print digits from 1 to 10, one tactic could be, we can write a program which includes 10 print
statements, but what about if you need to print digits from 1 to 100 or more?. Java looping statements
can help you to accomplish the same in an easy way. Java for loop can be used to repeat execution of
statements for a fixed number of times or till a condition is true. The basic syntax of for loop is:
for(initialization; condition; increment/decrement)
{
// code to be executed inside for loop
}
All that is inside the ( ) after the for loop are non-compulsory expressions which do specific tasks.
Initialization expression is used to initialize variables, objects int i = 0, int count=10 etc.
Condition expression is used to test the condition, for example i<=10, count>0 etc. Increment /
decrement expression is used to change in variable or object value, for example i++, count-- etc. All
that comes inside matching curly brackets { } after for keyword is the part of for statement which is
also called as for block or for loop body.
HOW A FOR LOOP WORKS
70 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Initialization expression is the first expression executed as the loop begins and it is executed only
once. Then the condition expression is then evaluated, it's a boolean expression which returns
either true or false. If the condition expression returns as true, Statements inside the body of for loop is
executed. Then the increment/decrement expression is executed. Again, the condition expression is
evaluated. If it returns as true, again the statements inside the body of for loop is executed and then
increment/decrement expression is executed. This process goes on until the condition expression
returns as false. If the condition expression returns as false, for loop terminates.
CONTROL FLOW DIAGRAM OF FOR LOOP

class ForLoop
{
public static void main(String [] args)
{
for(int num=1; num<=10; num++)
{
System.out.println(num);
}
System.out.println("After the end of for
loop");
}
}

FOR LOOP PROGRAM IN JAVA


Can I use many variables in a for loop expressions? Yes you can use them in a for loop
expressions. For eg. for (int x=0, y=10; x<10 && y>0; x++, y-- ) is a valid java for loop. You can initialize
many variables of same data type only in initialization expression.
Infinite for loop in Java
What if a condition expression written in for loop statement always returns as true, the body of for loop
will keep executing, this is basically called as infinite for loop.
class InfiniteForLoop
{
public static void main(String [] args)
{
for(int num=1; num>0; num++)
{
System.out.println(num);
}
}
}
71 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
In above program, num>0 will always return true since num increases in every iteration. So, for loop
will keep running infinite/endless number of times. In for loop syntax, all the expressions are
optional, programmer can leave all of them as blank. If all of them leaved as blank, this again becomes
infinite for loop.
for( ; ; )
{
// code to be executed inside for loop
}

while loop in Java


while is another looping statement in java which allows us to repeat the execution of one or more
line of code as far as a condition is true. The computer keeps repeating the execution of statements
inside the while loop until the condition get's false. Programmer can also read this as " execute given
statements while something is true ". The syntax of while loop is :
while(condition)
{
// code to be executed inside while loop
}
Here the condition is a boolean expression which must return either true or false. If it returns true, the
code written inside the while block gets executed and if it returns false, the while block code won’t
be executed. Everything that comes inside matching curly brackets { } after while keyword is the part
of while statement which is also called as while block or while loop body.
CONTROL FLOW DIAGRAM OF WHILE LOOP
class WhileLoop
{
public static void main(String [] args)
{
int num = 1;
while(num<=10)
{
System.out.println(num);
num++;
}
System.out.println("After the end of while loop");
}
}

WHILE LOOP FLOW DIAGRAM while loop program in Java


Can I test multiple conditions in while statement? Yes, you can test multiple conditions using && or
|| operator. For e.g. while(a>0 && b<10) is a valid statement.
Infinite while loop
If the condition in while loop always returns as true, it becomes an infinite loop.
while(true)
72 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
{
// code to be executed inside while loop
}
do while loop in Java
do while is also a looping statement in java which allows to repeat the execution of one or more line
of code as far as a condition is true. It's so similar to the while loop, the only difference is that in do
while loop the statements inside do while block is executed first then condition expression is tested.
Therefore, code within the do block is always executed at least once. The syntax of do while loop is:
do
{
// code to be executed inside do while loop
}while(condition);
Note the semicolon(;) at the end of while statement, it's the part of declaration, programmer usually
misses this while using the do while loop in java, which results in syntax error.
class doWhileLoop
{
public static void main(String [] args)
{
int num = 1;
do
{
System.out.println(num);
num++;
} while(num<=5);
System.out.println("After the end of do while
loop");
}
}

while loop flow diagram do while loop program in Java


DIFFERENCE BETWEEN WHILE AND DO WHILE LOOP IN JAVA
In a while loop, the condition expression is checked first. If it’s true then a code inside the while loop
gets executed else it won't be run. In a do while loop, a code inside a loop is executed first then the
condition is checked. If the condition is true then the code inside aloop will be executed again otherwise
it won't be executed. So, in a do while loop the code inside the loop is executed at least once no matter
whether the condition is true or false which is not the case with while loop.
WHEN TO USE FOR, WHILE AND DO WHILE LOOP?
When you know that your code inside a loop should be executed a fixed number of times, use for loop.
When you are not sure about the repetition number, go for while loop, in a situation where you
want your code should be executed at least once, go for do while loop. Just for an example if you
want to print a table of a number, you should know that the iteration / repetition must be done 10 times,
73 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
use for loop and let us suppose you want to know how many times a random integer number is
divisible by to 2, go for while loop e.g. 256 is divisible 8 times, 12 is divisible 2 times only etc.
java nested loops
Java programming allows programmers to place one loop statement inside the body of another loop
statement. E.g., a for loop can be placed inside other for loop, a while loop can be placed inside
other while loop, a while loop can be place inside other for loop etc. The process of placing one loop
inside other loop is called nesting, and such loops are called as nested loops. The syntax of nested
loops are:
for(init; condition; inc/dec) while(condition1)
{ {
// outer loop code // outer loop code
for(init; condition; inc/dec) while(condition2)
{ {
// inner loop code // inner loop code
...... ......
...... ......
} }
// outer loop code // outer loop code
} }
Points about nested loops which will help you to understand more about nesting of loops.
 For every iteration of outer loop, inner loops complete all its iteration.
 A single loop can contain multiple loops at same level inside it.
 It's perfectly legal to place, for inside while, while inside for, for and while in the same level etc.
How many times I can do nesting of loops? The process of repeating the nesting can be done any
number of times.
class NestedForLoop class NestedWhileLoop
{ {
public static void main(String [] args) public static void main(String [] args)
{ {
for(int i=1;i<=3;i++) int i=0,j=0;
{ while(i<3)
System.out.println("Outer loop iteration i = "+i); {
for(int j=1;j<=3;j++) j=0;
{ while(j<3)
System.out.println("j = "+j); {
} System.out.print(i+""+j+ " ");
} j++;
} }
} System.out.println("");
i++;
}
}
}

Nested for loop in Java Nested while loop in Java


74 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

JAVA BREAK AND LABELED BREAK STATEMENT


Once the execution of a loop statement in a program starts, it keeps repeating the execution of loop
instructions as far as a given condition is true. Sometimes you may want to break the execution flow
in between. To break the execution flow of a loop, java provides a keyword called as break. It can be
used inside for, while, do while and switch statements only. As soon as a break statement encountered
in a loop, the execution of that loop gets terminated and the control flow jumps to the next statements
after the loop body. It’s mostly used along with conditional statements (if, else). The syntax of
break statement is:
break;
class BreakStatement
{
public static void main(String [] args)
{
for(int i=1; i<=5; i++)
{
if(i==4)
{
break;
}
System.out.println("i = "+i);
}
System.out.println("line after for loop");
}
}
break statement flow diagram break statement java program
When the value of i equals to 4, a break statement is run and control flow jumps to line
(System.out.println("line after for loop");) after the for loop, that is why value 4 and 5 is not printed.
What if I use break statement outside of loop or switch statement? Your program won't compile, it
will throw compilation error. Does break break Out all loops? No, It breaks only the current loop in
which it is used. If break statement is used inside any inner loop, it breaks only inner loop once it is
executed and the execution flow moves to the next line after inner loop. The outer loop will be executed
as usual.
class InnerLoopBreakStatement public static void main(String [] args)
{ {
public static void main(String [] args) firstLable:
{ for(int i=1;i<=3;i++)
for(int i=1; i<=3; i++) {
{ System.out.println("Outer loop i = "+i);
System.out.println("Outer loop i = "+i); secondLabel:
for(int j=1; j<=5; j++) for(int j=1;j<=5;j++)
{ {
if(j==3) if(i==2 && j==2)
{ {
break; break firstLable;
} }
System.out.println("j = "+j); System.out.println(" j = "+j);
75 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
} }
} }
System.out.println("line after outer for loop"); System.out.println("line after labeled break
} statement");
} }
}
Inner break loop labeled break statement
LABELED BREAK STATEMENT
A label is an identifier, from java SE 5 and above where we can declare a collection of statements
with a label identifier. Labeled break statement allow you to break the execution of label statements.

JAVA CONTINUE AND RETURN KEYWORDS


Sometime you may want a specific repetition of a loop, not to run few or all instructions of loop body. To
solve such needs, java provides continue keyword which allows you to skip the current iteration of
a loop and move to the next iteration. If you want to skip the execution of a code inside a loop for a
specific iteration or repetition, you use the continue statement. Only the code written after
the continue statement will be skipped, code before the continue statement will execute as usual for
that iteration. The continue statement can only be used inside for, while and do while loops of java. In
case of break statement, the control flow exits from the loop, but in case of continue statement, the
control flow will not be exited, only the current iteration of loop will be skipped. It is mostly used along
with conditional statements(if, else). The syntax of continue statement is:
continue;
class ContinueStatement
{
public static void main(String [] args)
{
for(int i=1; i<=5; i++)
{
if(i==4)
{
continue;
}
System.out.println("i = "+i);
}
System.out.println("line after for loop");
}
}
Continue statement flow diagram Continue statement Java Program
CONTROL FLOW DIAGRAM OF CONTINUE STATEMENT (ABOVE)
Once the continue statement is run inside for loop, the control flow moves back to for loop to evaluate
increment/decrement expression and then condition expression. If continue statement is executed
inside while and do while loop, the control flow jumps to condition expression for evaluation. As you can
see in above program, for i==4 the continue statement is executed which skips the current iteration and
move to the next iteration, that is why value i = 4 is not printed. If continue statement is used inside any
inner loop, it skips current iteration of inner loop only, the outer loop will be executed as usual.
76 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class LabeledContinueStatement
class InnerLoppContinueStatement {
{ public static void main(String [] args)
public static void main(String [] args) {
{ firstLable:
for(int i=1; i<=3; i++) for(int i=1;i<=3;i++)
{ {
System.out.println("Outer loop i = "+i); System.out.println("Outer loop i = "+i);
for(int j=1; j<=2; j++) secondLabel:
{ for(int j=1;j<=3;j++)
if(i==2) {
{ if(i==2)
continue; {
} continue firstLable;
System.out.println(" j = "+j); }
} System.out.println(" j = "+j);
} }
System.out.println("line after outer for loop"); }
} System.out.println("line after end of firstLable ");
} }
}
Inner loop continue statement labeled continue statement java program
LABELED CONTINUE STATEMENT
A Labeled continue statement allows programmer to skip the current iteration of that label.
Java Program of labeled continue statement
JAVA RETURN STATEMENT
As the return keyword itself suggest that it is used to return something. Java return statement is used to
return some value from a method. Once a return statement is run, the control flow is exited from current
method and returns to the calling method. The syntax of return statement is:
return expression;
return;
Who gets the value that is returned by method?The caller of a method. This value can be assigned
in some variable. The return statement given above has two forms:
 First that returns a value. To return a value, just place the value or expression
after return keyword. for eg. return 10, return a+b, return "refresh java" etc. The data type of the
returned value must match the return type of it's method declaration.
 Second that doesn't returns a value. To use, just place return keyword. When the return type of
method is declared as void, you can use this form of return as it doesn't return a value, or you
can also leave out to use return keyword for such methods.
JAVA PROGRAM OF RETURN STATEMENT
class ReturnStatement
{
public static void main(String [ ] args)
{
int sum = sum(10,20);
System.out.println("Sum = "+sum);
77 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
public static int sum(int a, int b)
{
return a+b;
}
}
In above program, a and b are integers, so a+b will also be an integer which is equivalent to return type
of method sum which is also an int.
NOTE: continue statement cannot be used outside of a loop, if used it will result in compile time error.
Use continue statement more precisely inside while and do while block, if not used precisely, it may
result as infinite loop. Ensure all letters of the continue keyword are small, cannot use Continue,
contiNue, CONTINUE etc. Ensure all letter of return keyword is small, cannot use Return, RETURN
etc. return keyword can be used anywhere inside method, but not outside method.
JAVA SWITCH CASE STATEMENT
Sometime you may need to select one block of code from many blocks of codes. To do this java gives
a switch statement which allows you to select a block from many blocks of statements. The
flowchart and syntax of switch statement is:
switch (expression)
{
case constant-1:
// code of case 1 block
break;
case constant-2:
// code of case 2 block
break;
case constant-3:
// code of case 3 block
break;
...
...
case constant-N:
// code of case N block
break;
default:
// code of default block
}

switch statement flowchart switch statement syntax


A switch statement evaluates it's expression and then selects the matching block. The working
of switch statement is very similar to if-else if ladder, which means the same thing can be achieved
using if-else if statement. Does the switch statement move directly to matching case? No, It starts
matching from top to bottom, the one that is matched, the code of that block is executed.
A programmer should remember below points while using switch statement in java.
78 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 The expression used in a switch statement should be of type byte, short, char, int,
enums and String(Java SE 7 and above). Wrapper classes Character, Byte, Short
and Integer can also be used.
 A programmer can have any number of case statements within a switch block.
Each case statement must be followed by the value to be compared to and a colon(:).
 Each case value must be unique. Duplicating a case value will result in compile time error.
 The type of value for every case must be same as data type of switch statement expression.
Each case value must be a constant or a literal. You cannot use variables, for
example case num1, case num2 are incorrect declaration.
 There can be multiple lines of code(statements) for each case.
 When a case is matched, all statements of that case will run until a break statement is reached.
 When a break statement is reached, the switch block terminates, and the flow of control jumps
to the next line after the switch block.
 Use of break statement is optional, If not used, all the cases(including codes inside it) after the
matching case will execute until a break statement or end of switch statement is reached.
 The default case in switch statement is optional. It can be used to perform any tasks when no
cases is matched.
SWITCH CASE PROGRAM IN JAVA
class SwitchStatement
{
public static void main(String [] args)
{
int dayNo = 4;
String dayName;
switch (dayNo)
{
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
79 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("day name = "+dayName);
}
}
NOTE: Conventionally you should use default statement in last, though it's not mandatory but prefer to
follow this. Keywords are case-sensitive, you cannot use like Switch, SWITCH, switcH etc. Every letter
should be small letter. return statement can also be used inside switch cases, once executed the flow
will be exited from the method itself. Expressions like a+b, a+b*c etc. can also be used in switch
statement.
JAVA PROGRAMS OF CONTROL FLOW STATEMENTS
Let see some basic useful programs as beginners. These programs use the control flow statements in
some-way. These programs will help us to build different logics for different types of programs. Let's
see the first program which shows how to find if a number is even or odd.
class EvenOddProgram
{
class NumberTable
public static void main(String [ ] args)
{
{
public static void main(String [ ] args)
int num1 = 22;
{
if(num1 % 2 == 0)
int num1 = 8;
{
for(int i=1; i<=10;i++)
System.out.println(num1+ " is an even number");
{
}
System.out.println(num1*i);
else
}
{
}
System.out.println(num1+ " is an odd number");
}
}
}
}
Java Program of even odd number Java code to print multiplication table of a number
class GreatestOfThreeNumber
{
public static void main(String [] args) class FindingGrade
{ {
int num1 = 40, num2 = 20, num3 = 50; public static void main(String [] args)
if(num1 > num2) {
{ int marks = 65;
if(num1 > num3) if(marks >= 80)
System.out.println("Greatest number = "+num1); System.out.println("A+ grade");
else else if(marks >= 60 && marks < 80)
80 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Greatest number = "+num3); System.out.println("A grade");
} else if(marks >= 40 && marks < 60)
else System.out.println("B grade");
{ else if(marks >= 30 && marks < 40)
if(num2 > num3) System.out.println("C grade");
System.out.println("Greatest number = "+num2); else
else System.out.println("D grade");
System.out.println("Greatest number = "+num3); }
} }
}
}
Java Program to find greatest of three number Java Program for finding a grade

A % returns a remainder. If a number is divisible by 2, it's an even number. 22 is divisible by 2, and


returns a remainder 0 which means 22 is an even number. Just change the num1 as 23, the output
will be "23 is an odd number." As a beginner you want to write a program which prints a multiplication
table of a number. Program above shows how to print multiplication table of a number, just change
the num1 as any other integer number, the program will display the table of that number.
Sometime you will need to write a program to find the greatest of three number, program below shows
how to find the greatest of three number. You can change the value of num1, num2, num3 the program
will print the greatest of all three numbers. This is one approach to find the greatest number, there
could be other approaches as well.

JAVA ARRAY’S INTRODUCTION


We all know that java provides primitive data types to store single values like 20, 100, 20.5 etc in
a variable. But what if you wany to store many values of the same data type like 20, 30, 40 or 10.5,
20.4, 30.6 etc in a single variable, one style could be, to create many variables and assign single
values in each variable. Another easy way is to use arrays provided by java. An array in java is a
container which allows us to store many values of same data type in one variable. The syntax of
declaring an array is:
dataType[ ] arrayName;
dataType arrayName[ ];
You can use any of the above two forms to declare an array in java. For example:
int[ ] intArray; // declares an array of integer with name as intArray
int intArray2[ ]; // declares an array of integer with name as intArray2
float[ ] floatArray; // declares an array of float with name as floatArray
char[ ] charArray; // declares an array of char with name as charArray
81 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The [ ] is used with the data types or array name suggests that it's an array. The data type of an array
can be primitive or non-primitive, while the name of the array is given by you. The name must follow
the rules and convention given in Identifier-naming-convention section. Arrays of primitive data types
stores values while arrays of non-primitive data types store object references.
WHICH APPROACH I SHOULD PREFER TO DECLARE AN ARRAY?
Though you can use any of the above form, it's good practice to use first one as it is more meaningful.
The code int[] intArray itself suggest that variable intArray is an int type array. Java convention also
discourage to use the second form which is int intArray[]. The code given below shows how to declare
an array of non primitive data type. Assuming that you have already created a class MyFirstProgram.
To declare an array of MyFirstProgram, use below syntax:
MyFirstProgram[]mfpArray; // declares an array of MyFirstProgram class with name
as mfpArray

HOW TO INITIALIZE ARRAY IN JAVA


Java arrays initializes array values in a continuous memory location where each memory
location is given an index. You can assign or access the value to that memory location using its index.
The index starts from 0 and goes as 0,1,2,3,4.... The first approach to create or initialize an array
in memory is by using new keyword. The code below initializes an array in memory with size as 5 and
then assigns values in it using its indexes.

int[] marks = new int[5];


marks[0] = 40; // initialize first element
marks[1] = 60; // initialize second element
marks[2] = 80; // initialize third element
marks[3] = 65; // initialize fourth element
marks[4] = 70; // initialize fifth or last element
// initializing in one line
int[] marks = new int[]{40,60,80,65,70};

Java Array Initialization

HOW TO ACCESS VALUES OF ARRAY


Each item in an array is called an element, and each element of array is accessed by its index. The
index of first element is 0.
marks[0] // To access element 40
marks[1] // To access element 60
marks[2] // To access element 80
marks[3] // To access element 65
marks[4] // To access element 70
Min or start index of an array = 0;
Max or last index of an array = length of array - 1;
WHAT IS LENGTH OR SIZE OF AN ARRAY?
82 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The maximum or total number of elements that can be assigned into the array is known as length
or size of an array. You can get the length of an array using the length property of array. The second
and shortcut approach to initialize an array in memory is by directly assigning array values into array
variable like below :
int[] intArray2 = {20,40,60}; // initializes an int array with size as 3
int[] intArray3 = {
20,30,40,
50,60,70,
80,90,100
}; // initializes an int array with size as 9
// Do not use comma (,) after last element.
The length of array in above declaration is determined by the number of values given inside the { } and
separated by comma (,). You can assign elements of array in one line or multiple line as seen above.
Can I increase the length or size of an array after initialization? No, once an array is created or
initialized, the length of array is fixed. You can’t increase or decrease length of the array after
initialization. For e.g. if you create any array of length 5 as int[] marks = new int[5]; You cannot access
or assign value at 5th index(marks[5]) which is 6th element, if you access marks[5], java will throw a
runtime exception.
You can also assign one array into another array like below. Just remember in this case if you make
any changes in element of one array, that will be reflected in other as well.
int[] intArray2 = {20,40,60};
int[] intArray3 = intArray2; // intArray3 refers intArray2
What if I don't assign a value to a particular index? If a programmer doesn't specify a value to a
particular index of an array, java will itself assign a value to that index as per the data type of array. For
eg. 0 for int, 0.0 for double, false for boolean etc. For non-primitive data type, it assigns null for that
index. Can I pass array from one method to other? Yes, You can pass array from one method to
other method as you pass normal variables.
ARRAY PROGRAM IN JAVA
class ArrayInJava
{
public static void main(String [] args)
{
int[] marks = new int[5];
marks[0] = 40;
marks[1] = 60;
marks[2] = 80;
marks[3] = 65;
marks[4] = 70;
System.out.println("Element at index 0 = "+marks[0]);
System.out.println("Element at index 1 = "+marks[1]);
System.out.println("Element at index 2 = "+marks[2]);
System.out.println("Element at index 3 = "+marks[3]);
83 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Element at index 4 = "+marks[4]);
// Accessing array elements using for loop;
System.out.println("Accessing array element using for loop ........");
for(int i=0; i<5; i++)
{
System.out.println("Element at index "+i+" = "+marks[i]);
}
}
}

Output:
Element at index 0 = 40

Element at index 1 = 60

Element at index 2 = 80

Element at index 3 = 65

Element at index 4 = 70

Accessing array element using for loop .........

Element at index 0 = 40

Element at index 1 = 60

Element at index 2 = 80

Element at index 3 = 65

Element at index 4 = 70
The program below calculates the average of given integer numbers of an array. It also shows how to
use the length property of array which returns the length of an array.
class ArrayDemo
{
public static void main(String [] args)
{
int[] numbers = {40,60,80,65,70};
double avgNumber;
int total = 0;
// finding sum of all numbers of array;
for(int i=0; i < numbers.length; i++)
{
total = total+numbers[i];
}
avgNumber = total/5;
System.out.println("Average of numbers of array = "+avgNumber);
}
84 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}

NOTE: Arrays with single [] brackets is also known as one dimensional array. Arrays discussed in this
section is single dimension arrays, for multidimensional arrays refer next section. Array elements starts
from index 0, not 1. If you access array variable name, java will return reference(address) of that
variable. Accessing any elements outside array index will throw ArrayIndexOutOfBoundsException at
runtime. A method can return an array as well to calling method.

JAVA MULTIDIMENSIONAL ARRAYS


In java you can define an array whose elements are itself an array. Are called multidimensional
array. A multidimensional array is an array of arrays which simply means the elements of such
arrays will itself be an array. They are of different types for example two dimensional(2D), three
dimensional(3D), four dimensional(4D) etc. We will see the two- and three-dimensional arrays.

JAVA TWO DIMENSIONAL (2D) ARRAYS


This is the simplest form of multidimensional array. A 2D array is an array of one-dimensional arrays
which means each element of two-dimensional array will be a single dimensional array. A 2D array has
two dimension which is also called as row and column of 2D array. This type of array has two indexes
row index and column index. You can access or assign value in 2D array using the combination of row
and column indexes. Row and column indexes start from 0. 2D array is similar to matrixes in
mathematics where we have rows and columns.
HOW TO DECLARE 2D ARRAYS
The syntax of declaring 2D array is:
DataType[][] arrayName;
Example:
int[][] intArray; // declares a 2D array of integer with name as intArray
double[][] doubleArray; // declares a 2D array of double with name as doubleArray
char[][] charArray; // declares a 2D array of char with name as charArray

The double brackets [ ][ ] indicates that it's a 2D array. You can use this bracket after the data type or
variable name as given in the previous section. The data type can be primitive or non-primitive while
the name of array is given as per the programmer's choice.
HOW TO INITIALIZE 2D ARRAYS
// First approach
int[][] matrix = new int[2][3];

matrix[0][0] = 10;
matrix[0][1] = 20;
matrix[0][2] = 30;
matrix[1][0] = 15;
matrix[1][1] = 80;
matrix[1][2] = 50;
85 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// 2nd approach
int[][] a = {{15,20,25,30},{20,30,40,50},{60,65,70,80}};
In first approach the value given in first bracket [ ] represents number of rows while value given
in second bracket [ ] represents number of columns. So in code new int[2][3], number of rows is 2
and number of column is 3. In second approach, each array inside the declaration represents a row
while elements inside each array represents the number of columns. So, the number of rows in 2nd
approach is 3 and number of columns is 4. Each array(rows) in second approach can have different
number of values(columns). E.g., The 1st array may have 4 elements, 2nd array may have 2 elements
and 3rd array have 3 elements. Such arrays are called jagged arrays. Following example represents
a jagged array.
int[][] a = {{15,20,25,30},{20,30},{60,65,70}};
Since a 2D array is an array of 1D arrays, you can think of the arrays given
in {{15,20,25,30},{20,30,40,50},{60,65,70,80}}; like below
{a[0],a[1],a[2]};
Here a[0], a[1], a[2] are arrays itself which points the corresponding arrays. Similarly in
declaration int[][] matrix = new int[2][3]; matrix[0] and matrix[1] will be an array. The image below
displays how 2D array can be represented in rows and columns.

To access values in 2D arrays, you use it's row and column indexes like a[0][0], a[0][1], a[0][2] and so
on. In above example a[0][0] will return 15, a[0][1] will return 20 and a[0][2] will return 25.
What is the length of 2D array? The length of 2D array is the total number of arrays declared inside it.
In other way the total number of rows inside a 2D array is the length of 2D array. For example in
declaration int[][] a = {{15,20,25,30},{20,30,40,50},{60,65,70,80}}; length is 3 while in declaration new
int[2][3] length is 2.
What is the total number of elements that can be stored in 2D array? To find the total number of
elements that can be stored in 2D arrays, you can multiply number of rows and columns. For example
in declaration int[][] matrix = new int[4][5], total number of elements that can be stored is 4x5 = 20.

2D ARRAY PROGRAM IN JAVA


class TwoDArray
86 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
{
public static void main(String [] args)
{
int[][] matrix = new int[2][2];
matrix[0][0] = 10;
matrix[0][1] = 20;
matrix[1][0] = 30;
matrix[1][1] = 40;
System.out.println("Element at index 00 = "+matrix[0][0]);
System.out.println("Element at index 01 = "+matrix[0][1]);
System.out.println("Element at index 10 = "+matrix[1][0]);
System.out.println("Element at index 11 = "+matrix[1][1]);
int[][] a = {{15,20,25},{20,30,40},{50,60,70}};
System.out.println("\nElement at index 00 = "+a[0][0]);
System.out.println("Element at index 01 = "+a[0][1]);
// Accessing array elements using for loop;
System.out.println("\nAccessing array element using for loop ........");
for(int i=0; i < a.length; i++)
{
for(int j=0; j < a[i].length; j++)
System.out.println("Element at index "+i+""+j+" = "+a[i][j]);
}
}
}

JAVA THREE DIMENSIONAL OR 3D ARRAYS


A three-dimensional array is an array of 2D arrays, which means each element in 3D array will be a 2D
array. Each element in this array is also accessed by it's indexes.
HOW TO DECLARE 3D ARRAYS
The syntax of declaring 3D array is:
DataType[][][] arrayName;
Examples:
int[][][] intArray; // declares a 3D array of integer with name as intArray
double[][][] doubleArray; // declares a 3D array of double with name as doubleArray
Every declaration in this array is same as 2D array except one more [] bracket. The triple [][][] indicates
that it's a 3D array.
HOW TO INITIALIZE 3D ARRAYS
// First approach
int[][][] matrix = new int[2][2][2];
matrix[0][0][0] = 10;
matrix[0][0][1] = 20;
87 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
matrix[0][1][0] = 30;
matrix[0][1][1] = 40;
matrix[1][0][0] = 80;
matrix[1][0][1] = 90;
matrix[1][1][0] = 15;
matrix[1][1][1] = 25;
// 2nd approach
int[][][] a = {{{15,20},{30,40}},{{25,50},{60,80}}};
What is the length of 3D array? The length of 3D array is the total number of 2D arrays declared
inside it. For example in declaration int[][][] a = {{{15,20},{30,40}},{{25,50},{60,80}}}; length is 2 while in
declaration new int[2][3][4] length will be 2.
What is the total number of elements that can be stored in 3D array? To find the total number of
elements that can be stored in 3D arrays, just multiply the values given in [] brackets. For example in
declaration int[][][] matrix = new int[4][5][2]; total number of elements that can be stored is 4x5x2 = 40.
3D ARRAY PROGRAM IN JAVA
class ThreeDArray
{
public static void main(String [] args)
{
int[ ][ ][ ] a = {{{15,20},{30,40}},{{25,50},{60,80}}};

System.out.println("Element at index 000 = "+a[0][0][0]);


System.out.println("Element at index 001 = "+a[0][0][1]);
// Accessing 3D array elements using for loop;
System.out.println("\nAccessing 3D array elements using for loop ........");
for(int i=0; i < a.length; i++)
{
for(int j=0; j < a[i].length; j++)
{
for(int k=0; k < a[i][j].length; k++)
System.out.println("Element at index "+i+""+j+""+k+" = "+a[i][j][k]);
} }
} }

JAVA FOR EACH LOOP


If you have to traverse(iterate) an array or collection elements using normal for loop, you may have
to write the for-loop expressions like initialization, condition, increment or decrement which is a bit
painful and sometimes wrong declaration may result as infinite loop. To simplify this, java offers another
looping statement known as for-each loop. The for-each loop is an enhanced form of normal for loop
which is used to traverse elements of arrays or collection. It was introduced in java 5 just to simplify
the traversing of arrays and collection elements. The Syntax of for-each loop is:
88 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
for(DataType item : array/collection variable )
{
// Code to be executed once for each element in array/collection.
}
Here item is the given variable name by a programmer while the data type of this variable should
be the same or compatible with data type of the array/collection variable. Array/collection variable is the
array or collection variable whose elements need to be traverse. You must read the colon(:) as "in",
so that the loop above is read as "for each item in array/collection variable".
What is collection in java? is a group of data structures(classes and interfaces). Variable of these
data structures can hold many elements like arrays do. E.g. ArrayList, LinkedList, HashSet, HashMap
etc are some of the collection data structures. Why it is called for-each loop? Since the loop iterates
through each element of array/collection. When should I prefer for-each loop over normal for loop?
When you just want to traverse each element of array/collection one by one.
FOR EACH LOOP PROGRAM IN JAVA
class ForEachLoop
{
public static void main(String [] args)
{
int[] marks = new int[]{40,60,80,65,70};
System.out.println("Accessing array element using normal for loop ........");
for(int i =0; i < marks.length; i++)
{
System.out.println(marks[i]);
}
System.out.println("Accessing array element using for-each loop ........");
for(int num : marks)
{
System.out.println(num);
}
}
}
We see you don't have to write the expressions like initialization, condition, increment/decrement which
is used in normal for loop and it's also easy to write and more readable as well. So, you should prefer to
use the for-each loop over normal for loop while traversing array/ collection elements. You should
read this as, "for each num in marks" execute the code inside the body.
How for each loop works
●It picks one element from array/collection. ●Assigns that element in variable given in left side
●Executes the body of for-each loop
●Then again moves to first step for the next element or finishes if all the elements are traversed.

foreach vs for loop


89 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
You cannot modify the elements of array/collection using the for-each loop since don't get the indexes
while the same can be done in a normal for loop. E.g. below thing cannot be achieved using the for-
each loop.
for(int i = 0; i < marks.length-1; i++)
{
if(i==3)
{
marks[i] = 70;
}
}
You can traverse an array/collection from last to first using normal for loop as seen below, but the
same cannot be achieved using for-each loop as it iterates only forward over the array/collection.
for(int i = marks.length-1; i>=0; i--)
{
System.out.println(marks[i]);
}
You can access many elements in a single iteration using the for loop as given below, but the
same cannot be achieved using for-each loop.
for(int i = 0; i < marks.length-1; i++)
{
if(marks[i] == marks[i+1])
{
}
}
Prefer the normal for loop over for-each loop whenever indexes are needed while iteration as for-
each loop doesn't keep track of indexes.

STRINGS IN JAVA INTRODUCTION


String is one of the most widely used data type in java. Words that we usually use in conversations
like "hello", "refresh java", "Hello world", "It's easy to learn java", name of a person, address of a person
etc are some of the examples of string in java. In java, a string is set of characters, for example the
string "hello" is a sequence of characters 'h', 'e', 'l', 'l', 'o'. Similarly, each string in java is a sequence of
characters. Java provides String class to create and manipulate strings in programs. This class is
defined in java.lang package which comes automatically in your java software(JDK or JRE).
Since a class in java acts as a non primitive data type, so String is also a non-primitive data type. You
can use String class as a data type to store string values. The Syntax of declaring a string is:
String var_name = "java by herbert";
String var_name = new String("Hello ISBAT");

Here String is the data type, the var_name is the name of variable given you and the value of the
string variable is given inside " ". You need to use the double quotes(“ ”) to create the string values
in java. Which approach should I prefer to declare a string, "" or new keyword? Though you can use
90 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
any of the above approach but creating a string using new operator is not commonly used and is not
recommended as it creates an extra object inside heap memory.
STRING CLASS PROGRAM IN JAVA
class StringDemo
{
public static void main(String args[])
{
// Creating String variables
String strVar = "refresh java";
String strVar2 = new String("Hello World");
char[] charArray = {'h', 'e', 'l', 'l', 'o'};
String strVar3 = new String(charArray);
String strVar4 = strVar;
// Printing the values of String variables
System.out.println("strVar = "+strVar);
System.out.println("strVar2 = "+strVar2);
System.out.println("strVar3 = "+strVar3);
System.out.println("strVar4 = "+strVar4);
}
}

JAVA STRING MEMORY ALLOCATION


String values in java are stored inside a special memory called a string pool or string constant
pool which exist inside the heap memory. This memory is used to allocate space for string values
only. String values given inside the " " in a program are made in a string pool. To understand
memory allocation of strings, let's consider the following string variables declared inside a program.
1. String s1 = "refresh java";
2. String s2 = new String("Hello World");
3. String s3 = new String("hello");
4. String s4 = "refresh java";
5. String s5 = "hello";
91 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Let's understand how java assigns memory for above strings variables.
 Line 1, java checks if string literal "ISBAT java" is already in string pool or not, since it's not there,
java creates this string literal in string pool and assigns the reference(address) of this in s1.
 Line 2 is creating object s2 using new keyword, so java will create it inside the heap memory with
value as "Hello World" and it will create the string literal("Hello World") inside the string pool as well.
 Line 3 is creating object s3 using new keyword, so it will also be created inside the heap memory
with value as "hello" and the same string literal("hello") would also be created inside string pool.
 Line 4, java again checks the string literal "refresh java" inside the string pool, since it's already
there in pool, so it won't create it again. Java assigns the reference of existing string literal in s4.
 Line 5, java again checks the string literal "hello" inside string pool, since it's already there in pool,
so it won't create it again. Java assigns the reference of existing string literal in s5.
Why does java use a special memory for string? Because a String is one of the most useful data
type with improved memory usage and application performance. So, java uses string pool memory as it
doesn't create unnecessary or duplicate objects, instead it uses the existing string objects. What is
string literal in java? A series of characters in your program that are enclosed in double quotes("") is a
string literal. E.g. "hello world", "refresh java", "java is easy to learn" are string literals in java. Whenever
it encounters a string literal in your code, the compiler creates a String object with its value in string
constant pool. String literals are string constants in java. How can I check if two string variables or
literal have same reference(address)?You can use == operator to compare if two string variables or
literals have same address. E.g. s1==s2, s1==s4 etc.

STRING CONCATENATION IN JAVA


This is a common concept in java programmers. String concatenation is a way of concating(adding)
two or more string values. Java provides the feature of adding two or more string variable or values
using plus(+) operator. E.g. you can add two string values "refresh" and "java" as "refresh"+"Java"
bwhich results as a new string "refreshJava". Java also provides the concat method in String class to
concat two string variables or values. You can refer next section about this method.
JAVA PROGRAM TO CONCATENATE TWO STRING
class StringConcatDemo
{
92 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
public static void main(String args[])
{
String s1 = "ISBAT";
String s2 = "Java";
s1 = s1+s2;
s2 = " ISBAT " + s2 + " section";
System.out.println("s1 = "+s1);
System.out.println("s2 = "+s2);
}
}

A JAVA STRING IS IMMUTABLE


Immutable simply means something that is not changeable, once a string value in java is created,
you can’t change that value. In the above program, the code s1+s2 creates a new string " ISBAT Java"
and assigns the reference of this in s1 but the original string "refresh" will still be there in string pool
memory, that is why string in java is immutable.
Why a string is immutable in Java? Since immutable strings cannot be changed, the same string can
be referenced in multiple programs or applications which significantly improves the memory usage and
application performance.
NOTE: String pool, string constant pool and string literal pool and string intern pool
are same things. Digits can also be stored as string in java, e.g. String str = "12345"; is a valid string.
A '+' operator, which does addition on primitives (i.e. int and double), is overloaded to perform
concatenation on String objects. A compiler, uses the append method of StringBuffer/StringBuilder
class to implement string concatenation.

USEFUL STRING CLASS METHODS IN JAVA


You may want to do some types of operations on strings like "compare two strings, find or replace a
particular character/word in a string, add two strings, extract a part of a given string" etc. As java
designer, there are a number of methods in String class which you can use in your program to perform
such type of operations on strings. To understand the String class methods better, let's first understand
how a string value in java is stored in memory. String in java is an array of characters, so string
values in java is stored as an array of characters where each characters have an index number. Some
String class methods use indexes to perform operations on strings. The image below shows how a
string value "refresh java" is stored as an array of characters in string pool memory.
93 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
As you see, each characters is given an index number and you can access the character at a given
index using charAt() method of String class which returns the character of a particular index.
The length of a string is the total number of characters in string. To understand the String class
methods better let's consider we have three string variables s1, s2 and s3 as given below.
String s1 = "refresh java";
String s2 = "Hello World";
String s3 = "learn java on refresh java section";

HOW CAN I CALL A METHOD OF STRING CLASS IN A PROGRAM? To access a method of String
class, you use the dot(.) operator with a string variable or a string literal, e.g. s1.length(),
s1.equals(s2), "Hello".equalsIgnoreCase("hello"), s1.chartAt(8) etc.

Table below shows the list of methods which are used often with string. You can refer oracle
documentation of String class to get the detail of all methods.
NAME DESCRIPTION EXAMPLE

It returns the length of string.


int length = s1.length();
int length() The length is equal to the total
//length = 12
number of characters in string.

s1.equals(s2);
Used to compare two strings.
// returns false
It returns true if both string
boolean equals(Object anObject)
represents same sequence of
s1.equals("refresh java");
characters else false.
// returns true.

Used to compare two strings,


ignoring the case(upper or
lower case). It returns true if
s1.equalsIgnoreCase("Refre
boolean equalsIgnoreCase(String both the string are of same
sh JAVA");
anotherString) length and represents same
// returns true
sequence of character
ignoring the case else
returns false.

s1.startsWith("refresh");
checks if a string starts with // returns true.
boolean startsWith(String prefix) the string represented
by prefix. s1.startsWith("Refresh");
// returns false.
94 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Used to search if a
substring(represented by str) s1.indexOf("java");
exist in the given string. // returns 8
int indexOf(String str) Returns the index of first
occurrence of substring in the s1.indexOf("hello");
given string if found else // returns -1
returns -1.

Used to search if
substring(represented by str)
s3.indexOf("java", 10);
exist in the given string, but it
// returns 22
starts searching from the
int indexOf(String str, int fromIndex)
index given by fromIndex. It
s3.indexOf("easy", 25);
returns starting index of that
// returns -1
substring if found else returns
-1.

Used to search the last


occurrence of
substring(represented by str)
s3.lastIndexOf("java");
int lastIndexOf(String str) in the given string. It returns
// returns 22
the index of last occurrence of
substring if found else returns
as -1.

Returns the character at char charVar = s1.charAt(8);


char charAt(int index)
specified index in given string. // charVar = 'j'

String str = s1.substring(8);


Returns a string that is a
// str = "java", s1 will still be
substring of the given string.
same that is "refresh java"
The substring starts with the
String substring(int fromIndex) character
String str2 =
at fromIndex position and
s3.substring(27);
extends to the end of given
// str2 = "section", s3 will still
string.
be same.

Returns a string that is a String str = s1.substring(0,7);


String substring of the given string. // Return characters from 0
substring(int fromIndex, int endIndex) The substring starts with the to 6
character str = "refresh"
at fromIndex position and
95 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

extends to the (endIndex-1) String str2 =


s3.substring(14,26);
// str2 = "refresh java"

String str =
Converts all the characters of s2.toLowerCase();
String toLowerCase() given string to lower case and // str = "hello world"
returns that string. s2 will still be same that is
"Hello World".

String str =
Converts all the characters of
s1.toUpperCase();
String toUpperCase() given string to upper case and
// str = "REFRESH JAVA",
returns that string.
s1 will still be same.

Used to remove whitespace( )


at the beginning and end (not
String str = " hello world
in between) of a given string.
String trim() ".trim();
Returns a string without any
// str = "hello world"
whitespace in end and
beginning.

String strVar = s1.concat("


Concatenates(adds) the string section");
String concat(String str) represented by str to the end // strVar = "refresh java
of given string section",
s1 will still be same.

char [] charArray =
s1.toCharArray();
Converts the given string to a
// charArray will contain an
char[] toCharArray() new character array and
array of
returns that char array.
characters(r,e,f,r,e,s,h,
,j,a,v,a)

Returns a string resulting from


replacing all occurrences of
String str = s1.replace('r', 'h');
String character represented
// str = "hefhesh java",
replace(char oldChar, char newChar) by oldChar with character
s1 will still be same.
represented by newChar in
the given string.
96 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Used to replace first


occurrence of string String str =
represented by regexe with s3.replaceFirst("java","progr
String replaceFirst(String regexe,
string represented am");
String replacement)
by replacement in given // str = "learn program on
string. regexe can be a regular refresh java section"
expression as well.

Used to replace all occurrence String str =


of string represented s3.replaceAll("java","progra
String replaceAll(String regexe, by regexe with string m");
String replacement) represented by replacement in // str = "learn program on
given string, regexe can be a refresh
regular expression as well. program section"

String[] str = s3.split(" ");


Used to split a given string on // str will contains strings
String[] split(String regexe) the basis of regexe. It returns "learn"
a string array. "java" "on" "refresh" "java"
"section"

STRING CLASS METHODS PROGRAM IN JAVA


class StringClassMethods{
public static void main(String [] args){
String s1 = "ISBAT University";
String s2 = "Hello World";
String s3 = "Learn Java at ISBAT";
String str;
// Getting the length of a string
System.out.println("length of string s1 = "+s1.length());
// Comparing two strings
System.out.println(s1.equals("refresh java"));
System.out.println("is s1 equals s2 = "+s1.equals(s2));
// Checking if a string starts with a given substring
System.out.println("is s1 starts with word refresh = "+s1.startsWith("ISBAT"));
// Searching a substring in a string
System.out.println("index of word java in s3 = "+s3.indexOf("java"));
System.out.println("index of word hello in s3 = "+s3.indexOf("hello"));
// Getting the character at given index in a string
System.out.println("character at index 8 in string s1 = "+s1.charAt(8));
// Extracting a substring from a given string
str = s1.substring(8);
97 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Substring str = "+str);
// After extracting a substring, value of s1 will still remain same.
System.out.println("Value of s1 = "+s1);
// Converting a given string to lower case.
str = s2.toLowerCase();
System.out.println("Lower case str = "+str);
// Concatenating a string to given string.
str = s1.concat(" section");
System.out.println("Concatenated str = "+str);
// Concatenating a string to given string using + operator.
str = str + " online";
System.out.println("+ operated value of str = "+str);
// Replacing a word in a given string.
str = s3.replaceFirst("java","program");
System.out.println("Replaced value str = "+str);
// Splitting a given string using space( ).
String[] strArray = s3.split(" ");
for(String strVar : strArray)
System.out.print(strVar+", ");
}
}
DIFFERENCE BETWEEN EQUALS() AND == IN JAVA
Both equals() method and == operator can be used to compare string variables or string literals in java
but there is a difference between both. equals() method compares the content(the sequence of
characters) of string variables or string literals. It returns true if both the content are same else
returns false while == operator compares the references(address) of string variables or string literals. It
returns true if both the variables or literals points to same reference else returns false. If the
comparison of two strings using == operator returns true then equals() method for same comparison
will definitely return true while vice-versa may or may not return true. The program given below shows
the difference of equals() method and == operator.
class StringComparison{
public static void main(String [] args){
String str = "refresh java";
String str2 = new String("refresh java");
String str3 = "refresh java";
String str4 = new String("refresh java");
String str5 = str2;
System.out.println("Comparison using equals() method ..........");
System.out.println("str equals() str2 >> "+str.equals(str2));
System.out.println("str equals() str5 >> "+str.equals(str5));
System.out.println("str2 equals() str4 >> "+str2.equals(str4));
System.out.println("str2 equals() str5 >> "+str2.equals(str5));
System.out.println("Comparison using == operator ..........");
98 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("str == str2 >> "+(str == str2));
System.out.println("str == str3 >> "+(str == str3));
System.out.println("str2 == str4 >> "+(str2 == str4));
System.out.println("str2 == str5 >> "+(str2 == str5));
System.out.println("str4 == str5 >> "+(str4 == str5));
}
}
STRINGBUFFER AND STRINGBUILDER IN JAVA
Apart from the String class java has two other classes to handle string values, StringBuffer and
StringBuilder. The classes were added with some purpose, the difference between both and when
to use StringBuffer or StringBuilder. String in java is immutable, which means you cannot change
string value once created. When we do string manipulation like concatenation, substring, replace etc, it
generates a new string and leaves the original string as is in memory which becomes a garbage value.
For an example the code given below will generate a garbage value as "refresh java" in memory.
String str = "refresh java";
str = str + " section";
The concatenation act above creates a new string as "refresh java section" in string pool memory and
assigns its reference in str but this operation won't change the original string "refresh java", it will still
exist in pool memory as a garbage value.

WHAT IS A GARBAGE VALUE?


Any value or object inside the memory that is not being referred by program or application is known
as garbage. The process of collecting and destroying such values from memory is known as garbage
collection. The string manipulation operations doesn't cost much if it is not happening frequently, but if
it's happening often and in many areas in your application, this may cause serious memory leak and
performance issue as it creates a lot of garbage in memory. To solve this problem, java gives two
more classes, StringBuffer and StringBuilder. String values stored in StringBuffer or StringBuilder
data type are mutable. Meaning, if you apply any operation on String values or objects stored
in StringBuffer and StringBuilder classes which are mutable, then you will change the original
string itself rather than creating a new string. As a result, it will not generate garbage in memory.
The Syntax of declaring StringBuffer and StringBuilder is:
StringBuffer var_name = new StringBuffer("StringBuffer value");
StringBuilder var_name = new StringBuilder("StringBuilder value");
// Example
StringBuffer strbuff = new StringBuffer("refresh java");
StringBuilder strbdr = new StringBuilder("java is easy");
Here StringBuffer and StringBuilder are the data type(classes), var_name is the name of variable
given as per the programmers choice and the value of variable is given inside "". Java considers string
literal(value given in "") as String type, so you cannot assign string literal directly to StringBuffer and
StringBuilder variable as given below. You must have to use new keyword to create StringBuffer and
StringBuilder.
99 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// Both line will throw compilation error.
StringBuffer strbuff = "refresh java";
StringBuilder strbdr = "java is easy";
You can also not use + operator to concat string on StringBuffer and StringBuilder variables.
StringBuffer strbuff = new StringBuffer("refresh java");
StringBuilder strbdr = new StringBuilder("java is easy");
// Both line will throw compilation error.
strbuff = strbuff + " another value";
strbdr = strbdr + " another value";

How can I add another string value in StringBuffer or StringBuilder variable? You need to use
append() method of these classes to add another string. Refer the program given below to see the use
of this method.
StringBuffer and StringBuilder program in Java
class StringBufferAndBuilder{
public static void main(String args[]) {
String str = "refresh java";
String str2 = str;
StringBuffer strbuff = new StringBuffer("StringBuffer on refresh java");
StringBuffer strbuff2 = strbuff;
StringBuilder strbuild = new StringBuilder("StringBuilder on refresh java");
StringBuilder strbuild2 = strbuild;
str = str + " section";
strbuff = strbuff.append(" section");
strbuild = strbuild.append(" section");
System.out.println("str = "+str);
System.out.println("str2 = "+str2);
System.out.println("strbuff = "+strbuff);
System.out.println("strbuff2 = "+strbuff2);
System.out.println("strbuild = "+strbuild);
System.out.println("strbuild2 = "+strbuild2);
}
}
As you see, both String variable have different value while both the StringBuffer and StringBuilder
variable have same value, that's because String is immutable. Once you add a string literal in String
variable, java creates a new string object and assigns the reference of it in String variable while in-
case of StringBuffer and StringBuilder, the same string is modified.
USEFUL STRINGBUILDER AND STRINGBUFFER METHODS IN JAVA
The table below shows some useful methods of a StringBuffer and a StringBuilder classes which is
usually used for string manipulation. Both classes have the same methods, the only difference is that
methods of StringBuffer class are synchronized. Table assumes you have a variable s1 of type
StringBuffer.
100 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

NAME DESCRIPTION EXAMPLE


It appends the string s1 = new StringBuffer("refresh");
append(String str) represented by str at the end s1.append("Java");
of given string. // s1 = "refreshJava"
Used to insert string
s1 = new StringBuffer("refresh");
represented by str at index
insert(int offset, String str) s1.insert(2, "java");
specified by offset in given
// s1 = "rejavafresh"
string.
It deletes characters s1 = new StringBuffer("refresh java");
delete
from startIndex to (endIndex- s1.delete(2,7);
(int startIndex, int endIndex)
1) from given string. // s1 = "re java"
It replaces characters
s1 = new StringBuffer("refresh java");
replace (int start, int end, from start to (end-1) index
s1.replace(0,7,"section");
String str) with string represented
// s1 = "section java"
by str in given string.
s1 = new StringBuffer("refresh java");
It reverses the sequence of
reverse() s1.reverse();
characters of given string.
// s1 = "avaj hserfer"
Used to replace the character
s1 = new StringBuffer("refresh");
at given index with character
setCharAt(int index, char ch) s1.setCharAt(0,'s');
represented by ch in given
// s1 = "sefresh"
string.

CONVERSION FROM STRING TO STRINGBUFFER/STRINGBUILDER AND VICE-VERSA


You cannot directly assign a String variable in StringBuffer/StringBuilder or vice-versa. You need to use
conversion like below to store it in other string data type variable.
String str = "ISBAT University";
// Both line will throw compilation error.
// StringBuffer strbuff = str;
// StringBuilder strbdr = str;
// Conversion from String to StringBuffer and StringBuilder.
StringBuffer strbuff = new StringBuffer(str);
StringBuilder strbdr = new StringBuilder(str);
// Both line will throw compilation error.
// String str2 = strbuff;
// String str3 = strbdr;
// Conversion from StringBuffer/StringBuilder to String.
String str2 = strbuff.toString();
String str3 = strbdr.toString();
STRING VS STRINGBUFFER VS STRINGBUILDER
 The String object is immutable while objects of StringBuffer and StringBuilder are mutable.
101 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 StringBuffer is thread safe as its methods are synchronized while StringBuilder is not, so use
StringBuffer in multi-threaded environment where thread safety is needed.
 StringBuffer is not as faster as StringBuilder for string manipulation operations, since methods
of StringBuffer class is synchronized.
 StringBuilder was added in java 1.5, before that there was only String and StringBuffer classes
for string handling.
 In single threaded environment, prefer String over StringBuilder if you don't need mutable
objects as String is easier and more convenient to use. Use StringBuilder if mutable objects
needed.
What is multi-thread environment? In a multi-threaded environment multiple programs or different
parts(thread) of a program runs simultaneously. Define synchronized in java? synchronized is a
keyword, use to achieve thread safety. A synchronized method cannot be accessed simultaneously by
multiple threads. In most of the scenarios we don't use String data type in multithreaded environment
where thread safety is needed, as it may cause inconsistent behavior. For example if a thread makes
any changes in String variable, the other thread may not get the updated value which may cause
inconsistent behavior of your program. To avoid such type of problem you should use StringBuffer
class where thread safety is needed.
Refer java oracle docs or java source code of StringBuffer and StringBuilder class to get details of all
methods. There are many methods in String and StringBuffer/StringBuilder classes that are available in
each other but not all. Digits can also be stored as string in StringBuffer and StringBuilder class in java,
for example StringBuffer str = new StringBuffer("12345"); is a valid string. The '+' operator, which
performs addition on primitives (such as int and double), is overloaded to perform concatenation on
String objects. The compiler, internally uses the append method of StringBuffer/StringBuilder class to
implement string concatenation.
ARRAY AND STRING PROGRAMS IN JAVA
In this section we will see some of the programs of array and string which are commonly asked with
beginners in interviews. These programs will help them to build their logics in using array and string.
Let's see the first program which shows how to check if a given number exist inside an array. If it exist,
the program will also print it's index in the array.
PROGRAM TO SEARCH AN ELEMENT IN AN ARRAY
class SearchNumber{
public static void main(String [] args){
int [] numbers = {40,60,80,65,70};
boolean isExist = false;
int searchNumber = 80;
int pos = -1;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] == searchNumber){
isExist = true;
pos = i;
break;
}
}
102 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
if(isExist)
System.out.println("number "+searchNumber+" exist in the array at index = "+pos);
else
System.out.println("number "+searchNumber+" does not exist inside the array");
}
}
The next program shows how to find minimum and maximum element of an array. This is one way to
find the minimum and maximum element, there can be other approaches as well.
JAVA PROGRAM TO FIND MAXIMUM AND MINIMUM NUMBER IN AN ARRAY
class MinMaxOfArray{
public static void main(String [] args){
int [] numbers = {40,20,80,65,70,90,35,10};
int maxValue = numbers[0];
int minValue = numbers[0];
for(int i=1;i < numbers.length;i++){
if(numbers[i] < minValue)
minValue = numbers[i];
if(numbers[i] > maxValue)
maxValue = numbers[i];
}
System.out.println("Minimum number = "+minValue+" and maximum number =
"+maxValue);
}}
The next program shows how to sort an array of integer elements in ascending order. This is one
approach to sort an array, there are other approaches as well to do the same.
JAVA PROGRAM TO SORT AN ARRAY
class SortArray{
public static void main(String [] args){
int [] numbers = {40,20,80,65,70,90,35,10};
int length = numbers.length;
int temp;
for(int i = 0; i < length; i++){
for(int j = i + 1; j < length; j++){
if(numbers[i] > numbers[j]){
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
System.out.println("Array elements in ascending Order:");
for(int n : numbers)
System.out.print(n + " ");
}}
103 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The next program shows how to reverse a given string and checks if it is a palindrome string. A string is
called palindrome if the reverse of the string is same as the original string. Again this is one way to
reverse the string, there can be other ways as well to do the same. You can also use reverse() method
of StringBuffer/StringBuilder class to reverse a given string directly but our intention is to learn the logic.
JAVA PROGRAM TO REVERSE A STRING AND PALINDROME STRING
class ReverseAndPalindromeString{
public static void main(String [] args){
String str = "abcba";
String revStr = "";
for(int i = str.length() - 1; i >= 0; i--){
revStr = revStr + str.charAt(i);
}
System.out.println("Reverse string = "+revStr);
if(revStr.equals(str))
System.out.println("The given string is a palindrome string");
else
System.out.println("The given string is not a palindrome string");
}}
Let's write one more program which counts total number of occurrence of a given character inside a
given string. The program shows two different approaches to count the total occurrence.
PROGRAM TO FIND OCCURRENCE OF A CHARACTER IN A STRING IN JAVA
class CharacterCount{
public static void main(String[] args){
String str = "Java is easy to learn";
char c = 'a';
int count = 0;
// First Approach
char[] charArray = str.toCharArray();
for(char ch : charArray){
if(ch == c)
count++;
}
System.out.println("Total occurrence of character 'a' using 1st approach = "+count);
// Second Approach
int count2 = str.length() - str.replace("a", "").length();
System.out.println("Total occurrence of character 'a' using 2nd approach = "+count2);
}
}

WHAT IS A CLASS IN JAVA


Java is an object-oriented programming language. Classes and objects are key concepts
to understanding object-oriented programming which is based on these two terms. Let's see
what a class is and similarly discuss objects. Programmatically, a class is a collection of variables,
104 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
constructors, methods, blocks which are optional class components. Class is defined using a class
keyword followed by the class name. The name of the class is used to refer that class within or outside
the class. The basic syntax of declaring a class is:
class ClassName{
// variables, constructors,
// method declarations
}
Here class is a keyword, used to define a class in java. ClassName is the name of class, given by
the programmer. After the class name, it's the class body given inside { }. Variables, methods,
constructors etc defined inside the balanced { } after the class name are the part of that class.
Do we have any convention to write the class name? The convention is that a class name and any
subsequent word in class name must start with uppercase, e.g. MyFirstProgram, HelloWorldProgram,
Person, Bicycle etc are valid class names of this convention. Is class keyword case-sensitive? All
keywords in java are case-sensitive and they must be in smallletters. So, you can’t use a class
keyword as Class, CLASS, clAss etc, it must be in small letters. In object oriented world, think of a
class as a blueprint or design describes how an object of a class behaves and what data(properties)
it will contain inside it. The methods of a class define the behavior of object while instance variables are
the data of the object that it will contain inside.
REAL TIME EXAMPLE OF CLASS
Some class examples are Person, Vehicle, House, Tree, Dog etc. For an E.g. a Person class
has properties like name, age, height etc. and behaviors like walk, talk, eat, sleep etc. Now if you
create an object of this class, it will have these properties and behaviors inside it. Once you created a
class, you can create multiple objects of that class.

Can I give any name to my class? Yes, you can give any name to a class by following the identifier
naming convention rules but giving a meaningful name is a good programming style. E.g. class names
like Abc, XYZ are valid names but not meaningful names while class names like MyFirstProgram,
HelloWorldProgram, Person are meaningful names.
JAVA CLASS PROGRAM
class Person{
// Instance variables, describes state/properties of object of this class.
105 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
String name;
int age;
int height;
// methods, describes behaviors of object of this class.
public void walk(){
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Walk");
}
public void talk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Talk");
}
}

class ClassDemo{
public static void main(String [] args){
Person p1 = new Person(); // Creating object of class Person
p1.name = "Rahul";
p1.age = 20;
p1.height = 170;
p1.walk();
p1.talk();
}}
In above example we have created a class called Person which is basically a prototype, describing that
object of this class will have properties as name, age, height and will have behaviors as walk and talk.
You can add more properties(instance variables) and behaviors(methods) in your program. This
example creates only a single object of Person class. You can create multiple objects of Person class
and assign different values inside it. Should I create all classes in single file? No, that's not a good
programming style. In real world programming mostly, we use to create each class in separate files in
our application. So next time when you are creating a class, think that you are creating a prototype
which will tell that what properties(state) and behaviors will exist inside the object of that class. This
way you will get better idea to design your class. A class is also called as a blueprint or a template or
a design or a Type. These are just different words use to describe a class in java. Who loads java
classes in memory while execution? As soon as you run a program, the class-loaders available
in java virtual machine loads classes in memory for execution. In java, these class-loaders are also a
program. Is it mandatory to define variables(instance or static variable) on top of a class? No,
you can define such variables after the method or in end of a class but that's not a good programming
style. You should always prefer to declare it at top since it makes a class more readable. Can a class
exist without main method? Yes, in real world programming only a starting class of your application(a
group of classes) will have main method, all other classes won't have main method. Should I focus
more on real world aspect of class? As a programmer you should focus more on it's programming
aspect rather than focusing on real world aspect, programming aspects like creation of class, creation
of variables and methods inside the class, creation of objects of class etc. The syntax of declaring a
class given in this section is the minimal one which is required. Some of the more keywords that can be
106 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
declared along with class keyword are public, abstract, final, extends, implements. A class can also
have another class, static blocks, enum etc inside the body of it.
NOTE: Every program must have at least one class, it can have more than one class as well. If there
are multiple classes in a single program file, the file must be saved by class name declared with public
keyword, if any. Every class(user defined or defined by java) in java is a non-primitive data type. There
should be only one main method having argument type as String [] in a class. If there are multiple non
public classes in a single program file, conventionally the program file should be saved by class name
having main method.

WHAT IS AN OBJECT IN JAVA


Objects are key concepts of java, since it is an object-oriented programming language. In OOP,
program focuses on objects rather than logic. In the real world, you can see many examples of object
around you: person, dog, laptop, mobile, bicycle etc. These objects have two features, state
and behavior. E.g. a person has a state like name, age, height etc and behavior like walk, talk,
eat etc while a dog have state like breed, age, color etc and behavior like run, bark, eat etc. Similarly,
software object also has two characteristics: state and behavior. The state of an object is
defined by the instance variables of a class while behavior is defined by the methods of class. So an
object in java is a set of data(instance variables) and methods that acts on those data. In programming
an object is an instance of a class. So next time when you are creating a class, think of two things
about its objects. "What possible states can this object have?" and "What possible behavior can this
object perform?". This way you will get better idea to design your class. You can think of a software
object like below which holds its state and behavior together with itself.
The Syntax given below shows the most basic way of creating an object of a class in java. There are
other ways as well but we will not discuss that here.
ClassName objName = new ClassName();
Here ClassName is the name of a class whose object needs to be created and objName is the
name of object. The object name should be unique and should follow the convention given in identifier
naming convention. A keyword new is used to create object in java. Using the ( ) with ClassName calls
the constructor of that class to create and initialize the object in memory. We will discuss about
constructors in later sections. Let's assume two classes Person & MyFirstProgram, code given below
shows how to create an object of these classes:
// Creates an object of Person class with name as obj.
Person obj = new Person();
// Creates an object of MyFirstProgram class with name as mfp.
MyFirstProgram mfp = new MyFirstProgram();
How can I access properties and methods of an object? You just have to apply dot(.) operator with
object name followed by property/method name to access the properties and methods of an object.
You can also change the value of a property of an object using the same operator. Refer program given
below to see the use of this operator. What if I access object name only? In java object name is a
reference, so accessing the name will return the reference(address) of that object in memory.
OBJECT PROGRAM IN JAVA
107 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class Person{
// Instance variables, describes state/properties of object of this class
String name;
int age;
int height;
// methods, describes behaviors of object of this class
public void walk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Walk");
}
public void talk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Talk");
}
public void eat() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Eat");
}
}
class ObjectDemo{
public static void main(String [] args){
// Creating object p1 of Person class
Person p1 = new Person();
p1.name = "Rahul";
p1.age = 20;
p1.height = 170;
p1.walk();
p1.talk();
p1.eat();
// Creating another object p2 of Person class
Person p2 = new Person();
p2.name = "Rohit";
p2.age = 30;
p2.height = 180;
p2.walk();
p2.talk();
p2.eat();
}
}

Save above program as ObjectDemo.java


compile as javac ObjectDemo.java
run as java ObjectDemo
108 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Output:
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Walk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Talk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Eat
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Walk
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Talk
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Eat

Here p1 and p2 are objects of Person class. Once the code


line Person p1 = new Person(); executed, java constructors
creates the object p1 in heap memory and assigns the default
values of the instance variables for this object. After that code
lines p1.name, p1.age and p1.height modifies those default
values of the instance variables for this object only. Similarly p2
is also created and assigned the values of instance variables. All
the objects of a class are created inside heap memory. You can
think of object p1 like below.

Who creates objects in java? It's the constructor that creates


object of a class inside heap memory. We will see about constructors in later sections. At runtime each
object that you have created in your program will be allocated space in heap memory. Each object will
have it's own copy of instance variables and methods defined inside the class. Changing the value of a
instance variable for one object will not change the value of that variable for other object. Can an
object exist without a class? No, an object can never exist without a class. Every object must have a
class which defines its type. What happens to objects when program execution completed?
As soon as the execution of a program completes, all it's objects are destroyed/removed from memory.
Should I focus more on real world aspect of object? You should focus more on its programming
aspects rather than on real world aspects, programming aspects like creation of object, accessing it's
fields and methods, accessing object of other class etc.
Every object in java has a unique ID, that is not known to external programmers. JVM uses this id
internally to identify each object uniquely. Word object and instance are used interchangeably. Fields,
properties, attributes, state of an object refers to same thing which is generally instance variables of a
class. An object can contain another object inside it. Only non-static variables and methods belong to
an object of a class.

WHAT IS A METHOD IN JAVA


A method is a block of instructions(one or more line of codes) given in { } inside a class. This block is
referred by a name which is basically the method name. The name of method is used to call(invoke)
that method within or outside a class. Once a method is called, the code given inside that method is
executed. After execution a method may or may not return a value. The most basic or minimal Syntax
of declaring a method is:
// Method without parameter
Return_Type methodName(){
// one or more line of code.
109 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
return some_value;
}

// Method with parameter


Return_Type methodName(DataType param1, DataType param2 ...){
// one or more line of code.
return some_value;
}
Method must have a return type which tells what type of value this method returns. The Return_Type
of a method can be primitive or non-primitive data type. If a method doesn't return a value, it's
return type must be void or in other way if the return type of a method is void, it means that method
doesn't return any value. The name of the method is given by the programmer. As per the convention
the method name should be in small letters while in multiWord method name, the first letter of any
subsequent word should be in capital letter. For example method names like add(), calculateArea(),
getName() etc are some examples of this convention. After method name, it's the parameters given
inside () which are basically variables. Parameters are optional which means a method may or may not
have parameters. You can access these parameters within the method only, not outside the method.
The data type of parameters can be primitive or non-primitive. After parameters it's method body given
inside { }. Everything given inside { } after method name are the part of that method. Let's see some
examples of method declaration.
int add(int num1, int num2){
// one or more line of code.
return value; // returns integer value.
}
void calculateArea(){
// one or more line of code.
}

Can I give any name to method? Yes you can given any name by following the identifier naming
convention but giving a meaningful name is a good programming style. The name should itself suggest
that what this method does. For example method names like xyz(), method123() are valid names but
not meaningful names while names like add(), calculateArea(), getColor() are meaningful names.
BUILT-IN VS. USER DEFINED METHODS
Methods that are defined inside the classes included in java software are known as built-in methods.
For example println() method, String class methods like charAt(), toLowercase(), trim() etc are built-in
methods. The methods that programmers defined inside their classes is known as user defined
methods. It's programmer who gives the name to his method and code inside that method.
Can't I include all code or logic inside a single method? Why I should create different methods?
Yes you can include all logics or code inside a single method but that's not a good programming style.
A good programmer always creates different methods for different tasks which makes your program
more readable and modular.
PARAMETER VS ARGUMENT
Parameters are variables declared inside the ( ) after a method name. Parameters can be accessed
inside the method only. In method declaration add(int num1, int num2), variables num1 and num2 are
110 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
parameters. Arguments are the values that are passed to method while calling the method. For
example in a method call add(20,30), 20 and 30 are arguments.
STATIC AND NON STATIC METHOD
A method declared with static keyword is known as static method. Static method belongs to class not
object which means you don't need to create object to access such methods. You can access static
methods with class name itself. Methods defined without static keyword is known as non-static method,
also known as instance method. You need object or instance of the class to access such methods.
E.g.,n below program calculateArea() is a static method while add(), firstMethod(), secondMethod() are
non static methods. Static method can access only static variables inside it's body while non static
method can access both static and non static variables.
JAVA METHOD PROGRAM
class MethodDemo{
public static void main(String [] args)
MethodDemo md = new MethodDemo();
int sum = md.add(20,30); // calling add() method
System.out.println("sum = "+sum);
md.firstMethod(); // calling firstMethod() using object
MethodDemo.calculateArea(100,50); // calling calculateArea method using className
}
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
void firstMethod()
{
System.out.println("Inside first method");
secondMethod(); // calling secondMethod()
System.out.println("After calling second method");
}
void secondMethod()
{
System.out.println("Inside second method");
}
static void calculateArea(int length, int width)
{
int area = length*width;
System.out.println("Area = "+area);
}
}
Output:
sum = 50
Inside first method
Inside second method
111 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
After calling second method
Area = 5000
static method calculateArea() is called using the class name MethodDemo. You can call static method
using object as well, but that's not a good practice, since static methods belongs to class not object.
You should always prefer to call static methods using class name.
What is called method and calling method? A method that calls another method is known as a
calling method while the method that is being called is known as called method. E.g. in above
program, main() is the calling method for called methods firstMethod() and calculateArea().
Can I pass object inside method calling? Yes you can pass objects as well inside the method. Any
changes made in that object in called method will be reflected in calling method as well.
How method execution happens in Java? As soon as a method is called, the execution of that
method get's started. Once the execution of method completed or any return keyword encountered, the
execution control comes back to the position from where it was called. Once a method is called, java
creates a new stack inside stack memory where all local variables of that method are initialized. For
example in above program once line int sum = md.add(20,30); executed, the execution of add method
get's started. As soon as the return statement in add method is executed, the execution control again
comes back to the line int sum = md.add(20,30); where the value returned by add method is assigned
in variable sum.
What is method signature?
 The name and the parameters of a method in a method declaration is referred as method
signature. Other components like access modifiers, return type etc are not the part of method
signature. For example method signature of add method in above program
is add(int num1, int num2).
 You can define multiple methods with same name having different parameter lists. Java
differentiates such methods on the basis of the number of parameters in the list and their types.
This is known as method overloading. We will discuss method overloading in later sections.
 The syntax of declaring a method given in this section is the minimal one which is required.
Apart from this there are couple of more keywords as given below that can be used with method
declaration. We will discuss these keywords with methods in later sections.
 An access modifier(public, protected, private) can also be used with method declaration. Access
modifiers decides the visibility/accessibility of method within or outside the class. For example
a private method can only be accessed within the class while public method can be accessed
from outside the class as well.
 final keyword can also be used with method declaration. final method cannot be overridden.
 abstract keyword can also be used with method declaration. The implementation or definition of
abstract method is defined by sub class.
 A method can also declare an exception using throws keyword.
1. Accessing a method means calling that method.
2. Functions in other programming language are equivalent to methods in java programming.
3. There should be only one main method having argument type as String [] in a class.
4. When you pass an object inside a method, the reference of that object is passed to the
method.
5. Method that returns a boolean value, can be called inside a conditional statement as well
like if(isValid()), if(isEmpty()) etc.
112 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

CONSTRUCTORS IN JAVA
Constructor in java is used in creation and initialization of object of a class inside memory. It's the
constructor that provides the initial values of instance variables for an object inside memory.
Constructors declarations are similar as method declarations except that constructors don't have any
return type and their name is same as class name. The syntax of declaring a constructor is :
class MyClassName {
// No-argument constructor
Access_Modifier MyClassName() {
// Initialization code
}
// Parameterized constructor
Access_Modifier MyClassName(DataType param1, DataType param2 ...) {
// Initialization code
}
}

Example :
class Person{
Person() {
// Initialization code
}
public Person(int param1, String param2) {
// Initialization code
}
}
Access modifier of a constructor can be public, private, protected or default(no modifier). These
modifiers with constructors decides the accessibility(visibility) of the constructor within or outside the
class. After access modifier it's the name of constructor which must be same as the class name.
Parameters in constructors are optional, a constructor may or may not have parameters. A constructor
without parameter is known as no-argument constructor while a constructor with parameter is also
known as parameterized constructor. The data type of parameters can be primitive or non-primitive. In
constructor body generally we initialize instance variables with some values but it's not limited to that
only. You can use other statements as well as you do in methods. You can define multiple constructors
with different argument lists. Java differentiates constructors on the basis of the number of arguments
in the list and their types. This is also known as constructor overloading. You cannot write two
constructors that have the same number and type of arguments for the same class, because java
compiler would not be able to differentiate them. In this case compiler will throw error.

Types of Constructors in Java


Constructor can be divided in three types.
1.No-argument constructor 2.Parameterized constructor 3.Default constructor
We have already covered the definition of first two constructor. We will see how to use them in program
example given below. How constructors are invoked(called)? Constructors are invoked automatically
when the code that creates object of a class using new keyword is executed.
113 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
CONSTRUCTOR PROGRAM IN JAVA
class Person{
int age;
int height;
String name;
// No-argument constructor
public Person() {
System.out.println("Initialization using no-argument constructor");
age = 15;
height = 160;
name = "Pradeep";
}
// Parameterized constructor
public Person(int a, int h, String n) {
System.out.println("Initialization using parameterized constructor");
age = a;
height = h;
name = n;
}
public static void main(String [] args) {
Person p1 = new Person(); // invokes no-argument constructor
p1.print();
Person p2 = new Person(20,170,"Rahul"); // invokes parameterized constructor
p2.print();
}
void print() {
System.out.println("age = "+age+", height = "+height+", name = "+name);
}}
HOW CONSTRUCTOR WORKS IN JAVA
Let's understand this by above program. Once the code new Person(); is executed, it creates the object
of Person class inside memory and invokes the no-argument constructor which executes the given print
statement and assigns values of instance variables for this object. Finally the reference of this object is
assigned into p1. Similarly code new Person(20,170,"Rahul"); creates another object inside memory
and invokes the matching parameterized constructor which assigns values passed to it in
corresponding instance variables for object p2. So both objects will have their specific values of
instance variables. You can imagine the object p2 inside memory like below.
114 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Can I create a class that have only no-argument or parameterized constructors? Yes you can
create a class that have only no-argument constructor or only parameterized constructor. While
creating the object you just have to ensure that the class contains the matching constructor otherwise
your program won't compile. For example if you try to create an object of Person class in above
program like below, compiler will throw error since it would not find the matching constructor.
// Both statements will result in compilation error as it won't find matching constructor
Person p3 = new Person(20,"Rahul");
Person p4 = new Person(20, 170.5,"Rahul");
WHAT IS DEFAULT CONSTRUCTOR
If you don't write any constructor in your class, java compiler inserts a no-argument constructor in
your .class file after compilation of your program. This constructor is known as default constructor since
it is provided by java compiler. For a class Person having no constructors defined, the default
constructor will look like below.
Person() {

}
The default constructor assigns default values for non-initialized instance variables of an object, for
example an integer instance variable will have value as 0 while a string variable will have value as null
etc. If you have created any constructor(no-argument or parameterized) in your class, java won't
provide default constructor to your class. Constructors created by programmers is also known as user
defined constructor.
Is no-argument constructor is same as default constructor? Default constructor is also a constructor
without argument but if you have created a no-argument constructor in your class that will be a user
defined constructor, not default constructor. Sometimes programmers get's confused about the same.
What is implicit and explicit constructor? Default constructor is also known as implicit constructor while
constructors defined by programmer's in a class is known as explicit constructor.
Can we invoke constructors like methods? Constructors cannot be invoked like methods.
Constructors are invoked automatically. Though you can call one constructor from other constructor of
same class using this keyword like below.
public Person(){
this(15,160,"Pradeep"); // invokes parameterized constructor
}
public Person(int a, int h, String n) {
age = a;
height = h;
name = n;
}
Similarly you can call other constructors if you have in your class by passing the number of arguments.
To call no-argument constructor use this(). If you are calling a constructor using this keyword, ensure
that it's the first statement in constructor body otherwise compiler will throw error. What is private
constructor? A constructor declared with private modifier is known as private constructor. If a class
contains only private constructor, you cannot create object of that class outside the class since your
constructor won't be accessible(visible) outside the class.
115 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD


CONSTRUCTOR METHOD
Constructor name must be same as the class Method name may or may not be same as class
name. name.
Constructor must not have return type. Method must have return type.
Constructor is used to initialize the state of an
Method is used to expose behavior of an object.
object.
Constructor is invoked(called) implicitly. Method is invoked explicitly.
Java compiler provides a default constructor if you Method is not provided by java compiler in any
don't declare any constructor in your class. case.
You cannot use keywords like abstract, final,
These keywords can be used with methods.
static etc with constructors.
A method can also have same name as class name but it must have return type which differentiates it
from constructor. Declaring a method name same as class name is not a good programming style.
Every class has a constructor whether it's a normal class or a abstract class. You can call a method
inside a constructor as well.

JAVA STATIC KEYWORD


static is a keyword in java which is used very often in java programs. Sometimes beginners faces
difficulty to understand what exactly the static keyword does and why to use this. This section explains
different usage of static keyword and also covers different questions like when, how and why do we
use static keyword in java. You will need an object of the class to access members like variables and
methods of that class, because these members belongs to object or instance of that class. Each object
have their specific values for such members. But sometimes we need members that should belong to
class rather than objects and should be same for all the objects. To achieve this java provides static
keyword. static members belong to class not objects. You can access such members using class
name itself rather than objects. Let's see the different usage of static keyword.
1.static variable 2.static method 3.static block 4.static inner class

JAVA STATIC VARIABLE


A static variable is similar to the normal variable except that it has the static keyword in its declaration
static variables are also called as class variables as these variables belongs to class not objects.
These variables must be created inside the class but outside any method or block. If you create static
variable inside any static or non-static method or block, compiler will throw compilation error. The
basic syntax of declaring a static variable is :
class className {
access_modifier static dataType varName;
access_modifier static dataType varName = value;
}
116 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Example :
class Student {
static int total;
public static String collegeName = "SUMVS";

}
The access modifier of static variable can be public, protected, private or default(no modifier). The
access modifier decides visibility/accessibility of the variable within or outside the class. The data type
of static variable can be primitive or non-primitive data type. The name of variable is given by the
programmer. The value of the static variable can be given during declaration or later in the program.
If static variables are not initialized with any value, java will assign a default value as per their data
type.
STATIC VARIABLE MEMORY ALLOCATION
As soon as java virtual machine loads your class inside memory, static variables of your class are
created inside the heap memory and it's created only once, it's not created separately for each object
unlike instance variables. As soon as the execution of a program finishes, static variables are removed
from memory. static variables belongs to class and is common to all objects of a class. There is only
one copy of static variable available that is shared with all the objects of that class, if changes are made
to that variable value using one object, all other objects will also see the effect of changes. The image
below shows how two objects obj1 and obj2 of Student class shares a static variable collegeName
which is created only once.

HOW TO ACCESS STATIC VARIABLE IN JAVA


Since static variables belongs to class, it can be accessed using class name
as className.staticVarName. You can also access static variable using object of a class
as objName.staticVarName but you should prefer to access static variable using class name
as static variables belongs to class not objects. You can access static variables inside static or non-
static methods or blocks.
You can access static variables directly inside your class but outside the class(in other classes) you
must need class name or object name to access the static variables of a class.
STATIC VARIABLE PROGRAM IN JAVA
class Student {
static int total = 40;
117 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static String collegeName = "SUMVS";
}

class StaticVarDemo {
static String test = "Testing static variable";

public static void main(String [] args) {


System.out.println(test+ ", "+ StaticVarDemo.test);
// Accessing Student class static variables
System.out.println("Total students = "+ Student.total);
System.out.println("college name = "+ Student.collegeName);
}
}

WHEN TO CREATE STATIC VARIABLE?


You should create a static variable when you need a variable that should be same for all the objects of
a class or in other way you need a variable that is not different for each objects. For example
a Student class can have a static variable as collegeName, since it will be same for all the students of a
college while variables like name, age, rollNo etc can be declared as instance variables since these will
be different for each students.
STATIC METHOD IN JAVA
static method is similar as normal method except that it has a static keyword in it's declaration. The
basic syntax of declaring a static method is :
access_modifier static return_type methodName(DataType param1, DataType param2 ...){
// one or more line of code
return some_value; // Needed if return_type is not void
}
Example :
public static int getArea(){
// one or more line of code
return some_value;
}
static void calculateVolume(double radius){
// one or more line of code
}
The access modifier of a method can be public, protected, private or default(no modifier). The access
modifier of a method decides visibility/accessibility of a method within or outside the class. The return
type of a method can be primitive or non-primitive data type. If the method doesn't return a value, it's
return type must be void. The name of method is given by the programmer. Parameters are optional,
a static method may or may not have parameters.

HOW TO ACCESS STATIC METHOD IN JAVA


Since static method belongs to a class, you access them using class name
as className.methodName().
118 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
You can access static method using object as objName.methodName() but you should prefer to
access using class name as static method belongs to class not objects. Static method cannot access
non-static variables or methods directly inside it's body, doing so will result in compilation error. You
can create and access local variables inside static method as you do in normal methods. You can
access static methods directly inside your class but outside the class(in other classes) you must need
class name or object name to access the static methods of a class.
STATIC METHOD PROGRAM IN JAVA
class Student {
static int total = 50;
static String collegeName = "SUMVS";
public static void printDetail() {
System.out.println("total students = "+ total);
System.out.println("college name = "+ collegeName);
}}
class StaticMethodDemo {
int count = 20;
static String test = "Learning static method";
public static void main(String [] args) {
StaticMethodDemo.testMethod();
// testMethod(); // Can access testMethod directly as well.
Student.printDetail(); // Calling printDetail method of Student class
// printDetail() // Can't access other class static method directly.
}
static void testMethod() {
// count = count+2; // Static method can't access non-static variables
int num = 30;
System.out.println(test+ ", num = "+num);
}}
Output:
Learning static method, num = 30
total students = 50
college name = SUMVS
WHEN TO USE STATIC METHODS IN JAVA
There are not any defined rules but there are some observations that can be used to
create static methods.
 You want to call method without creating instance of that class.
 If the method doesn't need to access/modify instance variables.
 If the method works only on arguments provided to it. For eg. static int factorial(int number), this
method only operates on number provided to it.
 If it's a kind of utility method. For eg. built-in methods of Math class like log10(double a),
sqrt(double a), cbrt(double a) etc. These are utilities that performs common operations, it
doesn't require any object states.
119 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

WHAT IS A CLASS IN JAVA


Java is an object oriented programming language. Classes and objects are key concepts to
understand object oriented programming. Java programming is based on these two terms. A class is
a group of variables, constructors, methods, blocks etc. These are optional components of a class. A
class is defined using class keyword followed by class name. The name of the class is used to refer
that class within or outside the class. The basic syntax of declaring a class is :
class ClassName{
// variables, constructors,
// method declarations
}
Here class is a keyword, used to define a class in java. ClassName is the name of class, given by the
programmer. After the class name, it's the class body given inside { }. Variables, methods, constructors
etc defined inside the balanced { } after the class name are the part of that class.
Do we have any convention to write the class name?
The convention is that the class name and any subsequent word in class name should start with upper
case, for example MyFirstProgram, HelloWorldProgram, Person, Bicycle etc are valid class names of
this convention.
Is class keyword case-sensitive? All keywords in java are case-sensitive and they must be in
small letter. So you can not use class keyword as Class, CLASS, clAss etc, it must be in small letters.
In object oriented world, think of a class as a blueprint or a design that basically describes how an
object of a class will behave and what data(properties) it will contain inside it. The methods of a class
defines the behavior of object while instance variables are the data of the object that it will contain
inside.
Real time example of class
Some of the real world examples of class are Person, Vehicle, House, Tree, Dog etc. For an example
a Person class have properties like name, age, height etc. and behaviors like walk, talk, eat,
sleep etc. Now if you create an object of this class, it will have these properties and behaviors inside it.
Once you created a class, you can create multiple objects of that class.

Can I give any name to my class ?


Yes, you can give any name to your class by following the identifier naming convention rules but giving
a meaningful name is a good programming style. For example class names like Abc, XYZ are valid
120 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
names but not meaningful names while class names like MyFirstProgram, HelloWorldProgram,
Person are meaningful names.
Java Class Program
class Person{
// Instance variables, describes state/properties of object of this class.
String name;
int age;
int height;
// methods, describes behaviors of object of this class.
public void walk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Walk");
}
public void talk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Talk");
}
}

class ClassDemo{
public static void main(String [] args){
Person p1 = new Person(); // Creating object of class Person
p1.name = "Rahul";
p1.age = 20;
p1.height = 170;
p1.walk();
p1.talk();
}
}
Save above program as ClassDemo.java
compile as javac ClassDemo.java
run as java ClassDemo
Output:
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Walk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Talk
Here we made a class called Person which is a prototype, describing that object of this class will have
properties as name, age, height and will have behaviors as walk and talk. You can add more
properties(instance variables) and behaviors(methods) in your program. This example creates only
a single object of Person class. You can create multiple objects of Person class and assign different
values inside it. Should I create all classes in single file? No, that's not a good programming
style. In real world programming mostly we use to create each classes in separate files in our
application. So next time when you are creating a class, think that you are creating a prototype which
will tell that what properties(state) and behaviors will exist inside the object of that class. This way you
121 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
will get better idea to design your class. A class is also called a blueprint or a template or a design or
a Type. These are just different words use to describe a class in java.
Who loads java classes in memory while execution? As soon as you run a program, the
class-loaders available in java virtual machine loads classes in memory for execution. In java, these
class-loaders are also a program.
Is a must to define variables(instance or static variable) on top of a class?
No, you can define such variables after the method or at the end of a class but that's not a good
programming style. You should always prefer to declare it at top since it makes a class more readable.
Can a class exist without main method?
Yes, in real world programming only the starting class of your application(a group of classes) will have
main method, all other classes won't have main method.
Should I focus more on real world aspect of class?
As a programmer you should focus more on its programming aspect rather than focusing on real world
aspect, programming aspects like creation of class, creation of variables and methods inside the class,
creation of objects of class etc. The syntax of declaring a class given in this section is the minimal one
which is required. Some of the more keywords that can be declared along with class keyword
are public, abstract, final, extends, implements. A class can also have another class, static blocks,
enum etc inside the body of it.
1. Every program must have at least one class, it can have more than one class as well.
2. If there are multiple classes in a single program file, the file must be saved by class name
declared with public keyword, if any.
3. Every class(user defined or defined by java) in java is a non primitive data type.
4. There should be only one main method having argument type as String [] in a class.
5. If there are multiple non public classes in a single program file, conventionally the program file
should be saved by class name having main method.

WHAT IS AN OBJECT IN JAVA


Objects are key concepts of java programming, since java is an OOP language. In object oriented
programming, program focuses on objects rather than logics. In the real world you can see many
examples of object around yourself: a person, your dog, laptop, mobile, bicycle etc. Real world
objects have two features, state and behavior. E.g., a person has states name, age, height etc
and behavior like walk, talk, eat etc while a dog have state like breed, age, color etc and behavior
like run, bark, eat etc. Even software object also have two characteristics : state and behavior.
The state of an object is defined by the instance variables of a class while behavior is defined by the
methods of class. So object in java is a collection of data (instance variables) and methods that acts
on those data. Programmatically an object is an instance of a class. So next time when you are
creating a class, think of two things about it's objects. "What possible states can this object
have?" and "What possible behavior can this object perform?". This way you will get better idea to
design your class. You see software object like below which holds it's state and behavior together with
itself.
122 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

The Syntax given below shows the most basic way of creating an object of a class in java. There are
other ways as well but we will not discuss that here.
ClassName objName = new ClassName();
Here ClassName is the name of class whose object need to be created and objName is the name of
object, given by the programmer. The object name should be unique and should follow the convention
given in identifier naming convention. The keyword new is used to create object in java. Using
the () with ClassName calls the constructor of that class to create and initialize the object in memory.
Let's assume we have two classes Person and MyFirstProgram, code given below shows how to create
an object of these classes :
// Creates an object of Person class with name as obj.
Person obj = new Person();
// Creates an object of MyFirstProgram class with name as mfp.
MyFirstProgram mfp = new MyFirstProgram();

How can I access properties and methods of an object? You just have to apply dot(.)
operator with object name followed by property/method name to access the properties and methods of
an object. You can also change the value of a property of an object using the same operator. Refer
program given below to see the use of this operator.
What if I access object name only? In java object name is a reference, so accessing the name
will return the reference(address) of that object in memory.
Object program in Java
class Person{
// Instance variables, describes state/properties of object of this class
String name;
int age;
int height;
// methods, describes behaviors of object of this class
public void walk() {
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Walk");
}
public void talk(){
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Talk");
123 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
public void eat(){
System.out.println("Hi my name is : "+name+", age : "+age+" year,"
+" height : "+height+" cm. I can Eat");
}
}

class ObjectDemo{
public static void main(String [] args) {
// Creating object p1 of Person class
Person p1 = new Person();
p1.name = "Rahul";
p1.age = 20;
p1.height = 170;
p1.walk();
p1.talk();
p1.eat();
// Creating another object p2 of Person class
Person p2 = new Person();
p2.name = "Rohit";
p2.age = 30;
p2.height = 180;
p2.walk();
p2.talk();
p2.eat();
}
}
Save above program as ObjectDemo.java
compile as javac ObjectDemo.java
run as java ObjectDemo
Output:
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Walk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Talk
Hi my name is : Rahul, age : 20 year, height : 170 cm. I can Eat
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Walk
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Talk
Hi my name is : Rohit, age : 30 year, height : 180 cm. I can Eat
Here p1 and p2 are objects of Person class. Once the code line Person p1 = new Person(); executed,
java constructors creates the object p1 in heap memory and assigns the default values of the instance
variables for this object. After that code lines p1.name, p1.age and p1.height modifies those default
values of the instance variables for this object only. Similarly p2 is also created and assigned the
values of instance variables. All the objects of a class are created inside heap memory. You can think
of object p1 like below.
124 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Who creates objects in java? It's the constructor that creates object of a class inside heap
memory. We will see about constructors in later sections. At runtime each object that you have created
in your program will be allocated space in heap memory. Each object will have it's own copy of instance
variables and methods defined inside the class. Changing the value of a instance variable for one
object will not change the value of that variable for other object.
Can an object exist without a class? No, an object can never exist without a class. Every
object must have a class which defines it's type.
What happens to objects when program execution completed?
As soon as the execution of a program completes, all it's objects are destroyed/removed from memory.
Should I focus more on real world aspect of object?
You should focus more on it's programming aspects rather than on real world aspects, programming
aspects like creation of object, accessing it's fields and methods, accessing object of other class etc.
1. Every object in java has a unique ID, that is not known to external programmers. JVM uses this
id internally to identify each object uniquely.
2. Word object and instance are used interchangeably.
3. Fields, properties, attributes, state of an object refers to same thing which is generally instance
variables of a class.
4. An object can contain another object inside it.
5. Only non-static variables and methods belong to an object of a class.

WHAT IS METHOD IN JAVA


A method is a block of instructions(one or more line of codes) given in { } inside a class. This block is
referred by a name which is basically the method name. The name of method is used to call(invoke)
that method within or outside a class. Once a method is called, the code given inside that method is
executed. After execution a method may or may not return a value. The most basic or
minimal Syntax of declaring a method is:
// Method without parameter
Return_Type methodName(){
// one or more line of code.
return some_value;
}
// Method with parameter
Return_Type methodName(DataType param1, DataType param2 ...) {
125 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// one or more line of code.
return some_value;
}
A method must have a return type which basically tells what type of value this method returns.
The Return_Type of a method can be primitive or non-primitive data type. If a method doesn't return a
value, it's return type must be void or in other way if the return type of a method is void, it means that
method doesn't return any value. The name of the method is given by the programmer. As per the
convention the method name should be in small letters while in multiWord method name, the first letter
of any subsequent word should be in capital letter. E.g., method names like add(), calculateArea(),
getName() etc are some examples of this convention. After method name, it's the parameters given
inside () which are basically variables. Parameters are optional which means a method may or may not
have parameters. You can access these parameters within the method only, not outside the method.
The data type of parameters can be primitive or non-primitive. After parameters it's method body given
inside { }. Everything given inside { } after method name are the part of that method. Let's see some
examples of method declaration.
int add(int num1, int num2){
// one or more line of code.
return value; // returns integer value.
}
void calculateArea() {
// one or more line of code.
}

Can I give any name to method? Yes you can give any name by following the identifier naming
convention but giving a meaningful name is a good programming style. The name should itself suggest
that what this method does. For example method names like xyz(), method123() are valid names but
not meaningful names while names like add(), calculateArea(), getColor() are meaningful names.
Built-in vs. User defined methods
Methods that are defined inside the classes included in java software are known as built-in methods.
For example println() method, String class methods like charAt(), toLowercase(), trim() etc are built-in
methods. The methods that programmers defined inside their classes is known as user defined
methods. It's programmer who gives the name to his method and code inside that method.
Can't I include all code or logic inside a single method? Why I should create
different methods? Yes you can include all logics or code inside a single method but that's not a
good programming style. A good programmer always creates different methods for different tasks
which makes your program more readable and modular.
Parameter vs Argument
Parameters are the variables declared inside the () after the method name. These parameters can be
accessed in a method only. E.g., in method declaration add(int num1, int num2), variables num1
and num2 are parameters. Arguments are the values that are passed to method while calling the
method. For example in a method call add(20,30), 20 and 30 are arguments.
Static and Non Static Method
A method declared with the static keyword is known as static method. Static method belongs to class
not object which means you don't need to create object to access such methods. You can access static
126 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
methods with the class name. Methods defined without static keyword is known as non static method,
also known as instance method. You need object or instance of the class to access such methods. E.g.
in below program calculateArea() is a static method while add(), firstMethod(), secondMethod() are non
static methods. Static method can access only static variables inside it's body while non static method
can access both static and non static variables.
Java Method Program
class MethodDemo{
public static void main(String [] args){
MethodDemo md = new MethodDemo();
int sum = md.add(20,30); // calling add() method
System.out.println("sum = "+sum);
md.firstMethod(); // calling firstMethod() using object
MethodDemo.calculateArea(100,50); // calling calculateArea method using className
}
int add(int num1, int num2){
int sum = num1 + num2;
return sum;
}
void firstMethod(){
System.out.println("Inside first method");
secondMethod(); // calling secondMethod()
System.out.println("After calling second method");
}
void secondMethod(){
System.out.println("Inside second method");
}
static void calculateArea(int length, int width){
int area = length*width;
System.out.println("Area = "+area);
}
}
Output:
sum = 50
Inside first method
Inside second method
After calling second method
Area = 5000
As you can see static method calculateArea() is called using class name MethodDemo. You can
call static method using object as well, but that's not a good practice, since static methods belongs to
class not object. You should always prefer to call static methods using class name.
What is a called method and av calling method?
A method that calls a given method is known as calling method while the method that is being called is
known as called method. E.g., in above program, main() is the calling method for called methods
firstMethod() and calculateArea().
127 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Can I pass object inside method calling?


Yes you can pass objects as well inside the method. Any changes made in that object in called method
will be reflected in calling method as well.
How method execution happens in Java?
As soon as a method is called, the execution of that method get's started. Once the execution of
method completed or any return keyword encountered, the execution control comes back to the
position from where it was called. Once a method is called, java creates a new stack inside stack
memory where all local variables of that method are initialized. E.g. in above program once line int sum
= md.add(20,30); executed, the execution of add method get's started. As soon as the return statement
in add method is executed, the execution control again comes back to the line int sum =
md.add(20,30); where the value returned by add method is assigned in variable sum.
What is method signature?
The name and the parameters of a method in a method declaration is referred as method signature.
Other components like access modifiers, return type etc are not the part of method signature. For
example method signature of add method in above program is add(int num1, int num2). You can define
multiple methods with same name having different parameter lists. Java differentiates such methods on
the basis of the number of parameters in the list and their types. This is known as method overloading.
The syntax of declaring a method given in this section is the minimal one which is required. Apart from
this there are couple of more keywords as given below that can be used with method declaration. An
access modifier(public, protected, private) can also be used with method declaration. Access
modifiers decides the visibility/accessibility of method within or outside the class. For example
a private method can only be accessed within the class while public method can be accessed from
outside the class as well. final keyword can also be used with method declaration. final method can not
be overridden. abstract keyword can also be used with method declaration. The implementation or
definition of abstract method is defined by sub class. A method can also declare an exception
using throws keyword.

CONSTRUCTORS IN JAVA
Constructor in java is used in creation and initialization of object of a class inside memory. It's the
constructor that offers the initial values of instance variables for an object inside memory. Constructors
declarations are similar as method declarations except that constructors don't have any return type and
their name is same as class name. The syntax of declaring a constructor is :
class MyClassName {
// No-argument constructor
Access_Modifier MyClassName() {
// Initialization code
}
// Parameterized constructor
Access_Modifier MyClassName(DataType param1, DataType param2 ...) {
// Initialization code
}
}
Example :
128 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
class Person{
Person() {
// Initialization code
}
public Person(int param1, String param2) {
// Initialization code
}
}
Access modifier of a constructor can be public, private, protected or default(no modifier). These
modifiers with constructors decides the accessibility(visibility) of the constructor within or outside the
class. After access modifier it's the name of constructor which must be same as the class name.
Parameters in constructors are optional, a constructor may or may not have parameters. A
constructor without parameter is also known as no-argument constructor while a constructor with
parameter is also known as parameterized constructor. The data type of parameters can be primitive
or non-primitive. In constructor body generally we initialize instance variables with some values but it's
not limited to that only. You can use other statements as well as you do in methods. You can define
multiple constructors with different argument lists. Java differentiates constructors on the basis of the
number of arguments in the list and their types. This is also known as constructor overloading. You
cannot write two constructors that have the same number and type of arguments for the same class,
because java compiler would not be able to differentiate them. In this case compiler will throw error.
Types of Constructors in Java
Constructor can be divided in three types.
1.No-argument constructor 2.Parameterized constructor 3.Default constructor
We have already covered the definition of first two constructor. We will see how to use them in program
example given below.
How constructors are invoked(called)?
Constructors are invoked automatically when the code that creates object of a class using new keyword
is executed.
Constructor Program in Java
class Person{
int age;
int height;
String name;
// No-argument constructor
public Person() {
System.out.println("Initialization using no-argument constructor");
age = 15;
height = 160;
name = "Pradeep";
}
// Parameterized constructor
public Person(int a, int h, String n) {
System.out.println("Initialization using parameterized constructor");
129 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
age = a;
height = h;
name = n;
}
public static void main(String [] args) {
Person p1 = new Person(); // invokes no-argument constructor
p1.print();
Person p2 = new Person(20,170,"Rahul"); // invokes parameterized constructor
p2.print();
}
void print() {
System.out.println("age = "+age+", height = "+height+", name = "+name);
}
}
Output:
Initialization using no-argument constructor
age = 15, height = 160, name = Pradeep
Initialization using parameterized constructor
age = 20, height = 170, name = Rahul
How constructor works in Java
Let's understand this by above program. Once the code new Person(); is executed, it creates the object
of Person class inside memory and invokes the no-argument constructor which executes the given print
statement and assigns values of instance variables for this object. Finally the reference of this object is
assigned into p1. Similarly code new Person(20,170,"Rahul"); creates another object inside memory
and invokes the matching parameterized constructor which assigns values passed to it in
corresponding instance variables for object p2. So both objects will have their specific values of
instance variables. You can imagine the object p2 inside memory like below.

Can I create a class that have only no-argument or parameterized constructors?


Yes you can create a class that have only no-argument constructor or only parameterized constructor.
While creating the object you just have to ensure that the class contains the matching constructor
otherwise your program won't compile. For example if you try to create an object of Person class in
above program like below, compiler will throw error since it would not find the matching constructor.
// Both statements will result in compilation error as it won't find matching constructor
130 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Person p3 = new Person(20,"Rahul");
Person p4 = new Person(20, 170.5,"Rahul");

What is default constructor


If you don't write any constructor in your class, java compiler inserts a no-argument constructor in
your .class file after compilation of your program. This constructor is known as default constructor since
it is given by java compiler. For a class Person having no constructors defined, the default constructor
will look like below.
Person() {

}
The default constructor assigns default values for non-initialized instance variables of an object, for
example an integer instance variable will have value as 0 while a string variable will have value as null
etc. If you have made any constructor(no-argument or parameterized) in your class, java won't provide
default constructor to your class. Constructors created by programmers is also known as user defined
constructor.
Is no-argument constructor is same as default constructor?
Default constructor is also a constructor without argument but if you have created a no-argument
constructor in your class that will be a user defined constructor, not default constructor. Sometimes
programmers get confused about the same.
What is implicit and explicit constructor?
Default constructor is also known as implicit constructor while constructors defined by programmer's in
a class is known as explicit constructor.
Can we invoke constructors like methods?
Constructors can not be invoked like methods. Constructors are invoked automatically. Though you can
call one constructor from other constructor of same class using this keyword like below.
public Person() {
this(15,160,"Pradeep"); // invokes parameterized constructor
}
public Person(int a, int h, String n) {
age = a;
height = h;
name = n;
}
Similarly you can call other constructors if you have in your class by passing the number of arguments.
To call no-argument constructor use this(). If you are calling a constructor using this keyword, ensure
that it's the first statement in constructor body otherwise compiler will throw error. We will get to know
more about this keyword in later sections.
What is private constructor?
A constructor declared with private modifier is known as private constructor. If a class contains only
private constructor, you cannot create object of that class outside the class since your constructor won't
be accessible(visible) outside the class.
DIFFERENCE BETWEEN CONSTRUCTOR AND METHOD
131 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

CONSTRUCTOR METHOD
Constructor name must be same as the class Method name may or may not be same as class
name. name.
Constructor must not have return type. Method must have return type.
Constructor is used to initialize the state of an
Method is used to expose behavior of an object.
object.
Constructor is invoked(called) implicitly. Method is invoked explicitly.
Java compiler provides a default constructor if you Method is not provided by java compiler in any
don't declare any constructor in your class. case.
You can not use keywords like abstract, final,
These keywords can be used with methods.
static etc with constructors.
1. A method can also have same name as class name but it must have return type which
differentiates it from constructor.
2. Declaring a method name same as class name is not a good programming style.
3. Every class has a constructor whether it's a normal class or a abstract class.
4. You can call a method inside a constructor as well.

Java static Keyword


static is a keyword in java which is used very often in java programs. Sometimes beginners faces
difficulty to understand what exactly the static keyword does and why to use this. This section explains
different usage of static keyword and also covers different questions like when, how and why do we
use static keyword in java. Generally you need an object of a class to access members like variables
and methods of that class, because these members belongs to object or instance of that class. Each
object have their specific values for such members. But sometimes we need members that should
belong to class rather than objects and should be same for all the objects. To achieve this java
provides static keyword. static members belongs to class not objects. You can access such members
using class name itself rather than objects. Let's see the different usage of static keyword.
static variable, static method, static block, static inner class
Java static variable
A static variable is similar as normal variable except that it has a static keyword in it's declaration
. static variables are also called as class variables as these variables belongs to class not objects.
These variables must be made inside a class but outside any method or block. If you create static
variable inside any static or non-static method or block, compiler will throw compilation error. The
basic syntax of declaring a static variable is :
class className {
access_modifier static dataType varName;
access_modifier static dataType varName = value;
}
Example :
class Student {
132 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static int total;
public static String collegeName = "SUMVS";
}
The access modifier of static variable can be public, protected, private or default(no modifier). The
access modifier decides visibility/accessibility of the variable within or outside the class. The data type
of static variable can be primitive or non-primitive data type. The name of variable is given by the
programmer. The value of static variable can be given during declaration or later in the program.
If static variables are not initialized with any value, java assigns a default value as per their data type.
Static variable memory allocation
As soon as java virtual machine loads your class inside memory, static variables of your class are
created inside the heap memory and it's created only once, it's not created separately for each object
unlike instance variables. As soon as the execution of your program finishes, static variables are
removed from memory. static variables belongs to class and is common to all objects of a class. There
is only one copy of static variable available that is shared with all the objects of that class, if changes
are made to that variable value using one object, all other objects will also see the effect of changes.
The image below shows how two objects obj1 and obj2 of Student class shares
a static variable collegeName which is created only once.

How to access static variable in Java


Since static variables belongs to class, it can be accessed using class name
as className.staticVarName. You can also access static variable using object of a class
as objName.staticVarName but you should prefer to access static variable using class name
as static variables belongs to class not objects. You can access static variables inside static or non-
static methods or blocks. You can access static variables directly inside your class but outside the
class(in other classes) you must need class name or object name to access the static variables of a
class.
Static variable program in Java
class Student {
static int total = 40;
static String collegeName = "SUMVS";
}
class StaticVarDemo {
static String test = "Testing static variable";
public static void main(String [] args) {
133 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println(test+ ", "+ StaticVarDemo.test);
// Accessing Student class static variables
System.out.println("Total students = "+ Student.total);
System.out.println("college name = "+ Student.collegeName);
}
}
Output:
Testing static variable, Testing static variable
Total students = 40
college name = SUMVS
When to create static variable?
You should create a static variable when you need a variable that should be same for all the objects of
a class or in other way you need a variable that is not different for each objects. For example
a Student class can have a static variable as collegeName, since it will be same for all the students of a
college while variables like name, age, rollNo etc can be declared as instance variables since these will
be different for each students.
Static method in Java
static method is similar as normal method except that it has a static keyword in it's declaration. The
basic syntax of declaring a static method is :
access_modifier static return_type methodName(DataType param1, DataType param2 ...){
// one or more line of code
return some_value; // Needed if return_type is not void
}
Example :
public static int getArea() {
// one or more line of code
return some_value;
}
static void calculateVolume(double radius) {
// one or more line of code
}
The access modifier of a method can be public, protected, private or default(no modifier). The access
modifier of a method decides visibility/accessibility of a method within or outside the class. The return
type of a method can be primitive or non-primitive data type. If the method doesn't return a value, it's
return type must be void. The name of method is given by the programmer. Parameters are optional,
a static method may or may not have parameters.
How to access static method in Java
Since static method belongs to class, you can access them using class name
as className.methodName(). You can also access static method using object
as objName.methodName() but you should prefer to access using class name as static method
belongs to class not objects. Static method can not access non-static variables or methods directly
inside it's body, doing so will result in compilation error. You can create and access local
variables inside static method as you do in normal methods.
134 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
You can access static methods directly inside your class but outside the class(in other classes) you
must need class name or object name to access the static methods of a class.
STATIC METHOD PROGRAM IN JAVA
class Student {
static int total = 50;
static String collegeName = "SUMVS";

public static void printDetail() {


System.out.println("total students = "+ total);
System.out.println("college name = "+ collegeName);
}}

class StaticMethodDemo {
int count = 20;
static String test = "Learning static method";

public static void main(String [] args) {


StaticMethodDemo.testMethod();
// testMethod(); // Can access testMethod directly as well.
Student.printDetail(); // Calling printDetail method of Student class
// printDetail() // Can't access other class static method directly.
}
static void testMethod() {
// count = count+2; // Static method can't access non-static variables
int num = 30;
System.out.println(test+ ", num = "+num);
}}
Output:
Learning static method, num = 30
total students = 50
college name = SUMVS

WHEN TO USE STATIC METHODS IN JAVA


There are not any defined rules but there are some observations that can be used to
create static methods.
 You want to call method without creating instance of that class.
 If the method doesn't need to access/modify instance variables.
 If the method works only on arguments provided to it. For eg. static int factorial(int number), this
method only operates on number provided to it.
 If it's a kind of utility method. For eg. built-in methods of Math class like log10(double a),
sqrt(double a), cbrt(double a) etc. These are utilities that performs common operations, it
doesn't require any object states.

Call by Value in Java


Call by value and call by reference is a mechanism of passing argument while calling a method. When
we pass an argument to a method while calling, it is passed using either call by value or call by
135 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
reference mechanism. Since java uses only call by value mechanism, so we will discuss only call by
value mechanism. Java doesn't uses call by reference mechanism in any way for passing argument to
methods. Before we understand call by value mechanism, let's first understand how a variable or object
is stored in java, it will help us to understand the mechanism better. In java all primitive types are value
types which means all primitive variables in java stores it's value directly inside memory. While all non
primitive types are reference types which means non primitive variables stores the references, not the
value(object) directly. The actual object in java is created somewhere else in memory, the reference of
this object is stored as value in non primitive variable. Let's understand this by an example and image
below to clarify the things properly. Let's consider Person is a class.
int count = 20;
Person p = new Person();

As you can see the value of variable count is stored directly. If you access the count in your program,
it's the value that will be returned. While variable p holds the reference of actual object as value, the
actual Person object is created somewhere else. So if you access the non primitive variable, it's the
reference of actual object that will be returned not the actual object itself.
Note: The reference(Person@15db9742) of object p given in above image is not the exact memory
address. It is just used as an example to understand how non-primitive variables are stored in java.
How parameters are passed in Java
In java whenever you are passing a primitive type variable, it's the copy of variable value that is passed
to called method. This value is now referred by corresponding called method parameter. So if you
make any changes in that parameter value, it won't be reflected in calling method. While when we pass
reference type variable, it's the copy of reference that is passed to called method. Since this reference
points to an actual object, if you make any changes using this reference, the changes will be reflected
in both the methods, calling and called methods.
How references are passed in java ?
In java, the reference of an object is itself a value. In call by value mechanism, this value(reference) is
itself passed to called method.
Call by value program in Java
The program below shows the call by value mechanism for primitive type variables in java. The
changes made in called method will not be reflected in calling method.
class CallByValue {
136 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static int a = 20;
public static void main(String [] args) {
int b = 30;
System.out.println("Before method call, a = "+a+ ", b = "+b);
changeValues(a,b);
System.out.println("After method call, a = "+a+ ", b = "+b);
}
public static void changeValues(int p, int q) {
p = 40;
q = 50;
System.out.println("In changeValues method, a = " +a+ ", p = "+p+", q = "+q);
}
}
Output:
Before method call, a = 20, b = 30
In changeValues method, a = 20, p = 40, q = 50
After method call, a = 20, b = 30
As you can see from the output, even after changing the values in changeValues method, the value of
variable a and b is still stay same in main method, since it's a copy of value of variable a and b which is
passed to called method. The program below shows the call by value mechanism for reference type
variables. The changes made in called method would be reflected in calling method as well.
class Person {
int age;
int height;
public Person(int a, int h) {
age = a;
height = h;
}
public static void main(String [] args) {
Person p = new Person(20,170);
System.out.println("Before method call, age = "+p.age+ ", height = "+p.height);
changeValues(p);
System.out.println("After method call, age = "+p.age+ ", height = "+p.height);
}
public static void changeValues(Person q) {
q.age = 30;
q.height = 180;
System.out.println("In changeValues method, age = "+q.age+ ", height = "+q.height);
}
}
Output:
Before method call, age = 20, height = 170
In changeValues method, age = 30, height = 180
After method call, age = 30, height = 180
137 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
As you can see from the output, after changing the values in changeValues method, the value of
attributes age and height for object p is changed. This is happening because the reference of
object p is passed to method changeValues which is then assigned in object q. Object q makes the
changes on same reference that is why the changes are reflected in calling(main) method as well.
If you assign null or create and assign a new object(new Person(30,160)) to object q in above example,
the actual object p will not be affected, it will still be pointing to same object.
How String variables are passed in Java
Since String is also a non primitive data type in java, so it's the reference of variable which is passed to
called method. But the interesting thing is that, if you make any changes in String variable in called
method, it doesn't reflects in calling method. Let's see the example first, then we will understand the
reason behind this.
class CallByValueForString {
public static void main(String [] args) {
String str = "String";
StringBuffer strbuf = new StringBuffer("StringBuffer");
System.out.println("Before method call, str = "+str+ ", strbuf = "+strbuf);
changeValue(str,strbuf);
System.out.println("After method call, str = "+str+ ", strbuf = "+strbuf);
}
public static void changeValue(String temp, StringBuffer tempbuf) {
temp = "String Modified";
tempbuf = tempbuf.append(" Modified");
System.out.println("In changeValue method, temp = "+temp+ ", tempbuf =
"+tempbuf);
}
}
Output:
Before method call, str = String, strbuf = StringBuffer
In changeValue method, temp = String Modified, tempbuf = StringBuffer Modified
After method call, str = String, strbuf = StringBuffer Modified
As you can see from the output, the value of String variable str doesn't change even after method call
while the value of StringBuffer variable strbuf get's changed after method call. This is because String in
java is immutable while StringBuffer is mutable. If you make any changes in String variable, a new
string is created inside the string pool, the original string still remains same that is why the value
of str doesn't change even after method call.
What if I pass objects of wrapper classes like Integer, Float, Character etc in method
calling? Wrapper classes in java are also immutable like String class, if you make any changes in
called method, it won't be reflected in calling method.
1. call by value and pass by value are same thing.
2. Actual object itself is never passed, it's the reference of actual object which is passed to called
method.
3. You can change only state/attribute of object using the reference in called method.
4. In C/C++, the reference directly points to the memory address of a variable.
138 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
5. If you are passing expressions like a+b, a*b etc, it's the final evaluated value of expression that
will be passed to called method.

Java Nested/Inner Classes


Similar to variable and methods, java allows us to create a class within another class. Classes defined
inside another classes are known as nested classes. Here we explain different details of nested
classes like types of nested classes, program of nested classes, why we use nested classes, when we
use nested classes etc. The basic syntax of a nested class is :
class OuterClassName {
...
class NestedClassName {
...
}
}
Types of Nested classes in Java
Nested classes are divided into two categories: static and non-static. Nested classes that are
declared using static keyword are called static nested classes. Non-static nested classes are called
inner classes. Nested classes can be divided as below :
1. Non-static nested class (inner class)
Member inner class
Local inner class
Anonymous inner class
2. Static nested class
Does java creates different .class files for nested or inner classes ?
Yes, Java compiler creates different .class file for outer and inner class of a program after compilation.
Generally the inner class .class file name is made with combination of outer and inner class name with
$ sign in between like OuterClassName$InnerClassName.class
Member Inner class
A class defined inside another class but outside any method or block is known as member inner class.
These classes act as a member of outer class similar as member variables and methods. The
basic syntax of declaring a member inner class is :
class OuterClassName {
...
access_modifier class MemberInnerClassName {
...
}}
Example :
class OuterClass {
...
public class InnerClass {
...
}}
Some of the key points about the member inner classes are :
139 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 It can have all type of access modifiers(public, private, protected or default) in it's declaration.
Remember, the outer most class can have only public and default(no modifier) modifier in it's
declaration.
 These classes can also be declared as abstract or final.
 It can access any member of the outer class, whether they are static, private or anything else.
 These classes can only define non-static members inside it.
 Like instance variables and methods, inner classes are also associated with an instance of the
outer class.
Remember a class can not be declared as abstract and final together, no matter whether it's an inner or
outer class.
How to create object of member inner class ?
Since these classes belongs to an object, you should create the object of its outer class first then
create the object of inner class using the outer class object like below :
OuterClassName outer = new OuterClassName();
OuterClassName.InnerClassName inner = outer.new InnerClassName();
Here OuterClassName and InnerClassName is the name of outer and inner class respectively
while outer and inner is the name of outer and inner class object respectively. As you can access
member variables of a class directly inside a non-static method, similarly you can directly create the
object of member inner class inside a non-static method of outer class, as given in below program
inside the run method. Remember outside the outer class, you must need the reference of outer class
to create the object of member inner class.
Member inner class program in Java
class OuterClass {
int outerVar = 100;
class MemberInnerClass {
int innerVar = 50;
int getSum(int param) {
return innerVar + outerVar + param;
}}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.MemberInnerClass inner = outer.new MemberInnerClass();
System.out.println(inner.getSum(10));
outer.run();
}
void run() {
MemberInnerClass memberInner = new MemberInnerClass();// Creating object directly
System.out.println(memberInner.getSum(20));
}}
Save above program as OuterClass.java, compile as javac OuterClass.java. Java compiler will
create two .class file, OuterClass.class and OuterClass$MemberInnerClass.class for above program.
Run as java OuterClass
140 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Output:160
170
Local or method local Inner class
Local inner class is a class which is defined inside a method or block of outer class, like local variables.
It can be defined inside static or non-static method. These classes are accessible within the method
only, similar as local variables. The key points about the local inner classes are :
 They cannot have access modifiers(public, private, protected) in their declaration.
 The only modifiers that you can use with local inner class declaration are abstract and final.
 They can access any member of outer class, whether they are static, private or anything else.
 These classes can only define non-static members inside them.
 They can access only final variables of it's enclosing method. Accessing non-final variables of it's
enclosing methods will result in compilation error.
How to create object of local inner class?
Creation of local inner class object is similar as creation of normal objects like below. You don't need
the reference of outer class object, as local inner class belongs to method only.
LocalInnerClassName objName = new LocalInnerClassName();
Here LocalInnerClassName is the name of local inner class while objName is the name of local inner
class object.
Java program of local inner class
class OuterClass {
int outerVariable = 100;
static int staticOuterVariable = 200;
public static void main(String[] args) {
OuterClass outer = new OuterClass();
int sum = outer.run();
System.out.println("Total sum = "+ sum);
}
public int run() {
int localVar = 50;
final int finalLocalVariable = 60;
// Creating local inner class
class LocalInnerClass {
int innerVariable = 20;
int getSum(int parameter) {
// Cannot access localVar here as it's not declared as final
return outerVariable + staticOuterVariable + finalLocalVariable +
innerVariable + parameter;
}}
LocalInnerClass local = new LocalInnerClass();
return local.getSum(10);
}}
141 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Save above program as OuterClass.java, compile as javac OuterClass.java and run as java
OuterClass
Output:
Total sum = 390
Anonymous Inner Class
An anonymous inner class is a class that has no name. These classes are usually declared inside a
method or block, but it can be defined outside a method or block as well. They are generally used to
define an implementation of interface or abstract class. It can be a re-implementation of a normal or
super class as well. The key points about anonymous inner classes are :
 They cannot have access modifiers(public, private, protected) in their declaration.
 These classes ends with a semicolon(;) after curly braces }.
 They can access any member of outer class, whether static, private or anything else.
 These classes can only define non-static members inside it, not static members.
 This is the only type of inner class that cannot define constructors since it doesn't have a name.
 These classes can be defined as a parameter inside a method as well.
How to create anonymous inner class ?
The creation of anonymous inner class is little different than normal class creation. It starts
with new keyword followed by the name of class/interface that need to be implemented. It's similar as
constructor creation except that it has a body. These classes are declared and used to create one
object in a single statement. The creation of anonymous class looks like below :
// As implementation of a class
new ClassName() {
// class body
};
// Here parameters will be passed to constructor of defined ClassName.
new ClassName(parameters) {
// class body
};
// As implementation of interface
new InterfaceName() {
// class body
};
// Or It can be defined like below as well
ClassOrInterfaceName objName = new ClassOrInterfaceName() {
// class body
};

Here ClassName/InterfaceName/ClassOrInterfaceName is not the name of anonymous class, it's


already defined an abstract class, superclass, normal class or interface name.
Anonymous inner class program in Java
The program below defines a simple abstract class first. The anonymous class implements this abstract
class.
abstract class MyAbstractClass {
abstract void run();
142 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
class OuterClass {
public static void main(String args[]) {
MyAbstractClass obj = new MyAbstractClass() { // Start of anonymous class body
int innerVariable = 100;
public void run() {
System.out.println("innerVar = "+ innerVariable);
System.out.println("Inside anonymous inner class method");
}
}; // End of anonymous class
obj.run();
}}
Save above program as OuterClass.java, compile as javac OuterClass.java and run as java
OuterClass
Output:innerVar = 100
Inside anonymous inner class method
Static Nested class
Classes that are defined inside the class but outside any method or block using static keyword are
called static nested classes. These classes act as static member of outer class which means these
classes belongs to outer class, not the object of outer class. The key points of static nested classes are
 It can have all type of access modifiers(public, private, protected or default) in it's declaration.
 These classes can also be declared as abstract or final.
 It can not access non-static members of outer class directly but using outer class object it can
access them.
 It can define both static and non-static members inside it's body.
 You can access these classes directly inside the containing/outer class. To access from a class
outside the containing class, use the syntax OuterClassName.StaticClassName.
How to create object of static nested class?
Inside the outer(enclosing) class, you can directly create the object of static nested class, but outside
that, you need the outer class name to create the object of static nested class.
// Inside outer/enclosing class
StaticClassName objName = new StaticClassName();
// Outside the outer class
OuterClassName.StaticClassName objName = new OuterClassName.StaticClassName();
Here OuterClassName and StaticClassName is the name of outer class and static nested class
respectively while objName is the name of static nested class object.
Can I create object of static nested class using outer class object?
No you cannot, since these classes belongs to class(outer class) and not to an instance of the outer
class, doing so will result in compilation error.
Static nested class program in Java
class OuterClass {
int outerVariable = 50;
143 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static int staticOuterVariable = 100;
static class StaticNestedClass {
int innerVariable = 10;
int getSum(int parameter) {
// Cannot access outerVariable here directly as it's not static
return innerVariable + staticOuterVariable + parameter;
}}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
StaticNestedClass inner = new StaticNestedClass();
System.out.println("Sum = "+ inner.getSum(20));
outer.run();
}
void run() {
StaticNestedClass inner = new StaticNestedClass();
System.out.println("Inside run method, Sum = "+ inner.getSum(40));
}}
Save above program as OuterClass.java, compile as javac OuterClass.java and run as java
OuterClass
Output: Sum = 130
Inside run method, Sum = 150
Why we use nested class in Java
There are couple of reasons for using nested classes which includes the following :
 Nesting of classes is a way of logically grouping classes that are only used in one place. If your
class is useful to only one other class, then it's logical to include it in that class and keep both
classes together.
 Nesting of classes helps to write more readable and maintainable code: Nesting small classes
within top-level classes places the code closer to where it is used which makes easy for
programmer to read and modify the code whenever required.
 Nesting also increases encapsulation. Consider classes A and B, where B needs access to
members of A which needs to be declared as private. By hiding class B within class A, A's members
can be declared private and B can access them. Furthermore, B itself will be hidden from the
outside world.
When to use nested classes in Java
When you know that your class is going to be used by one class only or your class will act as a helper
class to it's outer class, you should make your class as inner class. Moreover if you know that the
existence of your class is dependent on one other class only, declare your class as inner class inside
that class. In java, HashMap class contains number of inner classes like KeySet, EntrySet, Node etc
which acts as helper class to HashMap class.
1. A nested class can have another nested class inside it.
2. Nesting of classes can be done any number of time, however doing more than one level of
nesting is not a good design as it increases complexity.
3. You can define different types of nested classes together inside a class.
144 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
4. Nested classes except anonymous class can extend/implement other classes or interfaces as
well.
5. Anonymous class internally extends/implements implemented class/interface.
6. Using anonymous class object you can access variables and methods of implemented
class/interface only. Any new variable or method defined inside anonymous class won't be
accessible by it's object.
7. Members of all nested classes can have any access modifiers in their declaration.
8. You can also define nested class inside an interface.

Java Wrapper Classes


In this section we will discuss details of wrapper classes like what wrapper classes is, list of wrapper
classes, conversion from primitive to wrapper type and vice-versa, AutoBoxing and Unboxing, java
program of primitive to wrapper conversion, why do we use wrapper classes etc.
Define wrapper class in Java
In java all primitive data types are value types which means the variable of primitive types holds values
directly in memory. Java provides inbuilt classes corresponding to each primitive type that can be used
to convert these value types in object types. These inbuilt classes are known as wrapper classes or
primitive wrapper classes. The table below shows the list of all primitive data type and their
corresponding wrapper class.

These classes are called wrapper classes since it wraps(encloses) around primitive types and converts
them into object or non-primitive type. In addition, these classes also contains some useful methods
which are often used in java programs.
Conversion from primitive to wrapper class
The code below shows how to convert a primitive int and double value to to their corresponding
wrapper type. Similarly other primitive values can also be converted in to their respective wrapper type.
145 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
int i = 100;
// Converting into wrapper object
Integer itr = new Integer(i);
// OR
Integer itr = Integer.valueOf(i);
// OR
Integer itr = i;
double d = 10.5;
Double db = new Double(d);
// OR
Double db = Double.valueOf(d);
// OR
Double db = d;
After conversion we can use different methods of wrapper class with it's object. In above example we
can call methods of Integer class with object itr.
Conversion from wrapper class to primitive
You can get back the original primitive value from the wrapper object using the wrapper class method
or by directly assigning the wrapper object into corresponding primitive variable. Similar methods are
available in other wrapper classes as well to get the original primitive value.
Integer in = new Integer(100);
// Converting into primitive type
int i = in.intValue();
// OR
int i = in;
Double db = new Double(10.5);
double d = db.doubleValue();
// OR
double d = db;

AUTOBOXING AND UNBOXING IN JAVA


Autoboxing: The automatic conversion of primitive type into an object of corresponding wrapper
type is known as autoboxing. For example conversion of an int to an Integer or double to Double and
so on. Autoboxing happens automatically, it's the compiler who does this for us.
Unboxing: The automatic conversion of wrapper type object into corresponding primitive type is
known as unboxing. For example conversion of Integer to an int or Double to double and so on. It also
happens automatically, done by java compiler.
int i = 100;
double d = 10.5;
// Following are autoboxing
Integer in = i;
Integer ig = 20;
Double db = d;
Double dl = 20.5;
146 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// Following is not autoboxing
// Integer in = new Integer(i);

----------------------------------------

Integer in = new Integer(100);


Double db = new Double(20.5);
// Following are unboxing
int i= in;
double d = db;
int j = new Integer(50);
double k = new Double(50.5);
// Following is not unboxing
// int i = in.intValue();

WRAPPER CLASS PROGRAM IN JAVA


class WrapperClassExample {
public static void main(String args[]) {
int i = 50;
double d = 20.5;
// Converting primitives into objects
Integer intObj = new Integer(i);
Double doubleObj = new Double(d);
System.out.println("........ Printing wrapper objects ........ ");
System.out.println("Integer object : "+intObj+", Double object : "+doubleObj);
// Can use below as well for conversion
Integer intObj2 = Integer.valueOf(i);
Double doubleObj2 = Double.valueOf(d);
System.out.println("intObj2 : "+intObj2+", doubleObj2 : "+doubleObj2);
// Autoboxing : Converting primitives into objects
Integer intObj3 = i;
Double doubleObj3 = d;
System.out.println("intObj3 : "+intObj3+", doubleObj3 : "+doubleObj3);
// Converting the wrapper object to primitive
int in = intObj.intValue();
double db = doubleObj.doubleValue();
System.out.println("........ Printing primitve values ....... ");
System.out.println("int value : "+in+", double value : "+db);
//Unboxing : Converting the wrapper object to primitive
int in2 = intObj;
double db2 = doubleObj;
System.out.println("int value2 : "+in2+", double value2 : "+db2);
}
}
147 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Output:
........ Printing wrapper objects ........
Integer object : 50, Double object : 20.5
intObj2 : 50, doubleObj2 : 20.5
intObj3 : 50, doubleObj3 : 20.5
........ Printing primitve values .......
int value : 50, double value : 20.5
int value2 : 50, double value2 : 20.5
String to numeric conversion in Java
If a number is presented in string form, it can be converted to a numeric value using methods of
wrapper class. E.g., string "100" can be converted into numeric value 100 using wrapper class method.
Each of the wrapper classes (except Character class) has a method like parseXXX(String) which
converts a numeric string into a numeric value. A numeric value can be converted into string
using toString() method of wrapper classes.
The command line arguments are also passed as string. If it's a numeric string we can convert that
string to numeric value using wrapper class methods. The program below shows the conversion of
numeric string to numeric value and vice-versa.
class StringConversion {
public static void main(String args[]) {
String str = "100";
String str2 = "100.5";
int i = Integer.parseInt(str);
double d = Double.parseDouble(str2);
System.out.println("int value: "+i+", double value: "+d);
// Converting integer value to string
String str3 = Integer.toString(i);
System.out.println("String value: "+str3);
// Converting command line argument
if(args.length != 0) {
int j = Integer.parseInt(args[0]);
System.out.println("Command line integer value = "+j);
}}}
Let's execute below commands to compile and execute the above program.
javac StringConversion.java
java StringConversion 500
Here argument 500 will be passed as string to main method which get's stored in args[0]. This string is
then converted to an integer value using parseInt method of Integer class.
Output:
int value: 100, double value: 100.5
String value: 100
Command line integer value = 500
148 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
What if I try to convert a non numeric string to numeric value using wrapper class
methods?The program will throw NumberFormatException. For example if you run command java
StringConversion hello for above program, it will throw the exception because a non numeric string
can not be converted to an integer.
USE OF WRAPPER CLASSES IN JAVA
 List given below points some of the reasons to use the wrapper classes in java :
 To convert the primitive data types to object or non-primitive types.
 To convert the numeric strings into numeric values.
 Data structures in collection framework such as ArrayList, LinkedList, HashMap etc works with
object types only and not primitive types. Example :
ArrayList<Integer>
HashMap<Integer,String>
ArrayList<int> // compilation error
 Wrapper classes provide many ready to use utility methods, for example Character class
provides method to convert a char value to upper/lower case, Integer class provides method to
find min/max of two number etc.
 Primitive data types are passed by value while objects are passed by reference to a method.
Wrapper classes provides the ability to pass primitives types as reference type to a method.

What is Enum in Java


Enum in java is very similar as classes with some restrictions. Enums are generally used to declare a
fixed set of constants. For example the directions(EAST, WEST, NORTH and SOUTH) of a compass or
days(Sunday, Monday ...) of a week can be represented as enum type. An enum is defined
using enum keyword. Every enum that we define acts as a Type(data type) which is used to refer the
constants of that enum within or outside the enum type. An enum type is also referred as enumeration
type. Every enum that we define is also known as enum type, so words enum and enum type are used
interchangeably. Java enums are added from java version 1.5.
Enum declaration in Java
An enum type can be declared separately or it can be declared anywhere inside a class/interface but
not inside a method. If defined separately, they must be saved with .java extension. The
basic syntax of declaring an enum type is :
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3, ... ;
}
Example:

enum Directions{
EAST, WEST, NORTH, SOUTH;
}
Here EnumName is the name of enum type given by the programmer. An enum type may contain any
number of constants. Everything that comes within { } after enum name is the enum body. Semicolon at
the end of constants is optional if enum type contains only constants. An enum may contains
constructors and methods. Every enum in java is internally implemented as class and every constant of
149 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
an enum is an instance of that class. Each enum type that we define, internally extends java's
predefined Enum class. Above enum declaration will be converted as a class like below :
final class Directions extends java.lang.Enum {
private Directions(){}
public final static Direction EAST = new Direction();
public final static Direction WEST = new Direction();
public final static Direction NORTH = new Direction();
public final static Direction SOUTH = new Direction();
}
Since each enum type extends pre-defined Enum class, it can not extend any other enum type or
class, since multiple inheritance in java is not supported. We will discuss inheritance(extends keyword)
in later section. An enum type can implement interfaces as well. Also notice that each constant is
declared as public static final. Since it's static, it can be accessed using enum name. Since it's final, it
can not be changed once created. It can be changed at design time only.
What does java compiler creates after compilation of an enum type ?
It creates a .class file with same name as enum name.
Is it mandatory to give the enum constants in upper-case?No, it's not mandatory,
you can give in lower case as well but java convention says that enum constants should be declared in
upper case letters.
How to access enum constants
An enum constant can be accessed using enum name. The value of an enum type variable can only be
a constant from the list of constants defined inside the enum type. The value of enum type constant is
same as the text of enum constant.
EnumName varName = EnumName.ConstantName;
Example:
Directions est = Directions.EAST;
System.out.println(est); // prints EAST
System.out.println(Directions.NORTH); // prints NORTH
Enum program in Java
enum Directions {
EAST, WEST, NORTH, SOUTH;
}
class EnumDemo {
public static void main(String [] args) {
Directions d = Directions.EAST;
System.out.println("Direction = " + d);
}
}
Save this program as EnumDemo.java, compile as javac EnumDemo.java and run as java
EnumDemo
Output:
Direction = EAST
When does enum constants are created in memory ?
150 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Enum constants are created in memory when any of the enum constants is first called or referenced in
code. In above program enum constants will be created after execution of line Directions d =
Directions.EAST;
Enum with switch case in Java
An enum type variable or enum constant can be used in switch statements as well. The case matching
with constant given in bracket () of switch statement will be executed. Each case expression must be a
constant defined in enum type, if it's not a default case.
switch(Directions.NORTH) {
case EAST: // only constants defined under enum Directions can be used
// statements
case WEST:
// statements
.
.
}
Enum comparison in Java
An enum type constant or variable can be compared with another enum constant or variable using ==,
or != operator. We can also use equals() method to compare two enum constants or variables.
Directions d = Directions.EAST;
if(d == Directions.EAST) // true
if(d.equals(Directions.NORTH)) // false
Java program of enum uses in switch and if statement
enum Directions {
EAST, WEST, NORTH, SOUTH
}
class EnumInSwitchAndIf {
public static void main(String [] args) {
Directions d = Directions.NORTH;
switch(d) {
case EAST:
System.out.println("Direction = " + Directions.EAST);
break;
case WEST:
System.out.println("Direction = " + Directions.WEST);
break;
case NORTH:
System.out.println("Direction = " + Directions.NORTH);
break;
case SOUTH:
System.out.println("Direction = " + Directions.SOUTH);
break;
}
// Use of enum in if statement
if(d == Directions.NORTH)
151 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Current direction = "+d);
}
}
Output:
Direction = NORTH
Current direction = NORTH
Variable, Method and Constructor in Enum
An enum type can have methods, constructors and variables as well, but they must be declared after
constant declaration. The first line of code in an enum type must be constant declaration. The enum
constant declaration must end with semicolon(;) if the enum type contains method, constructor or field.
If the enum type contains constructor, ensure that you have a matching constructor for each constant
declaration since it looks for the matching constructor while compilation. The access modifier of
constructor for an enum type must be either private or package-private(no modifier). An enum type can
have multiple constructors.
Since each constant in an enum type is internally an instance of enum type, so we can call the methods
of an enum type by using it's constants. The program below shows the usage of method, constructor
and variable inside an enum type.
Enum program with method, constructor and variable
enum TrafficSignal {
// Each constant will call single-argument constructor separately.
RED("wait"), GREEN("go"), ORANGE("go slowly");
private String action;
// enum method
public String getAction(){
return action;
}
// enum constructor - must be private or package-private
private TrafficSignal(String actionStr){
action = actionStr;
}
}
class EnumExample {
public static void main(String [] args) {
String action = TrafficSignal.GREEN.getAction();
System.out.println("Action = "+ action);
}
}
Output:
Action = go
Can we create the instance of enum by new keyword?No, Java doesn't allow us to
invoke an enum constructor, which means we can not create the object of enum type
using new keyword. Constructors are called automatically by java.
152 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Can we declare main method in an enum type ? Yes, and we can compile and run that enum
type similar as classes.
values(), valueOf() and ordinal() method of enum type
These are some useful methods which you can use with your enum type.
The values() and valueOf() method is added by compiler after compilation of your enum type
while ordinal() method is available in predefined Enum class. The general form of these methods are :
public static enum-type[] values()
public static enum-type valueOf(String str)
public final int ordinal()
 The values() method returns an array of enum-type which contains all the constants values of
enum in the order they are declared.
 The valueOf() method returns the enum constant which is equal to the string passed to this
method. The string parameter passed to this method is case-sensitive. If the string is not equal to
any of the constant, this method throws an exception.
 The ordinal() method returns the position number of constant. Each constant in an enum type is
given a position number which starts from 0 and goes as 1, 2, 3, 4 ...
Enum program to demonstrate the values(), valueOf() and ordinal() method
enum Color {
RED, GREEN, BLUE;
}
class EnumMethodsDemo {
public static void main(String[] args) {
// Calling values() method on enum type
Color arr[] = Color.values();
// Iteration of enum constants with for-each loop
for(Color col : arr) {
// ordinal() method to find index of a color.
System.out.println("Index of "+col+" = "+ col.ordinal());
}
// valueOf() method, returns enum constant equals to given string
System.out.println(Color.valueOf("RED"));
// This line will cause exception if uncommented,
// as the string doesn't matches with any constant
// System.out.println(Color.valueOf("BLACK"));
}
}
Output:
Index of RED = 0
Index of GREEN = 1
Index of BLUE = 2
RED

Java Enum vs Class


153 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Though enums are internally implemented as classes, following table outlines some of the differences
between enum and classes.
ENUM CLASS
Enums are generally used to declared a set of pre- Classes are design to expose state and behavior
defined constants. of an object.
Constructor of an enum type can be private or
A class constructor can have any access modifier.
package-private only.
Objects of enum type can not be created. Objects of classes can be created.
First line of code must be constant declaration. Classes doesn't have any such restrictions.
Enum can not extend another enum. Class can extend another class.
Java compiler adds some methods like values(),
No such specific methods are added with classes.
valueOf() to an enum type after compilation.
Each enum-type internally extends Enum class. Classes doesn't extend any such class.
When we should use emum in java?
You should use enum types any time you need to represent a fixed set of constants. If you know all
possible values(constant) of an entity at compile time(or design time) and you know that these values
won't change later, you should use that entity as an enum type. E.g.,you can use enum for
declaring Days name, Month name, Planet names etc as these entities will have fixed set of known
values.
1. Refer source code of java.lang.Enum class to get more details of enum.
2. new keyword can not be used with enum type, even within the enum type itself.
3. enum type defined inside a class is implicitly static.
4. equals() and "==" for enum constants evaluates to same result.
5. name() and valueOf() methods returns the text of enum constants. You can
override toString() method to return some other content.
6. An enum type can also have abstract method. In this case each constant must implement the
abstract method.
Static and Instance Initializer blocks in Java
Initializer block is a block of code defined inside curly brackets { }. These blocks are defined inside a
class but outside the method. These blocks are generally used to initialize variables but we can use
normal statements as well as we do in methods.
Generally we assign an initial value to a variable like below :
class Test {
// count is initialized to 10
int count = 10;
}
This approach works well when you know the initial value. If initialization requires some logic (for
example some conditional statements or exception handling), this approach is not sufficient. That is
where initialization blocks are quite useful. There are two types of initializer blocks in java :
 Static initializer block or Static block
154 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 Non static or instance initializer block
Java Static initializer block
A static initializer block is a block of code defined inside curly bracket { } preceded by static keyword.
These blocks are generally used to initialize static or class variables. A static initializer block is also
known as static block. The syntax of declaring a static block is :
class ClassName{
static {
// Initialization code
}}
Some key points about static initializer blocks are :
 A class can have multiple static blocks.
 These blocks can appear anywhere in class body.
 These blocks are executed in the order they appear in the program.
 These blocks are executed only once.
 These blocks belongs to class not objects.
When does static blocks are executed ?
As soon as your class is loaded by java virtual machine, all static blocks given inside your class is
executed. static blocks are executed even before main method is called.
Static block program in Java
class StaticBlockDemo{
static double result;
static {
result = Math.pow(2,3);
System.out.println("First static block, result = "+ result);
}
static {
result = Math.log10(100);
System.out.println("Inside second static block, result = "+ result);
}
public static void main(String [] args) {
System.out.println("Inside main method");
}
}
Output:
First static block, result = 8.0
Inside second static block, result = 2.0
Inside main method
As you can see from the output, static blocks are executed from top to bottom. It is executed even
before main method is executed. This program uses Math class of java which provides different
methods for different mathematical calculations.
Can we run a program having static block only, no main method.
155 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
It depends on the version of java you are using. Prior to JDK 7 you can run a program having static
block only, no main method. But from JDK 7 and above you can not run a program without main
method.
When we should use static block in Java
When you want to execute something that needs to be executed before any method of the class is
executed, you should use static blocks. Generally static blocks are used to initialize static variables that
requires some sort of operation or need to access some method.
INSTANCE INITIALIZER BLOCK OR NON STATIC BLOCK IN JAVA
Instance initializer block is a block of code defined inside { }. As the name suggests, these blocks are
generally used to initialize instance variables. The syntax of declaring instance initializer block is :
class ClassName{
// Instance initializer block
{
// Initialization code
}
}
Some key points about instance initializer blocks are :
 A class can have multiple instance initializer blocks.
 These blocks can also appear anywhere in class body.
 These blocks are executed in the order they appear in the program.
 Instance initialization blocks run every time a new instance is created.
 At compilation time, compiler copies instance block code and place at the beginning of all
constructors just after the call of super class constructor.
 These blocks run just after the super class constructor has completed execution and before the
start of current class constructor.
 They can be used to perform operations those are common to constructors.
JAVA PROGRAM OF INSTANCE INITIALIZER BLOCK
class InstanceBlockDemo {
int ivar;
public InstanceBlockDemo() {
System.out.println("Inside constructor");
}
// First initializer block
{
ivar = 20;
System.out.println("First initializer block");
}
// Second initializer block
{
System.out.println("Second initializer block");
}
public static void main(String args[]) {
InstanceBlockDemo ibd = new InstanceBlockDemo();
156 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Inside main method");
System.out.println("ivar = "+ibd.ivar);
}
}
Output:
First initializer block
Second initializer block
Inside constructor
Inside main method
ivar = 20
As mentioned above, after compilation java compiler places all initializer block code inside each
constructor, so after compilation the above constructor will contains the code like below :
public InstanceBlockDemo() {
super();
{
ivar = 20;
System.out.println("First initializer block"); }
}
{
System.out.println("Second initializer block");
}
System.out.println("Inside constructor");
}
Why we should use instance initializer block ?
We know that we can initialize instance variables which requires some operation or logic inside a
constructor, then question comes that why we should use this block. Sometimes we need to perform
some common initialization in multiple constructors. In such cases it's better to write these common
code inside an instance initializer block rather than writing in multiple constructors, since compiler itself
places this code inside each constructor.
Which initializer block runs first, static or non static initializer block ?
Static initialization blocks always runs before instance initializer block since they are executed during
the class initialization itself. The program given below contains both static and non static block. It
demonstrates the execution order of static and non static blocks.
Java program of static and non static block
class InitializerBlock {
// constructor
public InitializerBlock() {
System.out.println("Inside constructor");
}
{
System.out.println("First instance initializer block");
}
{
System.out.println("Second instance initializer block");
}
157 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static {
System.out.println("First static block");
}
static {
System.out.println("Second static block");
}

public static void main(String args[]) {


InitializerBlock in = new InitializerBlock();
System.out.println("Inside main method");
}
}
Output:
First static block
Second static block
First instance initializer block
Second instance initializer block
Inside constructor
Inside main method

Method Chaining and Method Recursion in Java


This section explains method chaining and method recursion concept. These are a mechanism related
with method calling in java programs. Sometimes it is quite useful to use these concepts in our
programs.
Method Chaining in Java
Method chaining is a technique of calling multiple methods using dot(.) operator in a single statement.
As the name itself suggests, it's a chain of method calls in a single statement. For example you might
have already seen or used code like below :
StringBuilder str = new StringBuilder("java");
str.insert(0,"refresh ").append("section ").append("online"); // Method chaining
As you can see we are calling a series of StringBuilder method in a single statement. This is called
method chaining. Each method except the last method in a method chaining syntax must return an
object to allow the calls to be chained together, since you need an object to call a method.
Method chaining is possible on these method because each of these methods returns an object, which
is then used to call the next method. E.g., the definition of append method of StringBuilder class is like
below :
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
The method is returning this, that is why we are able to invoke it multiple time in same line. In
java this is a reference to the same object on which the method is being called. The program below
demonstrates method chaining using the methods of String and StringBuffer classes. Methods
like insert, append, substring etc allows us to use the technique of method chaining.
158 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Java program of method chaining using String and StringBuilder class methods
class MethodChainingProgram {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Java");
// Below line uses method chaining technique
sb.insert(0,"Learn ").append(" on refresh java").append(" section");
System.out.println(sb);
// Below line also uses method chaining technique
String str = sb.substring(14).replace(" section", "").toUpperCase();
System.out.println(str);
}
}
Output:
Learn Java on refresh java section
REFRESH JAVA
Now let's create our own methods that can be used in method chaining approach. As mentioned above
the method must return an object if it needs to be used in method chaining. The program below
contains method setName and setAge that we can use in method chaining.
Method chaining program in Java
class Person {
String name;
int age;
// This method can be used in chaining
public Person setName(String name) {
this.name = name;
return this;
}
// This method can also be used in chaining
public Person setAge(int age) {
this.age = age;
return this;
}
public void getPersonDetails() {
System.out.println("Person name : " + name + ", age : " +age+" year.");
}}
class MethodChainingDemo {
public static void main(String[] args) {
Person person= new Person();
// Below line uses method chaining technique
person.setName("Rahul").setAge(22).getPersonDetails();
}}
Output:
Person name : Rahul, age : 22 year.
159 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Using method chaining has couple of benefits like it improves the readability and reduces the amount of
source code. But it also has some disadvantages as well like It's hard to debug if any of the method
fails while execution. Exception handling also becomes tough, sometime it's confusing as well.
Recursion in Java
Recursion is a process in which a method call itself from within it's body. The method that calls itself is
known as recursive method. The code below shows an example of recursive method :
int calculate(){
.....
calculate(); //calling the same method
.....
}
As you can see method calculate is calling itself, we can say calculate is a recursive method. Generally
programmer uses some conditional/looping statements to call the same method. If we don't use any
condition, the execution of method keep repeating itself again and again which results in an infinite
recursion. Recursion in computer science is a method of solving a problem. For example the program
below calculates the factorial of a number using method recursion. Factorial of a number 5 is calculated
as 5*4*3*2*1=120.
Factorial of a number using Recursion in Java
class FactorialProgram {
static int factorial(int n) {
if(n == 0)
return 1;
else
return(n * factorial(n-1)); // Calling the same method
}
public static void main(String args[]) {
int number=5;
int fact = factorial(number);
System.out.println("Factorial of number "+number+" is : "+fact);
}}
Output:
Factorial of number 5 is : 120
How recursion works
As you know once a method is called, a new stack(memory) is allocated for method. This stack is used
by method to store it's variables and performs it's operations and finally return the result to caller. In
recursion every time the method is called, a new stack is allocated on the top of last stack. Once the
last call happens, the method on top most stack evaluates it's result and returns the output to it's
previous stack. The same process goes on until the method at first stack evaluates it's result and
returns the result to it's caller. E.g., in factorial program, once the main method calls the findFactoria(5),
it calls findFactorial(4) and it goes on until findFactorial(0) is called which returns 1 to findFactorial(1)
which further returns it's result to findFactorial(2) and so on until findFactorial(5) is reached which
evaluates the final result and returns to main method. The image below shows a typical representation
of above factorial program.
160 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Programmer have to be careful while using method recursion, incorrect condition or logic may result in
an infinite recursion. In an infinite recursion the method keeps calling itself again and again which
means method call never ends. For example the program below results in an infinite recursion.
Infinite recursion program in Java
class InfiniteRecursion {

static void printNumber(int num) {


if(num <= 10) {
System.out.println(num);
num = num-1;
printNumber(num);
}
}
public static void main(String args[]) {
printNumber(10);
}
}
Output:
10
9
8
.
.
161 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Exception in thread "main" java.lang.StackOverflowError.
The condition statement that we have used in this program will always be true, as we are decreasing
the number in each iteration. This will result in calling the method again and again. So you have to use
the recursion carefully to avoid the infinite looping. If you change the conditions as if(num >= 1) the
program will run successfully.
1. Method chaining is a design strategy that needs to be made by programmer while defining the API.
2. If any of the method fails in method chaining, subsequent methods won't be executed .
3. Method chaining also known as named parameter idiom.
4. Use method chaining only when it is actually helpful like in case of some string methods.
5. Recursive method needs more memory than it requires in normal case.
6. Recursion makes the code compact but complex to understand.

PACKAGES IN JAVA
As in our computer we have directories to organize the files, similarly in java we have packages, used
to organize the classes and interfaces files in java applications. Packages are very similar as
directories which help us to write better and manageable code. A package, as the name itself suggest
is a group(pack) of similar types of classes and interfaces. Classes with similar type of functionalities
are put together inside a package. It's the programmer who creates the package and adds the classes
and interfaces inside that package. A package can contain other types as well like enums, annotation
types, subpackages. For simplicity we are referring classes and interfaces only, especially the classes.
The image below shows a hierarchy of different java elements where each element is a subset of next
element. For example a method is a group of statements, similarly an application is a group of
packages.

A package declaration looks like below :


package packagename;
Example:
package mypack;
package com.refreshjava.mypack;
Here package is a keyword while packagename is the name of package given by programmer. As per
java the naming of packages should be in small letters only.
Types of packages
Packages can be categorized in two types : 1.User defined packages and 2.Built-in packages
User defined packages in Java
Packages are defined by programmer is known as user defined packages. While working for an
application/project you may need to create one or more packages in your application. Each packages
may have one or more classes and interfaces inside it. Let's see how to create a user defined package.
Creating packages in Java
As mentioned above, a package is also a directory. Each package that you define is a directory in your
computer. E.g., a package name mypack will be a directory mypack inside your computer. Similarly a
package name com.refreshjava.mypack will have a directory structure as com/refreshjava/mypack,
162 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
where directory mypack will be inside refreshjava directory which will be inside com directory. So to
create a package, first you need to create a directory anywhere in your computer. You can also declare
the package in your program first and then create the directory with same name(as package name) in
your computer. Let's create a directory mypack inside the computer. In my computer it is created
inside D:\project directory, you can choose your own directory. Currently mypack is just an empty
directory. Once you have created the directory, you can use that directory as package name in your
program. Remember the package name declaration must be the first statement in your program.
package packagename;
class className {
...
}
Example:
package mypack;
class Test {
...
}
Now let's create the class MyFirstPackageProgram.java as given below inside
the D:\project\mypack\ directory.
Java package program
package mypack;
class MyFirstPackageProgram {
public static void main(String args []) {
System.out.println("My first package program");
printMessage();
}
public static void printMessage() {
System.out.println("Inside printMessage method");
}
}
Notice here the package name and directory name is same. A package program must be saved inside
it's own(package name) directory. Now let's see how to compile and execute the program.
Compilation and execution of package program
If you are not using tools like Eclipse, Netbeans etc, the compilation and execution of programs having
package declaration is a bit tricky. To compile above program, open command prompt and move to the
directory D:\project or the one that you have used. Execute the below command which will create
the .class file inside mypack directory.
javac mypack\MyFirstPackageProgram.java
Now let's see how to run the above program. To run a package program you need to give the class
name with it's package name while executing the program like below :
java mypack.MyFirstPackageProgram
163 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

While compiling or executing the program, ensure that you are in D:\project directory in command
prompt or the one you have used for your package directory.
Output:
My first package program
Inside printMessage method
It's a must to give the class name with it's package name while running the program since java looks for
the .class file in same directory(package name).
Can a class have multiple package declaration? No a class can have only one package
declaration. Declaring multiple package will result in compilation error.
Can multiple classes have same package declaration?Yes multiple classes can have same
package declaration. All these class files must go inside same directory.
Creating .class files in separate directory
Here we created the .class file in mypack directory but in real world applications, generally we use to
create the .class files in separate directory like classes or build directory. It's good programming style to
separate the source code and compiled code. To create .class files in separate directory java provides -
d option which is used with javac command. The -d option with javac command is used to specify the
directory where the .class files needs to be stored. Create a folder classes inside D:\project directory in
a computer and then execute the below command, it will create the .class file inside classes directory.
javac -d classes mypack\MyFirstPackageProgram.java
Here after -d option you need to specify the directory name where to save the .class file. Here
it's classes directory. The .class file will be generated inside D:\project\classes directory, so ensure that
it already exist. After successful compilation java compiler will create a
directory mypack inside classes directory. If you want to save the .class files in current or same
directory, you can use .(dot) after -d option which tells the java compiler to save the .class file in current
directory. Now to run the program you need to specify -classpath or -cp command line option
with java command. This option tells the java virtual machine where to look for .class files.
java -cp classes mypack.MyFirstPackageProgram // or
java -classpath classes mypack.MyFirstPackageProgram
Here after -cp or -classpath option you need to specify the directory name where to look for
the .class file. In this case it's classes directory where jvm will look for .class file.
164 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Output:
My first package program
Inside printMessage method
What if JVM doesn't find the .class file at location given by cp/classpath option ?
JVM will throw error like "Could not find or load main class ... ".
Java package program with multilevel directory
The program below reveals the package having multilevel directory structure. Create the directory
structure com/refreshjava/mypack inside D:\project directory and then save below program inside that
directory.
package com.refreshjava.mypack;
class PackageDemo {
public static void main(String args []) {
System.out.println("Package with multilevel directory");
}
}
Execute below commands to compile and run the program.
javac -d classes com\refreshjava\mypack\PackageDemo.java
java -cp classes com.refreshjava.mypack.PackageDemo
Output:
Package with multilevel directory
Advantages of Packages
The advantages of using packages are :
 Packages makes easy to search or locate class or interface files.
 Packages helps to avoid naming conflict. Classes with same name can exist in different packages.
 It also helps in controlling the access of one class inside other class.
 Packages helps in encapsulation of classes and interfaces.
 Packages helps to reuse the classes and interfaces.

1. Java's predefined packages are available in rt.jar file in bin folder of JRE.
2. Though you can use capital letters as well for package name but prefer to use small letters only.
3. In organizations, generally packages are named in reverse order of domain names
like com.orgname or org.orgname, for example com.refreshjava.mypack.
4. Programmer should avoid to use the word java for naming their packages like java, java.xyz,
java.refreshjava etc, since java uses this word for java packages.
165 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
5. Every class is part of some package. If no package is specified, the class goes inside a default
package(the current working directory) which has no name.

Sub Packages in Java


A package defined inside another package is known as sub package. Sub packages are nothing
different than packages except that they are defined inside another packages. Sub packages are
similar as sub directories which is a directory created inside another directory. Sub packages in itself
are packages, so you have to use/access them similar as packages. They can also have any types like
classes, interfaces, enums etc inside them.
How to create and use sub packages in Java
It's similar as creating packages in java. In previous section, we created a package mypack which is a
directory in computer. Now if I create a package(directory) testpack inside mypack directory, then
package testpack will be called as sub package.
Let's create a class inside this sub package. I have created a class MySubPackageProgram.java as
given below and saved it inside D:\project\mypack\testpack directory.
Subpackage program in Java
package mypack.testpack;
class MySubPackageProgram {
public static void main(String args []) {
System.out.println("My sub package program");
}
}
Notice here the package name is mypack.testpack which is a subpackage. Let's compile and run this
program by executing the commands given below.
javac mypack\testpack\MySubPackageProgram.java
java mypack.testpack.MySubPackageProgram
Output:
My sub package program
Why do we create Sub Packages
Subpackages are created to categorize/divide a package further. It's similar as creating sub folder
inside a folder to categorize it further so that you can organize your content more better which will make
easy to access the content. A package may have many sub packages inside it.

For an example in our computer generally we create directory like songs to store songs inside it. Then
inside that we may create sub directories like hindi songs and english songs or old songs and new
166 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
songs to categories the songs directory further. Doing this help us to organize or access the songs
easily. The same thing applies with sub packages as well.
How to import Sub packages
To access the classes or interfaces of a sub package, you need to import the sub package in your
program first. Importing the parent package of a sub package doesn't import the sub packages classes
or interfaces in your program. They must be imported explicitly in your program to access their classes
and interfaces. For example importing package mypack in your program will not import the classes of
sub package testpack given above. Importing sub packages is same as importing packages. The
syntax of importing a sub package is :
// To import all classes of a sub package
import packagename.subpackagename.*;
// To import specific class of a sub package
import packagename.subpackagename.classname;
Example
import mypack.testpack.*;
import mypack.testpack.MySubPackageProgram;
Example of Predefined SubPackages in Java
There are many predefined subpackages in java. Some of the examples of subpackages in java 8 are :
 The package java has subpackages like awt, applet, io, lang, net, util etc. The package java doesn't
have any class, interface, enums etc inside it.
 The package java.awt has subpackages like color, font, image etc inside it. The
package java.awt itself has many classes and interfaces declared inside it.
 The package java.util has subpackages like concurrent, regex, stream etc inside it. The
package java.util itself has many classes and interfaces declared inside it.
The program below shows how to use the Pattern class of java.util.regex subpackage. This sub
package contains classes and interfaces for regular expressions. The Pattern class is generally used to
search or match a particular pattern inside a given string.
import java.util.regex.Pattern;
// To imports all classes of java.util.regex subpackage.
// import java.util.regex.*;
class PatternMatch {
public static void main(String args[]) {
// Checks if the given string contains only alphabets
System.out.println(Pattern.matches("[a-zA-Z]*", "RefreshJava"));
System.out.println(Pattern.matches("[a-zA-Z]*", "RefreshJava2"));
// Checks if the given string contains only numbers
System.out.println(Pattern.matches("[0-9]*", "123456"));
System.out.println(Pattern.matches("[0-9]*", "123H456"));
}
}
Output:
true
false
true
167 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
false
1. Think of sub packages as packages while using or accessing them, they are nothing different.
2. A sub package may have another sub packages inside it.
3. Refer rt.jar file in bin folder of JRE to see some of the predefined sub packages in java.
4. Though you can use capital letters as well for sub package name but prefer to use small letters
only.
5. If a package mypack contains a subpackage as tespack, then package mypack can not contain a
class or interface with name as testpack inside it.

Built in packages in Java


Java has already defined some packages and included that in java software, these packages are
known as built-in packages or predefined packages. These packages contains a large number of
classes and interfaces useful for java programmers for different requirements. Programmers can import
these packages in their program and can use the classes and interfaces of these packages in that
program. Built-in packages comes automatically in your jdk/jre download. These packages comes in
the form of jar files. By unzipping the jar file you can see the packages available in that jar. For example
if you unzip rt.jar file available in lib folder of JRE, you can see the directory java which contains
packages like lang, io, util, sql etc. There are many built-in packages available in java. In this section
we will see some of the built-in packages and how to use their classes in our program. Some of the
inbuilt packages in java are :
 java.awt : Contains classes for creating user interfaces and for painting graphics and images.
Classes like Button, Color, Event, Font, Graphics, Image etc are part of this package.
 java.io : Provides classes for system input/output operations. Classes like BufferedReader,
BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable etc are part of this
package.
 java.lang : Contains classes and interfaces that are fundamental to the design of Java
programming language. Classes like String, StringBuffer, System, Math, Integer etc are part of this
package.
 java.net : Provides classes for implementing networking applications. Classes like Authenticator,
HttpCookie, Socket, URL, URLConnection, URLEncoder, URLDecoder etc are part of this package.
 java.sql : Provides the classes for accessing and processing data stored in a database. Classes
like Connection, DriverManager, PreparedStatement, ResultSet, Statement etc are part of this
package.
 java.util : Contains the collections framework, some internationalization support classes, properties,
random number generation classes. Classes like ArrayList, LinkedList, HashMap, Calendar, Date,
TimeZone etc are part of this package.
As mentioned above, you can unzip the jar files to see the list of all java packages or you can
refer this link to see the list of all packages available in java 11.
The package java.lang is automatically imported to every program that we write, that is why we don't
need any import statement in our programs for using classes like String, StringBuffer, System etc.
Except java.lang, other packages must be imported first in your program to use the classes and
interfaces available in that packages.
Java awt package(java.awt)
168 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Java AWT(Abstract Window Toolkit) package contains classes and interfaces used to develop
graphical user interface or window based applications in java. Java AWT components are platform-
dependent since they uses operating system resources to create components like textbox, button,
checkbox etc. The program below creates a frame containing a label using java.awt classes.
Java awt package program
import java.awt.Frame;
import java.awt.Label;
class JavaAWTExample {
// Declaring constructor
public JavaAWTExample() {
Frame fm = new Frame(); //Creating a frame
Label lb = new Label(" Welcome to refresh java"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 200); //setting frame size
fm.setVisible(true); //setting frame visibility as true
}
public static void main(String args []) {
JavaAWTExample awt = new JavaAWTExample();
}
}
Here Frame and Label are classes defined in java.awt package. Frame class is used to create frame
while Label class is used to create label. AWT package is rarely used today because of it's platform
dependency and heavy-weight nature. Swing is the preferred API over AWT for developing graphical
user interface in java.
Output:

Java lang package(java.lang)


This packages contains the fundamental or core classes of java language without which it won't be
possible to write program in java. This package is automatically imported to each program, which
means we can use the classes of this package directly in our program. The program below shows how
to use the Math class of java.lang package which provides many different methods for different
mathematical operations.
Java program of demonstrating use of java.lang package
class JavaLangExample {
public static void main(String args []) {
int a = 20, b =30;
int sum = Math.addExact(a,b);
169 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
int max = Math.max(a,b);
double pi = Math.PI;
System.out.printf("Sum = "+sum+", Max = "+max+", PI = "+pi);
}
}
Output:
Sum = 50, Max = 30, PI = 3.141592653589793
As you can see we are able to use Math and System classes defined in java.lang package without any
import statement, it's because java.lang package is imported implicitly.
Java io package(java.io)
Java IO(Input/Output) package provides classes and interfaces for handling system(computer, laptop
etc) input and output operations. Using these classes programmer can take the input from user and do
operations on that and then display the output to user. Generally input is given using keyboard/keypad.
We can also do file handling(read/write) using the classes of this package. The program below uses
the Console class of java.io package to take the input from user and then print that input to user's
screen(command prompt or any other terminal used). Java program of demonstrating use of java.io
package
import java.io.Console;
class JavaIOExample {
public static void main(String args []) {
Console cs = System.console();
System.out.println("Enter your name : ");
String name = cs.readLine();
System.out.println("Welcome : "+name);
}}
Once you run this program, it will ask for your name and then it will display that name in console
window.
Output:
Enter your name :
Rahul
Welcome : Rahul
Java util package(java.util)
Java util package provides the basic utility classes to java programmers. It is one of the most useful
package for java programmers, it helps them to achieve different types of requirements easily by using
it's predefined classes. The program below uses Arrays class of this package to sort an array of
integers. The Arrays class provides many api's(methods) for different array requirements.
Java program of demonstrating use of java.util package
import java.util.Arrays;
class JavaUtilExample {
public static void main(String args []) {
int[] intArray = {10,30,20,50,40};
Arrays.sort(intArray);
System.out.printf("Sorted array : %s", Arrays.toString(intArray));
}
170 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
Output:
Sorted array : [10, 20, 30, 40, 50]

Package import in Java


Package import is a feature in java which allows us to reuse the classes available in a package. Java
provides import keyword to import classes of another package inside your class. Once a class is
imported, you can use the imported class anywhere in your class. Package import basically makes
availability of classes of that package in your class, so that you can use the functionalities of that
classes. To access a class of another package, first you need to import that class or package in your
class. Importing packages allows us to import not only classes but also interfaces, enums etc as well.
We are referring classes only in this section, just for simplicity.The syntax of importing a package or
class is :
// To import all classes of a package
import packagename.*;
// To import specific class of a package
import packagename.classname;
// To import all classes of a sub package
import packagename.subpackagename.*;
// To import specific class of a sub package
import packagename.subpackagename.classname;
Example
import mypack.*;
import mypack.MyFirstPackageProgram;
import java.util.*;
The * wildcard is used to import all classes of a package. E.g. suppose if there are classes
like PackageDemo1, PackageDemo2, PackageDemo3 etc inside a package mypack, then importing
package mypack using * wildcard will import all these classes in your class. The * wildcard does not
import classes of a sub package, they must be imported explicitly as given above to import their
classes. The package import statement must come after package name declaration and before the
start of your class. If your class doesn't have a package declaration, then import statement will be the
first statement in your class. Note: Accessibility of a class outside the package is also controlled by
access modifier. You can only access it if it has an access modifier that allows it to be accessed
outside.
ACCESSING CLASSES OF A PACKAGE
To access the class of a package, you just have to import that class or package in your program. Let's
see this by the programs given below. In first program we are creating a
class MyFirstPackageProgram in mypack package. The second program which is in another package
accesses the MyFirstPackageProgram class.
package mypack;
public class MyFirstPackageProgram {
public void printMessage() {
System.out.println("Inside printMessage method");
}
171 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
The program below which is in testpack pacakge, shows how to import and use the above class. This
program creates an object of above class and calls it's printMessage method.
package testpack;
import mypack.MyFirstPackageProgram;
// To import all classes of mypack package
// import mypack.*;

class PackageImportProgram {
public static void main(String args []) {
System.out.println("package import demo");
MyFirstPackageProgram mfp = new MyFirstPackageProgram();
mfp.printMessage();
}
}
Now let's compile and execute the program. We need to compile MyFirstPackageProgram.java first,
then only we can compile and execute PackageImportProgram.java.

Output:
package import demo
Inside printMessage method
What if my program doesn't find the class in imported package? The program won't compile.
It will throw compilation error.
Should I prefer to import particular class over importing all classes using * wildcard? Yes,
It's good programming style to import only required classes over importing all classes using * wildcard.
Accessing class without importing the package. We can access the class of a package without
importing it. In that case we will have to use the name of class with it's package name. For example the
above program can be written without importing the class like below :
package mypack;
class PackageImportProgram {
public static void main(String args []) {
System.out.println("package import demo");
testpack.MyFirstPackageProgram mfp = new testpack.MyFirstPackageProgram();
mfp.printMessage();
}}
Output:
172 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
package import demo
Inside printMessage method
Accessing classes of built in java packages
To access the classes of built in java packages, you just have to import that class or package inside
your program, once imported you can use that class anywhere in your program. The program below
shows how to access the class Arrays of built in java packages java.util.
import java.util.Arrays;
// To imports all classes of java.util package.
// import java.util.*;
class SortArray {
public static void main(String args[]) {
int [] arr = {30,40,10,20,50};
Arrays.sort(arr);
for(int i : arr)
System.out.print(i + " ");
}}

Here Arrays class is available in java.util package which has method sort to sort an array.
Can I import multiple classes or packages in my class? Yes you can, in real world
applications most of the classes needs to import multiple classes or packages.
Resolving class name conflict
If two package have class with same name, and you have imported both the packages in your program,
then you might get the error while using the same name class in your class. Let's see this by an
example. The package java.util and java.sql both has a class called Date and suppose you have
imported both the packages in your program. Now if you use Date class directly in your class, it will
result in compilation error. Now you can follow any of the approaches given below to avoid this error :
If you want to access the Date class of a particular package in your program, then you can specifically
import the Date class of that package. For example to use Date class of java.util package, import like
below :
import java.util.Date;
import java.sql.*;
Date date = new Date(); // java.util.Date will be used
If you want to access the Date class of both the packages, then you need to refer them using their
packages name in your program like below :
import java.util.*;
import java.sql.*;
java.util.Date date = new java.util.Date();
java.sql.Date today = new java.sql.Date(1000);
Static import in Java
Static import is a feature in java which allows us to access static variables and methods of a class
directly in our program without using their class name. We just have to static import that
member(variable or method), then we can use that member directly in our class. This feature is
available from java version 5 and above. We can import a specific static member or all the static
173 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
members using static import. The code below shows how to import a specific and all members
of Arrays class of java.util package.
// Imports only sort method of Arrays class
import static java.util.Arrays.sort;
// Imports all static member of Arrays class
import static java.util.Arrays.*;
Static import program in Java
import static java.util.Arrays.sort;
class SortArray {
public static void main(String args[]) {
int [] arr = {30,40,10,20,50};
sort(arr);
for(int i : arr)
System.out.print(i + " ");
}
}
Output:
10 20 30 40 50

As you can see the sort method is called directly without using the class name, since it's a public
static method in Arrays class. Note : You can not import a package using static import, it must be the
class or static variable/method that can be imported using static import. For example using below
import will result in compilation error.
import static java.util.*; // compilation error
Access Modifiers in Java
Access modifiers, as the name itself suggests, are used to control the accessibility/visibility of variables,
methods, constructors of a class inside another class. Java provides some keywords to accomplish the
same, these keywords are known as access modifiers. These modifiers decides whether other classes
can use a particular variable, method, constructor of a class or not. There are four types of access
modifiers in java.
 Private (declared using private keyword)
 Default or package private (when no keyword is used)
 Protected (declared using protected keyword)
 Public (declared using public keyword)
All these modifiers can be used with variables, constructors and methods of a class while Default
and Public access modifiers can also be used with top level classes and interfaces. An access
modifier must be used before the data type of a variable and return type of a method. In case of class,
interface or enum it must be used before the class, interface and enum keyword. Some of the
examples of using access modifiers with different members are :
private int count = 0; // Correct
public String print() { } // Correct
public class MyClass { } // Correct
int protected id = 20; // Wrong
void public getDetail() { } // Wrong
174 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Private Access Modifier in Java
A member is declared private using private keyword. This is the most restrictive access modifier in java.
The code below declares the variable count as private.
private int count = 0;
. Some key points about private access modifier are :
 A private member is accessible within it's own class only. For example a variable count defined
as private, inside class A will be accessible within class A only, no other classes can access this
variable.
 Variables, methods and constructors can be declared as private.
 Top level classes and interfaces can not be declared as private, where as nested classes and
interfaces can be declared as private.
 If a class has private constructor then we cannot create the object of that class in another class.
Private access modifier program in Java
class PrivateModifier {
private int count = 10;
private void printMessage() {
System.out.println("count = : "+count);
}
}
class PrivateModifierTest {
private int num = 20;
public static void main(String [] args) {
PrivateModifierTest pmt = new PrivateModifierTest();
pmt.printDetail();
System.out.println("num = "+pmt.num);
PrivateModifier pm = new PrivateModifier();
// pm.printMessage(); // compilation error
// System.out.println(pm.count); // compilation error
}
private void printDetail() {
System.out.println("Private modifier program");
}
}
Output:
Private modifier program
num = 20
As you can see in above program class PrivateModifierTest is able to access it's private variable and
method but if you uncomment last two line in PrivateModifierTest class it will result in compilation error
as it can not access private members of PrivateModifier class.

Default Access Modifier in Java


When a member is declared without any access modifier, it is called default modifier. So default is not a
keyword, it's just when we don't use any access modifier, it is called default or no modifier. It is also
known as package-private access modifier. The code below declares the variable count as default.
175 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
int count = 0;
Some key points about default access modifier are :
 A default member is accessible within the package only, that is why it is also known as package-
private modifier. For example a variable count defined with no modifier inside class A can be
accessed by a class B if class B is in same package as class A.
 Any member can be declared with no modifier whether it's a variable, method, constructor, class,
interface or anything else.
 Nested classes and interfaces can also be declared with no modifier.
Default access modifier program in Java
package mypack;
class DefaultModifier {
int count = 10;
void printMessage() {
System.out.println("Default modifier program");
}
}

public class DefaultModifierTest {


public static void main(String [] args) {
DefaultModifier dmf = new DefaultModifier();
dmf.printMessage();
System.out.println("count = "+dmf.count);
}
}
Output:
Default modifier program
count = 10
As you can see in above program class DefaultModifierTest is able to access the default variable and
method of class DefaultModifier, since both classes are in same package mypack. If both classes were
in different packages, this program would have resulted in compilation error.
Protected Access Modifier in Java
A member is declared protected using protected keyword. Code below declares the variable count
as protected.
protected int count = 0;
Some key points about protected modifier are :
 A protected member can be accessed within it's own package as well as by a subclass in another
package. For example a variable count defined with protected modifier inside class A can be
accessed by class B if class B is in same package as class A or class B is in different package but
it's a subclass of class A.
 This access modifier can be used with variable, method and constructors.
 Top level classes and interfaces can not be declared as protected, where as nested classes and
interfaces can be declared as protected.
Protected access modifier program in Java
package testpack;
public class ProtectedModifier {
176 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
protected int count = 10;
protected void printMessage(){
System.out.println("Protected modifier program");
}
}
package mypack;
import testpack.ProtectedModifier;
public class ProtectedModifierTest extends ProtectedModifier {
public static void main(String [] args) {
ProtectedModifierTest pmf = new ProtectedModifierTest();
pmf.printMessage();
System.out.println("count = "+pmf.count);
}
}
Output:
Protected modifier program
count = 10
Here both classes are in different packages but ProtectedModifierTest class is a subclass of
ProtectedModifier class that is why it is able to access the variable and method of it's super class. Note
: It must be the object of subclass to access the protected member of super class if both the classes
are in different packages. For example in above program we can not access the protected member
of ProtectedModifier class by creating it's object in ProtectedModifierTest class.
Public Access Modifier in Java
A member is declared public using public keyword. This modifier doesn't put any restriction, it can be
accessed anywhere. The code below declares the variable count as public.
public int count = 0;
Some key points about public modifier are :
 A public member is accessible everywhere, no matter whether it's in same package or in different
package.
 Any member can be declared with public modifier whether it's a variable, method, constructor,
class, interface or anything else.
Public access modifier program in Java
package testpack;
public class PublicModifier {
public int count = 10;
public void printMessage() {
System.out.println("Public modifier program");
}
}
package mypack;
import testpack.PublicModifier;
public class PublicModifierTest {
public static void main(String [] args) {
PublicModifier pmf = new PublicModifier();
pmf.printMessage();
177 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("count = "+pmf.count);
}
}
Output:
Public modifier program
count = 10
As mentioned above public modifier doesn't apply any restriction that is why public members
of PublicModifier class is accessible in PublicModifierTest class even though both classes are in
different packages.
Java access modifiers table
The following tables shows the accessibility/visibility scope of a member for different access modifiers
in java.

Can I declare the variables of a method with public, private or protected modifiers?.
No, variables inside a method can not be declared with public, private or protected modifier. They must
be declared without any modifier. Note : A member declared inside another member will be accessible
outside only if it's outer member has same or greater accessibility modifier. For example if you declare
a public variable inside a class which has default modifier, then the variable will not be accessible
outside the package as it's class will be accessible within the package only.
1. A program file can have only one public class, as each public type in java must be saved in it's own
file name.
2. A program can not contain public class and public interface together.
3. There can be multiple classes with default modifier in a program.
4. If you want your member's of a class should be accessible to everyone then declare your class and
member both as public.
5. You should use access modifiers for a member wisely, giving unnecessary access to others limits
the flexibility of changing your code.

WHAT IS INTERFACE IN JAVA


Interfaces is also a key concept of java which is used very often in java applications. This section
explains different details of interfaces like what interfaces is, how to create interfaces, why do we use
interfaces etc. In java programming language an interface is a reference type, similar as class, that can
contain only constants, method declaration (method signature, no body), default methods,
static methods and nested types inside it's body. Nested type simply means it can contain another
interface or class inside it. The default and static methods can be used from java 8 onward only. These
methods must have a body if used in an interface. These methods will be discussed in next section. An
178 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
interface in java is declared using interface keyword, followed by interface name. After interface name
it's interface body enclosed in { }. The basic syntax of declaring an interface is :
interface interfaceName {
// constant declarations
// Method signatures
}
Example :
interface MyInterface {
int id = 20;
void print();
public int calculateArea();
}
The name of interface is given by the programmer by following the java naming convention. Inside the
interface we can declare variables and methods. A variable declared inside an interface must be
initialized with some value. We can also use public and abstract modifier with interface declaration. An
interface declared with public access modifier is accessible everywhere while the abstract modifier is
added implicitly by the compiler with each interface that we declare.
public abstract interface MyInterface {
// constant and Method declarations
}
Interfaces in java cannot be instantiated, which means we can not create the object of interfaces
using new keyword. Interfaces can only be implemented by classes or extended by other interfaces.
How to implement interface in Java
Interfaces are designed to be implemented by classes as they contains method declarations only, no
method body. These methods must be defined by classes which implements the interface. The class
that implements an interface must define all the methods of that interface otherwise that class must be
defined as abstract class. Java provides implements keyword which is used to implement an interface
by a class. The program below demonstrates how a class implements an interface.
Interface program in Java
interface MyInterface {
int id = 20;
void print();
}
class MyClass implements MyInterface {
public void print() {
System.out.println("This is print method");
}
public static void main(String args []) {
MyClass obj = new MyClass();
obj.print();
System.out.println(obj.id);
}
}
Save above program as MyClass.java, compile as javac MyClass.java and run as java MyClass.
Output:
179 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
This is print method
20
How to save interface program? If a program contains only interface then it should be
saved by interface name. If the program contains class and interface both then it must be saved by the
class or interface name declared with public modifier. If it doesn't contain any public interface or class
then prefer to save by class name, but it's not mandatory.
What does java creates after compilation of an interface?
Java compiler always creates a .class file for every interface, no matter it is defined separately or in
combination with class inside a program. Each constants defined inside an interface are by
default public, static and final while each methods are by default public and abstract. It's the compiler
which adds these modifiers with constants and variables after compilation of interface. For example the
above interface would be converted as below :
interface MyInterface {
public static final int id = 20;
public abstract void print();
}
So it doesn't matter whether you use or not use these modifiers with variables and methods, java
compiler will automatically adds these modifiers after compilation of your interface.
Can I declare a variable of interface as private or protected? No, the variable of
an interface must be declared either public or it should be left without any modifier.
Implementing multiple interfaces
Java allows the classes to implement multiple interfaces. If a class implements multiple interfaces, then
it must implement all the methods of each interfaces. The Program below demonstrates multiple
interface implementation.
Java program to implement multiple interfaces
interface FirstInterface {
int id = 20;
void printMessage();
}
interface SecondInterface {
int count = 10;
void printDetail();
}

class MultipleInterface implements FirstInterface, SecondInterface {


public void printMessage() {
System.out.println("This is printMessage method");
}
public void printDetail() {
System.out.println("This is printDetail method");
}
public static void main(String args []) {
MultipleInterface obj = new MultipleInterface();
obj.printMessage();
180 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
obj.printDetail();
System.out.println("id = "+obj.id);
System.out.println("count = "+obj.count);
}
}
Output:
This is printMessage method
This is printDetail method
id = 20
count = 10
When to use interfaces in Java
Interfaces are a way of defining a set of contracts(in form of method) or minimum functionalities of an
application. While designing an interface in your application, think it in this way, what are the minimum
functionalities your application/software must have. You can write those functionalities in the form of
abstract methods in one or more interfaces. Classes dealing such functionalities can implement the
corresponding interface to ensure to provide the required functionalities by implementing the methods
of that interface. For an example if you are developing a user management software which will provide
the functionalities like add user, update user, delete user, get user etc, you can write them in the form
of methods inside an interface. The classes dealing such functionalities can implement that interface to
provide these functionalities.
Why do we use interface in Java
Interfaces are generally used to declare a set of contracts or minimum functionalities which must be
present in an application or program. These contracts are then implemented by classes to provide the
actual feature. Apart from this there are some more benefits as listed below, of using interfaces in java.
 Interfaces helps to achieve abstraction as it contains method declarations only, no method body.
 Using interfaces we can achieve multiple inheritance in java, as a class can implement multiple
interfaces.
 It helps to achieve loose coupling, as methods are declared and defined separately.
 Interfaces helps to achieve polymorphism, as a class can behave as multiple types by implementing
multiple interfaces.
You may not understand the actual use of interfaces in a single program but once you start building any
application or library designing, you would understand the use of interfaces in java.
Can we design an application without the use of interfaces?
Yes you can design an application without using any interface, but a good design strategy is to use
interfaces in your application where ever needed.
1. An interface acts as non primitive data type, as it's a reference type.
2. A program can declare multiple interfaces inside it.
3. Object of implementing class can be assigned in to implementing interface type.
4. A public class and public interface can not be declared together inside a program.
5. Always remember to apply public access modifier while implementing an interface method in a
class.
Key points about Interfaces in Java
181 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Here we explain some of the key points about interfaces to help you to use interfaces correctly. To
understand this section easily, you must have knowledge about interfaces in java, if not,
refer Interface section first. Following are some key points about interfaces in java :
 Interfaces cannot be declared as private or protected. Only public and default modifiers are allowed.
private interface A { } // Compilation error
protected interface A { } // Compilation error
public interface A { } // Correct
interface A { } // Correct
 Every interface in java is by default abstract.
interface A { } // is same as abstract interface A { }
 Every variable of an interface is by default public static and final while every method of an interface
is by default public and abstract.
interface A {
int id = 20;
void print();
}
......... IS SAME AS ........
interface A {
public static final int id = 20;
public abstract void print();
}
 Interface variables must be initialized with some value at the time of declaration.
interface A {
// int id; // Compilation error
int id = 20;
}
 Class implementing an interface cannot change the value of variable declared in the interface since
they are declared as final by default.
interface A {
int id = 20;
void test()
}
class Myclass implements A {
public void test() {
id = 30; // Compilation error
}
}
 Class implementing an interface must implement all the methods of that interface, otherwise the
class must be declared as abstract.
interface A {
int id = 20;
void test()
}
abstract class Myclass implements A {
// Define the class as abstract if not overriding the interface method;
182 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
 While implementing the method of an interface in a class, it's visibility(access modifier) can not be
reduced. Reducing the visibility will result in compilation error, so it must have public access
modifier in class as well.
interface A {
void test();
}
class Myclass implements A {
void test() { } // Compilation error
public void test() { } // Correct
}
 An interface can extend another interface but it cannot implement it. Only classes can implements
interfaces.
interface A { }
interface B extends A { // valid }
interface B implements A { // Not valid }
 A class can implement any number of interfaces.
class Myclass implements Interface1, Interface2, Interface3, .... {
// Define methods of all implemented interface
}
 If a class implements two interfaces which have same method name, then the implementation of
same name method once is enough.
interface A {
int calulateArea();
}
interface B {
int calulateArea();
}

class MyClass implements A, B {


public int calulateArea() {
// Defining once is enough.
}
}
 A class cannot implement two interfaces that have methods with same name but different return
type.
interface A {
int calulateArea();
}
interface B {
void calulateArea();
}

class MyClass implements A, B {


// Not possible to define calculateArea() for both interfaces
183 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
 Variable name conflicts can be resolved by interface name. Conflict is a situation in which a class
implements two interfaces which have same variable name. Conflicted variable must be accessed
by interface name otherwise compiler will throw error.
interface A {
int id = 10;
}
interface B {
int id = 20;
}

class MyClass implements A, B {


public static void main(String args []) {
// System.out.println(id); // compilation error if uncommented
System.out.println(A.id); // Access interface A variable, prints 10
System.out.println(B.id); // Access interface B variable, prints 20
}
}
 The object of implementing class can also be assigned into interface type. Using such object you
can call only the methods declared inside the interface. If you call a method defined inside class
using such object, it will result in compilation error.
interface MyInterface {
void print();
}

class MyClass implements MyInterface {


public void print() {
System.out.println("Inside print method");
}
public void message() {
System.out.println("Inside message method");
}
public static void main(String args []) {
MyInterface obj = new MyClass(); // Assigning MyClass object into MyInterface type
// obj.message(); // Error if uncommented, message() is not interface method
obj.print(); // prints "Inside print method"
}
}
 A class can extend another class and can implement an interface as well.
class MyClass extends AnotherClassName implements InterfaceName { }
 From java 8 onward an interface can have default and static methods with body. Refer New
features in Interfaces section for the same.
 An interface can have another interface inside it. Refer Nested Interface section for the same.

Interfaces changes in Java 8 & Java 9


184 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Before java 8 an interface can have only constant variables and abstract methods. Java 8 and 9
introduced some new features in interfaces like default methods, static methods and private methods.
Let's see these features of interfaces one by one.
Interface changes in Java 8
Java 8 has introduced two new features in interfaces, default methods and static methods. From java 8
onward an interface can have following components inside it.
 Constant variables
 Abstract methods
 Nested Types
 Default methods
 Static methods
Default methods in java interfaces
From java 8 onward an interface can have default method with a body. A default method is defined
using default keyword. The syntax of declaring a default method is :
interface interfaceName {
default return_type methodName() {
// method definition
}}
Example:
interface MyInterface {
default void print() {
// method definition
}}
Some key points about default methods are :
 A default method must have a body.
 The access modifier of default methods are implicitly public.
 The class implementing such interface are not required to implement default methods. If needed,
implementing class can override default methods.
Default methods enable you to add new functionality to the interfaces of your application and ensures
that your old version of code won't break as it doesn't force the classes to implement this. Before java 8
adding new method in an interface broke the classes which already had implemented that interface.
The purpose of providing this feature is to allow the developers to add new functionalities to their
interfaces whenever needed, without breaking their older version of code.
Java program of default methods in interface
interface MyInterface {
void calculateArea();
default void print() {
System.out.println("This is default method");
}
}
class DefaultMethod implements MyInterface {
public void calculateArea() {
System.out.println("Calculate area in this method");
185 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
public static void main(String args []) {
DefaultMethod obj = new DefaultMethod();
obj.print();
obj.calculateArea();
}}
Output:
This is default method
Calculate area in this method
Static methods in java interfaces
From java 8 onward you can define static methods in an interface which can be called without the
object of implementing class. The syntax of declaring static method is :
interface interfaceName {
static return_type methodName() {
// method definition
}
}
Example:
interface MyInterface {
static void print() {
// method definition
}
}
Some key points about static methods are :
 A static method must have a body.
 The access modifier of static methods are implicitly public.
 These method must be called using interface name.
 Since these methods are static, we cannot override them in implementing class.
Java program of static method in interface
interface MyInterface {
void calculateArea();
static void print() {
System.out.println("This is static method");
}
}
class StaticMethod implements MyInterface {
public void calculateArea() {
System.out.println("Calculate area in this method");
}
public static void main(String args []) {
StaticMethod obj = new StaticMethod();
obj.calculateArea();
MyInterface.print();
}
186 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
Output:
Calculate area in this method
This is static method

Interfaces changes in Java 9


Java 9 introduced private methods and private static methods in interfaces. Static methods in java 8
can not be private but from java 9 it can be. From java 9 onward an interface can have following
components inside it.
 Constant variables
 Abstract methods
 Nested Types
 Default methods
 Static methods
 Private methods
 Private Static methods
Private and Private Static Methods in Java Interfaces
A private method is defined using private access modifier. The basic syntax of declaring a private and
private static method in an interface is :
interface interfaceName {
private return_type methodName() {
// method definition
}
private static return_type methodName() {
// method definition
}}
Example:
interface MyInterface {
private void message() {
// method definition
}
private static void detail() {
// method definition
}
}
Some key points about private methods are :
 A private method must have a body.
 These method can be accessed within the interface only.
 Since these methods are private, we cannot override them in implementing class.
The purpose of adding private methods in interfaces is to improve the code re-usability. These methods
are generally used as utility methods which helps other defined methods inside that interface.
Java program of private method in interface
interface MyInterface {
default void print() {
187 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("This is default method");
// calling private methods
message();
detail();
}
private void message() {
System.out.println("This is private method");
}
private static void detail() {
System.out.println("This is private static method");
}
}
class PrivateMethods implements MyInterface {
public static void main(String args []) {
PrivateMethods obj = new PrivateMethods();
obj.print();
}}
Output:
This is default method
This is private method
This is private static method

 An interface can have multiple default methods from java 8 onward.


 An interface can have multiple private and static methods.
 If an interface extends another interface, private methods are not inherited.
 From java 8 onward we can define main method inside an interface and we can run it like classes.

Nested Interfaces in Java


Similar to nested classes we have nested interfaces in java. An interface defined inside another
interface or class is known as nested interface. Nested interface is also known as inner interfaces or
member interfaces. Nested interfaces are generally used to group related interfaces. The syntax of
declaring nested interface is :
interface OuterInterfaceName {
interface InnerInterfaceName {
// constant declarations
// Method declarations
}
}

Example :
interface MyInterface {
interface MyInnerInterface {
int id = 20;
void print();
188 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
}
Nested interface can be defined anywhere inside outer interface or class. Some of the key points about
nested interfaces are :
 Nested interfaces are static by default, irrespective of you declare it static or not.
 Nested interfaces are accessed using outer interface or class name.
 Nested interfaces declared inside a class can have any access modifier, while nested interfaces
declared inside another interfaces are public by default.
 Classes implementing inner interface are required to implement only inner interface methods, not
outer interface methods.
 Classes implementing outer interface are required to implement only outer interface methods, not
inner interface methods.
Does java compiler creates separate .class file for nested interfaces? Yes, Java
compiler creates separate .class file for nested interfaces, whose name is made with combination of
outer and inner interface name with $ sign in between. For example the name of .class file in above
declaration would be MyInterface$MyInnerInterface.class.
Nested interface program in Java
interface MyInterface {
void calculateArea();
interface MyInnerInterface {
int id = 20;
void print();
}
}
class NestedInterface implements MyInterface.MyInnerInterface {
public void print() {
System.out.println("Print method of nested interface");
}
public static void main(String args []) {
NestedInterface obj = new NestedInterface();
obj.print();
System.out.println(obj.id);
}
}
Output:
Print method of nested interface
20
As mentioned above nested interface can be declared inside a class as well. Class implementing such
interface needs to define all the methods of that nested interface. The program below demonstrates the
nested interface declared inside a class.
Java program of nested interface declared inside a class
class OuterClass {
interface MyInnerInterface {
int id = 20;
189 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
void print();
}
}
class NestedInterfaceDemo implements OuterClass.MyInnerInterface {
public void print() {
System.out.println("Print method of nested interface");
}
public static void main(String args []) {
NestedInterfaceDemo obj = new NestedInterfaceDemo();
obj.print();
System.out.println(obj.id);
// Assigning the object into nested interface type
OuterClass.MyInnerInterface obj2 = new NestedInterfaceDemo();
obj2.print();
}
}
Output:
Print method of nested interface
20
Print method of nested interface
The object of implementing class can also be assigned in to nested interface type, as in above
program obj2 is an object of NestedInterfaceDemo class but assigned into MyInnerInterface type. As
mentioned above class implementing an outer interface are not required to implement the inner or
nested interface methods. The program below demonstrates the same.
interface MyInterface {
void calculateArea();
interface MyInnerInterface {
int id = 20;
void print();
}
}
class OuterInterfaceTest implements MyInterface {
public void calculateArea() {
System.out.println("Calculate area inside this method");
}
public static void main(String args []) {
OuterInterfaceTest obj = new OuterInterfaceTest();
obj.calculateArea();
}
}
Output:
Calculate area inside this method
Why do we use nested interface in java
190 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
There are couple of reasons for using nested interfaces in java :
 Nesting of interfaces is a way of logically grouping interfaces which are related or used at one place
only.
 Nesting of interfaces helps to write more readable and maintainable code.
 It also increases encapsulation.
One example of nested interface in java library is java.util.Map.Entry interface defined inside
java.util.Map interface. We access it as Map.Entry, as it's a nested interface.
1. An interface or class can have any number of inner interfaces inside it.
2. Inner interface can extend it's outer interface.
3. Inner and outer interfaces can have method and variables with same name.
4. Nested interfaces can also have default and static methods from java 8 onward.
5. An inner class defined inside an interface can implement the interface.
6. Nesting of interfaces can be done any number of times. As a good practice you should avoid
doing nesting more than once.

BASIC STRUCTURE OF JAVA PROGRAM


Let us explain the basic structure of java program. It covers a brief detail of common components of
a java program and the order it must be declare / defined inside a java program. Writing the
program in a structured way helps you understand the program easily. Some orders of components
are mandatory to follow while others are not, but it's a good practice to follow the orders given here to
make your program more readable. The basic components of a java program and their order of
declaration are :
1.Package Statement 2.Import Statement
3.Documentation or comment
4.Class Definition
Declare instance and static variables
Declare constructors(if any)
Main method or other methods
Before we start to understand these components, let's see a program demonstrating above structure
first, then we will see each component one by one.

CLASS DEMONSTRATING BASIC STRUCTURE OF JAVA PROGRAM.


package mypack;
import java.util.Date;
/**
* The ProgramStructure class used to demonstrate
* the structure of java program.
*
* @author refreshjava
*/
class ProgramStructure {
/* The variable date is used to store
the current date. */
public static Date date = new Date();
191 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// This variable stores website name.
private String siteName = "refreshjava.com";

/**
* The no argument constructor.
*/
public void ProgramStructure() {
System.out.println("No argument constructor");
}
/**
* This method prints the string passed to it in console.
*
* @param str The string to be printed
*/
public void printMessage(String str) {
System.out.println(str);
}
/**
* Entry point, it's the first method to be called
* while running this class.
*/
public static void main(String args []) {
ProgramStructure obj = new ProgramStructure();
obj.printMessage("Java program of code structure");
System.out.println("Program was written on = "+date);
System.out.println("Program author : "+obj.siteName);
}
}
Output:
Java program of code structure
Program was written on = Tue Apr 28 09:04:36 IST 2020
Program author : refreshjava.com

Package Statement in Java


A package is a group of similar types of classes and interfaces. A package name is basically a directory
in your computer where the given class/program is saved. It's an optional statement, if you don't
declare any package, your program will be saved inside a default package(no name package).
Package declaration in above program is :
package mypack;
There can be only one package statement inside a program and it must be the first line of code in your
program. The program must be saved inside that package(directory), for example the above program
must be saved inside mypack directory. To get more detail about packages refer packages in
java section.
Import Statements in Java
192 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
If your program wants to access classes of any other packages, then those classes or packages must
be imported in your program first. Import statements basically imports/includes the classes of a
packages in your program, once imported you can use the classes of that packages in your program.
All the Import statements must be written after package name declaration and before class name
declaration. We can import a single class or all classes of a package like below :
import java.util.Date; //imports only Date class
import java.util.*; //imports all the classes of java.util package
Documentation or comment in Java
Documentation or comment is basically a little detail about your components(class, method, variable
etc) like what it does or what it is used for etc. Documentation makes it easy for you and your team
mates to understand your program easily. Documentation or comment about a component should be
written just before it's declaration. Though it's optional to write the documentation or comment but it's a
good practice to write them at the time of designing the component. It's not necessary to write the
documentation for each and every element of a program. Java provides the following approaches to
write documentation or comments in your programs.

 Single line comment : It starts with two forward slashes // and followed by your comment. Any text
after // and till the end of line is considered as comment. You can use single line comments
anywhere and up to any number of times in your program.
// This is single line comment
 Multi line comment : It starts with /* and ends with */. Any text between /* and */ will be
considered as comment. You can use multi line comments anywhere and up to any number of
times in your program.
/*
This is multi line comment
This is multi line comment
*/
 Documentation : It starts with /** and ends with */. Any text between /** and */ will be
considered as document. We generally use documentation for classes, constructors and methods.
/**
* This is documentation, used to give
* the little detail of component.
*/
Does these documents or comments executed while compiling or executing the program ?
No, Java completely ignores them, which means they are not executed while compiling or executing
the program. Note : While learning java, you can avoid to use comments as it takes time but if you are
working on any project or application then you should follow to write the documents or comments about
different components of your program as it will make your program more readable.
Class Definition in Java
193 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
In java, a program is basically a group of one or more classes. We define a class using class keyword,
followed by class name. As a good practice programmer should write a meaningful name to their
classes. Everything given inside { } after class name is the part of that class. As a good practice you
should write little detail about your class before it's declaration, as given in above program. To get more
detail about classes refer classes in java section.
Declare static and non static variables
Inside the class, first you should declare all your static and non static variables of that class. Though
it's not mandate, but it's a good practice to define the variables before defining methods or constructors
of a class. It makes easy to understand your program.
Declare constructors
After variables you should define the constructors(if any) of that class, again it's not mandatory, it's
just a good practice to follow. You should define all your constructors before defining the methods. Also
write little detail about the constructors as given in above example to make it easy to understand that
constructor.
Declare main method or other methods
After defining constructors, you should define the main method and other methods of that class. You
should also write little detail about the method before it's declaration to make it easy to understand. In
java, to run a program independently it must have a main method like below :
public static void main(String args []) {
// method body
}
The main method is the entry point of a program which means it's the fist method which will be called
while running your program.
What if I need to declare an interface in my program? Generally interfaces are declared in a
separate file, but if needed you can declare it before class declaration as interfaces are designed to be
implemented by classes. Though it's not mandatory to declare before class but doing so makes your
program more readable.
1. Keep in mind that java keywords and code is case sensitive.
2. Generally You need to define a class to write a program in java.
3. You must save your program with same name as class name having main method.
4. A program may have only variables, methods or constructors.
5. Generally each class in java is defined in separate file but we can define multiple classes in
same file.
Basic Concepts of Oops in Java
Object oriented programming(OOP) is a programming paradigm or style of writing program. As the term
object oriented programming itself suggests, writing programs in this style is oriented or based on the
concept of objects. This programming style says that, view everything as an object, be it you, your car,
dog, chair, house, remote etc where each objects have it's own data and behaviors. The data of an
object is basically the properties of that object while behavior is something, what that object does. For
example a person object have properties like name, age, height etc while behaviors like walk, talk,
eat etc. So in OOP, computer programs are basically a representation of object's data and behavior.
The data of an object in a program is given using variable(instance variable) while behavior is given in
194 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
form of methods(instance methods). Each object can change it's data and behavior as the user wants
and it can also interact with other object through it's behaviors. The object oriented programming has
following concepts and features :
 Object ●Class ●Interface
 Object oriented programming features :
Abstraction
Encapsulation
Inheritance
Polymorphism

What is Object in Oops


An object can be think of a real world entity, for example person, dog, chair bicycle, television etc are
objects. These objects have two things, state(attributes or properties or data) and behavior. To give you
an example, a person have state like name, age, height etc and behaviors like walk, talk, eat etc.
Identifying the state and behavior of an object is a great way to start thinking in terms of object-oriented
programming. Programmatically an object is a software bundle of state and behavior. State of an object
is defined by instance variables and behavior of an object is defined by methods. Think it in another
way, the instance variables of your program defines the state of object while the instance methods of
your program defines the behavior of object.

What is Class in Oops


All object-oriented programming languages support the concept of class. A class is basically a
predefined instructions which tells that what data and behavior the object of that class will have. The
behavior of an object is given in the form of methods in a class while the data is given in the form of
fields. We also call these predefined instructions, a template or design. For example if we need to
create a class for person objects, we can do something like below :
class Person {
String name;
int age;

void talk() {
System.out.println("I can talk");
}
void walk() {
System.out.println("I can walk");
}
}
195 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Here the Person is a class which is basically describing that the object of this class will have fields/data
like name and age while behaviors like talk and walk.
What is Interface in Oops
Interfaces are very similar as classes except that they only declare the set of behaviors of an object,
they don't define(implement) those behaviors. The implementation or definition of those behaviors are
given by the classes implementing that interface. More programmatically, Interfaces declares only the
signature of the methods and not their implementations. The methods that are declared in the interface
are implemented by the implementing classes. The code below shows how we create an interface in
java :
interface Shape {
public void draw();
public double getArea();
}
Here Shape is an interface which declares the behaviors draw and getArea. If a shape class like circle,
rectangle etc implements this interface, they will provide the implementation of these behaviors.
What is Abstraction in Oops
Abstraction is a process of hiding the internal details or implementations from the user and
showing only relevant or abstract (brief or short) information to user. Abstractions says that, show
only that information of an objects behavior which is essential or useful for the user and hide all other
information which is not essential for them. A real-world example of abstraction could be your TV
remote. The remote has different functions like on/off, change channel, increase/decrease volume etc.
We use these functionalities just pressing the button. The internal mechanism of these functionalities
are abstracted(hidden) from us as those are not essential for us to know, this is what abstraction is.
Abstraction says that, focus on what an object does rather than how it does. In java abstraction is
achieved using abstract classes and interfaces as these types contains set of abstract
behaviors(method), the internal working of these behaviors are defined by some other classes.
What is Encapsulation in Oops
Encapsulation process of binding or enclosing(as in a capsule) the state(instance variables)
and behavior(methods) together in a single unit is known as encapsulation. You can think of
encapsulation as a cover or layer which binds the data and behavior together in a single unit. This layer
prevents the access of data/behavior of a class outside the class. To take a real world example, we can
think of capsule, as capsule binds all it's medicinal materials within it, similarly in java encapsulation
units(class, interface etc) encloses all it's data and behavior within it. In java every class, interface or
object that we create is a form of encapsulation. Each class contains it's information(variables and
methods) associated with it, other classes needs to create object of this class in order to access these
information.

What is Inheritance in Oops


Inheritance is a mechanism by which object of one class is allowed to inherit the features(fields
and methods) of another class. This feature basically allows us to reuse the existing code. The class
that inherits the feature of another class is known as subclass or child class and the class whose
feature is being inherited is known as super class or parent class. By inheriting the parent class the
child class get's the access of fields and methods of parent class. To take a real world example we can
196 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
consider parent child relationship. The properties of parents like hands, legs, eyes etc and the
behaviors like walk, talk, eat etc are inherited in child, so child can also use/access these properties
and behavior whenever needed. Java provides extends keyword to inherit the feature of an existing
class. The basic syntax of inheriting a class is :
class A extends B {
// Here Class A will inherit the features of Class B
}
Here class A is subclass or child class while class B is superclass or parent class. Here Class A will
inherit the features of class B which means class A will be able to access the variables and methods of
class B. Refer inheritance in java section for more detail about inheritance.
What is Polymorphism in Oops
This is another fundamental principle of object oriented programming. The word polymorphism is made
from two words, Poly which means many and morphism which means forms or types, so the word
polymorphism means many forms. Polymorphims in java is a mechanism in which the object or it's
behavior can have many different forms.
More programmatically in java a child class object can be assigned in any of it's parent class type which
means the object of child class can take the form or act as any of it's parent class in inheritance
hierarchy. We call such objects as polymorphic object. To take a real world example, we can consider
ourself. As a person we have many different forms like student, teacher, player, father/mother etc. The
same person can be a teacher as well as a player, so we can say person object is polymorphic in
nature.
1. Java is an object oriented programming language but not purely object oriented.
2. Some of other object oriented programming languages are C++, C#, Go, Lisp, Ruby, etc.
3. Smalltalk language is purely object oriented language.
4. Some of the non object oriented programming languages are ALGOL, BASIC, Pascal, C etc.
5. If a language supports oops features, we call it object oriented programming language.

Inheritance in Java - Examples, Uses, Advantages


Inheritance is one of the fundamental principle of object oriented programming. It is used quite often in
java programming language. This section covers different details about inheritance like what
inheritance is, real world example of inheritance, how it is achieved in java, what are the advantages of
using inheritance etc.
What is Inheritance
In general the meaning of inheritance is something that you got from your predecessor or parent, the
same applies with java inheritance as well. Inheritance in java is a mechanism by which one class is
allowed to inherit the features(fields and methods) of another class. The class that inherits the feature
of another class is known as subclass or child class and the class whose feature is being inherited is
known as super class or parent class. By inheriting the parent class the child class get's the access of
fields and methods of parent class. More programmatically, inheritance feature allows the object of
child class to acquire the properties and behavior of parent class, which simply means, using
inheritance the object of child class get's the access of fields/methods of parent class even though
those fields/methods are not defined in child class, they are defined only in parent class.
Real life example of inheritance
197 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
We can take parent and child relationship as an example of inheritance. The properties of parents like
hands, legs, eyes, nose etc and the behaviors like walk, talk, eat, sleep etc are inherited in child, so
child can also use/access these properties and behavior whenever needed. Along with some common
properties and behavior, both parent and child can have their specific or private properties as well, for
example parent and child have their specific properties as blood group, date of birth etc and specific
behavior like one plays cricket or any other game while other doesn't.

Generally in programming, the child classes will have more features than parent classes as they
declare their own features as well apart from inheriting the parent classes features, so do not over
indulge with real life example of inheritance.
How to implement inheritance in Java
Java provides extends keyword to inherit the features of a class. Using extends keyword your class can
inherit the features of another class. The basic syntax of inheriting a class in java is :
class A extends B {
// Here Class A will inherit the features of Class B
}
Here class A will inherit the features of class B which means object of class A will be able to access the
variables and methods of class B. In addition to the access of superclass fields and methods, the
subclasses can have their own fields and methods. Here class A is subclass or child class while class
B is superclass or parent class.
Who decides whether to inherit a class or not ? It's the programmer's who decides whether
his class needs to inherit(extend) another class or not.
Important terminologies in Java inheritance
Subclass/Child class : The class that inherits the features of other class is known as subclass, also
known as child class, derived class or extended class.
Superclass/Parent class : The class whose features are being inherited is known as super class, also
known as parent class or base class.
Now let's see how we can inherit the features of a class using the program below :
Inheritance program in Java
class B {
198 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
String message = "This is class A variable";
void add(int a, int b) {
System.out.println(a +"+" +b+" = "+(a+b));
}
}

class A extends B {
void subtract(int a, int b) {
System.out.println(a +"-" +b+" = " +(a-b));
}
public static void main(String args []) {
A obj = new A();
obj.add(5,10);
System.out.println(obj.message);
obj.subtract(20,10);
}
}
Output:
5+10 = 15
This is class A variable
20-10 = 10
Here you can see that the object of child class A is able to access the add method and message
variable of class B, because the methods and variables of class B is inherited in child class A
using extends keyword.
Can I access every member of parent class in child class? No, the accessibility of parent
class members inside child class is also decided by access modifier. The child class can access only
those variables/features of parent class which has an access modifier that allows it to be accessed
outside the class. For example a private variable or method in parent class won't be accessible inside
child class.
What is IS-A relationship
IS-A relationship in java represents Inheritance. When there is an extends or implements keyword in
the class declaration, then that specific class is said to be following the IS-A relationship. In other way
when you see Is-A relationship between two entities, you can use inheritance. For example :
A student is a person.
A car is a vehicle.
A dog is an animal.
A chair is a furniture.
Which means a class student can extends a class person, since student is a person. Similarly a
class Car can extends a class Vehicle, since car is a vehicle. Let's see this by the example below :
Student and Person class inheritance program
class Person {
String name = "Rahul";
int age = 20;
199 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
void talk() {
System.out.println("I can talk");
}
}

class Student extends Person {


int rollno = 30;

void study() {
System.out.println("I am studying");
}
public static void main(String args []) {
Student obj = new Student();
System.out.println("Name : "+obj.name+", age : "+obj.age+", rollno : "+obj.rollno);
obj.talk();
obj.study();
}
}
Output:
Name : Rahul, age : 20, rollno : 30
I can talk
I am studying
When do we use inheritance in java?
Though it's quite clear that when you want to reuse the features which is already created in some class,
you should use inheritance, but as a good practice generally you should see if there is is-a relationship
in both the classes or not, if yes then you should use inheritance there. In other way, when you want to
create a more specific version of a given class, you should use inheritance. For example a car is a
more specific version of a vehicle because a vehicle can be of other types as well, like bike, bus, auto
etc. In this case the class car can extend class vehicle. Furthermore, if you want to create more specific
version of a car like suv car or sedan car then you can use the inheritance between suvcar and car
class as well. More programmatically, inheritance comes into consideration, when there are certain
classes which have common properties and behavior in them. You can put these common properties
and behavior in a separate class and made it as generic class, the specific version classes can extend
this class and reuse those properties and behaviors.
What we can do in subclasses?
The subclasses can do everything that a normal class do along with inheriting the variables and
methods of parent class, just to list down some of the things :
 We can declare new variable in the subclass that are not in the superclass.
 We can declare a variable in the subclass with same name as the one in superclass. In this
case the subclass variable hides the superclass variable, thus the subclass doesn't inherit the
variable from its superclass.
 We can write a new instance or static method in the subclass that are not in the superclass.
 We can write a new instance method in the subclass that has the same signature as superclass
method. In this case the subclass does not inherit the method from its superclass. It is also
known as method overriding.
200 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 We can write a new static method in the subclass that has the same signature as the superclass
method. In this case the subclass static method will hide the super class static method but it
won't override that method.
 The subclass constructor implicitly invokes the constructor of superclass. We can call it explicitly
as well using the super keyword. If calling explicitly, then it must be the first statement in your
subclass constructor.
Advantages of Inheritance
 The biggest advantage of inheritance is code reusability, since the fields and methods of
parent class get's inherited in child class, the child class won't have to create it again. It can
access those features from parent class, that is what the code reusability is.
 It also help's to reduce code duplicacy. If inheritance is not used, multiple classes may need to
write similar functions/logic in their body.
 Another advantages of inheritance is extensibility, you can add new features or change the
existing features easily in subclasses.
 Using inheritance we can achieve runtime polymorphism(method overriding).
 Inheritance makes easy to maintain the code, as the common codes are written at one place.
What if I don't want my class to be inherited by any other class ?
Declare your class using final keyword, eg. final class A { ... }. Final classes can not be inherited. We
will see details of final keyword in later section.
1. Every class in java internally extends Object class, so Object class is the super class of every
class.
2. If a class extends another class, then it won't extends Object class, instead it's parent class will
inherit the Object class.
3. A class can inherit only one class, as multiple inheritance is not allowed in java.
4. The classes involved in inheritance can be in same or different packages.
5. Static classes can also be inherited.
6. You can not extends a class which is not visible(as per access modifier) in your class.
7. If a class implements an interface, that is also a form of inheritance.

Different Types of Inheritance in Java


There are different types of inheritance supported by java. The programmers can use any of them as
per the requirement. The different types of inheritance supported in java are :
 Single inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Multiple inheritance(Supported using interfaces, not by classes)
 Hybrid inheritance(Mix of two or more of above inheritance types)
201 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Single level Inheritance in Java


When a class inherits only one another class, we call it single inheritance or single level inheritance.
This is the simplest form of inheritance as it involves only two classes. Below program shows an
example of single inheritance.
Single inheritance program in Java
class A {
void add(int a, int b) {
System.out.println(a +"+" +b+" = "+(a+b));
}
}

class B extends A {
void subtract(int a, int b) {
System.out.println(a +"-" +b+" = " +(a-b));
}
public static void main(String args []) {
B obj = new B();
obj.add(5,10);
obj.subtract(20,10);
}
}
Output:
202 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
5+10 = 15
20-10 = 10
Multilevel Inheritance in Java
When three or more than three classes inherits in same chain or level, we call it multilevel inheritance.
The number of classes in multilevel inheritance is not limited to three classes, it can go up to any
number of classes in the same level or inheritance chain.
In multilevel inheritance the class at any position(level) can access the features of all the classes which
are on top of that level. For example the class at bottom of chain will be able to access the features of
class which is on top of that chain. The program below shows an example of multilevel inheritance.
Multilevel inheritance in java Program
class A {
void add(int a, int b) {
System.out.println(a +"+" +b+" = "+(a+b));
}
}
class B extends A {
void subtract(int a, int b) {
System.out.println(a +"-" +b+" = " +(a-b));
}
}
class C extends B {
void multiply(int a, int b) {
System.out.println(a +"*" +b+" = " +(a*b));
}
public static void main(String args []) {
C obj = new C();
obj.add(5,10);
obj.subtract(20,10);
obj.multiply(10,20);
}
}
Output:
5+10 = 15
20-10 = 10
10*20 = 200
Hierarchical Inheritance in Java
When two or more than two classes inherits a single class, we call it hierarchical inheritance. In java a
class can be inherited by any number of classes, so in hierarchical inheritance, there can be any
number of child classes, it's not limited to two classes only. The program below shows an example of
hierarchical inheritance.
Hierarchical inheritance program in Java
class A {
void add(int a, int b) {
System.out.println(a +"+" +b+" = "+(a+b));
203 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
}
class B extends A {
void multiply(int a, int b) {
System.out.println(a +"*" +b+" = " +(a*b));
}
}
class C extends A {
void divide(int a, int b) {
System.out.println(a +"/" +b+" = " +(a/b));
}
}
class Test {
public static void main(String args []) {
B obj = new B();
obj.add(5,10);
obj.multiply(20,10);

C obj2 = new C();


obj2.add(20,30);
obj2.divide(20,10);
}
}
Output:
5+10 = 15
20*10 = 200
20+30 = 50
20/10 = 2
Multiple Inheritance in Java
When a class inherits the features from more than one parent, we call it multiple inheritance. Multiple
inheritance in java is not supported using classes, which means a class can not extend more than one
class. Multiple inheritance in java is supported through interfaces only, which means a class can inherit
the features(specially default and static methods from java 8 onwards) from more than one interfaces.
Java allows a class to implement any number of interfaces. The program below shows an example of
multiple inheritance.
Multiple inheritance program in Java
interface A {
public void print();
default void add(int a, int b) {
System.out.println(a +"+" +b+" = "+(a+b));
}
}
interface B {
public void print();
204 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
default void subtract(int a, int b) {
System.out.println(a +"-" +b+" = " +(a-b));
}
}
class C implements A, B {
public void print() {
System.out.println("Testing multiple inheritance in Java");
}
public static void main(String args []) {
C obj = new C();
obj.print();
obj.add(20,10);
obj.subtract(20,10);
}
}
Output:
Testing multiple inheritance in Java
20+10 = 30
20-10 = 10
The above program will work if you are using java 8 or onward. If you are using any lower version, then
you need to remove the default methods and it's calling from class C to make it work. There are couple
of points to note about multiple inheritance through interfaces: If a class implements two interfaces
which have same name variables and if the class needs to access such variables, then they must be
accessed by interface name. The same applies with static(java 8 onwards) methods as well. If a class
implements two interfaces which have same default(java 8 onwards) methods, then that method must
be overridden in implementing class. A class cannot implement two interfaces that have method with
same name but different return type.
Why Java does not support multiple inheritance through classes?
This is a design decision taken by the creators of java. To make java simple and reduce the complexity,
multiple inheritance is not supported in java. E.g., consider a scenario where we have three classes A,
B, and C. The class C inherits class A and B. If classes A and B have same name method(or variable),
now if you try to call the same method with object of child class C, the object will get confused, since
there will be ambiguity to call the method of class A or class B. So ambiguity is one of the main reason
why java does not support multiple inheritance.
Hybrid Inheritance in Java
Hybrid inheritance, as the name itself suggests, it is a mix of two or more inheritance types given
above. The hybrid inheritance diagram given in the beginning of this section is a mix of hierarchical and
multiple inheritance but it's not limited to that only, it may contain the mix of any other inheritance types
as well. If hybrid inheritance contains multiple inheritance, then it won't be supported through classes,
as java doesn't support multiple inheritance using classes. Its supported through interfaces only.
Can we access all variables and features of parent class in child class?
No, the accessibility of parent class features inside child class is also decided by access modifier. The
child class can access only those variables/features of parent class which has an access modifier that
205 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
allows it to be accessed outside the class. For example a private variable or method in parent class
won't be accessible inside child class.
1. Since multiple inheritance is not supported, so if a class inherits another class then it wont
extend the Object class of java. In this case parent class will inherit the Object class.
2. The classes involved in any inheritance type can be in same or different packages.
3. C++ , Common lisp and few other languages supports multiple inheritance.
4. Multiple Inheritance is not used very often in software projects.
Abstraction in Java with realtime Example
Abstraction is also one of the fundamental principal of object-oriented programming languages and a
key element of good software design. Many times beginners find it difficult to understand this, so we will
see this concept with some real world examples to make it easy to understand.
What is Abstraction in Java
Abstraction is a process of hiding the internal details or implementations from the user and showing
only relevant or abstract(brief or short) information to user. Abstractions says that, show only those
information to user which is essential or useful for them and hide all other information which is not
essential for them. More programmatically, abstraction in java is the process of hiding implementation
details of object's feature and showing only the essential information of feature to the user. Abstraction
lets you focus more on what an object does rather than how it does.
Real time example of abstraction
To take a real time example, when we login to any social networking site like Facebook, Twitter,
Linkedin etc, we enter our user id and password and then we get logged in. Here we don't know how
they are processing the data or what logic or algorithm they are using for login. Those informations are
abstracted/hidden from us, since those are not essential for us. This is basically what abstraction is.
Another real world example of abstraction could be your TV remote. The remote has different functions
like on/off, change channel, increase/decrease volume etc. You use these functionalities just pressing
the button. The internal mechanism of these functionalities are abstracted from you as those are not
essential for you to know. In fact every object that you see around yourself has some degree of
abstraction in one way or other, be it your Mobile, Laptop, AC, Fan, Car or whatever. The internal
working of these objects are hidden from us.
How to achieve abstraction in Java
In java generally we use interfaces and abstract classes to achieve abstraction. An interface or
abstract class is something that is not concrete, something which is abstract/incomplete because these
types contains abstract methods whose functionality or the internal mechanism is not defined by the
interfaces/abstract classes itself, rather it is defined/implemented by other classes. For example if I
declare an interface like below :
interface Shape {
public void draw();
public double getArea();
}
When you look the above interface, you don't know the functionality or implementation detail of it's
abstract methods, you only know the name of method(feature), the functionality will be given by some
other class. This is what the abstraction is, wherein you only know the features. Now before we start to
understand abstraction with program, let's see a brief detail about abstract method and abstract
classes. We will see the complete details about both topic in later section.
206 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Abstract Method
A method without a body is known as an abstract method. Abstract methods do not have an
implementation, they only have method signature. These methods are declared in an abstract class or
interface. The following code declares an abstract method draw.
public abstract void draw();
Inside the interfaces we don't need to apply the abstract keyword with method declaration as it is
internally applied by interfaces but in case of abstract classes, we need to apply abstract keyword
explicitly with abstract methods.
Abstract Class
An abstract class is a class which is declared using abstract keyword. Abstract classes are very similar
as normal classes except that they can have abstract methods as well along with concrete methods.
We can not create the object of abstract classes. Following code defines an abstract
class MyAbstractClass.
abstract class MyAbstractClass {
// Class body
}
An abstract class may contain one or more abstract methods while an interface contains only(Before
Java 8) abstract methods. Interfaces allows you to achieve complete abstraction while abstract classes
can be used to achieve partial as well as complete abstraction. Abstract classes are generally used for
partial abstraction.
Java Program of abstraction using Interface
The classes in below program implements the Shape interface that we discussed above.
class Circle implements Shape {
private double radius;
public Circle(double r) {
this.radius = r;
}
public void draw() {
System.out.println("Drawing Circle");
}
public double getArea() {
return Math.PI*radius*radius;
}
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public void draw() {
System.out.println("Drawing Rectangle");
207 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
public double getArea() {
return length*width;
}}
Similar to Circle and Rectangle there can be other shape type as well that can
implement Shape interface. Now in order to access the features(getArea, draw) of a shape, all you
need to know is the implementing class, you don't need to know how they have implemented the
features, that can be hidden from you, this is what abstraction is. The class given below accesses
these features.
public class AbstractionTest {
public static void main (String args[]) {
// Shape object referring to circle.
Shape circle = new Circle(10);
circle.draw();
System.out.println("Area of given circle = "+circle.getArea());
// Shape object referring to rectangle.
Shape rect = new Rectangle(10,10);
rect.draw();
System.out.println("Area of given rectangle = "+rect.getArea());
}}
Output:
Drawing Circle
Area of given circle = 314.1592653589793
Drawing Rectangle
Area of given rectangle = 100.0
In order to run above program successfully, ensure that you have declared all the classes and
interfaces given above inside same directory.
Java Program of abstraction using abstract class
The program below contains an abstract class TwoDShape which contains one abstract and one
concrete method.
abstract class TwoDShape {
private double length;
private double width;
public TwoDShape(double length, double width) {
this.length = length;
this.width = width;
}
// Declaring abstract method
public abstract void draw();
// Defining concrete method
public double getArea() {
return length*width;
}
}
208 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
public class Rectangle extends TwoDShape {
public Rectangle(double length, double width) {
super(length,width);
}
public void draw() {
System.out.println("Drawing Rectangle");
}
public static void main (String args[]) {
// TwoDShape object referring to rectangle.
TwoDShape rect = new Rectangle(10,10);
rect.draw();
System.out.println("Area of given rectangle = "+rect.getArea());
}
}
Output:
Drawing Rectangle
Area of given rectangle = 100.0
Here the abstract class TwoDShape gives the definition of getArea method while hides the
implementation of draw method. The implementation of draw method is given by the implementing
class which is Rectangle class. So for us the TwoDShape class is an example of partial abstraction.
Example of Abstraction in Java language
In Java we can take Map interface as e.g.. The Map interface has declared many abstract methods
like get, put, remove, size etc. The classes like HashMap, TreeMap, Hashtable etc implements
this Map interface and provides the functionality of these methods. We use these implemented classes
and it's implemented methods in our programs without knowing how they have been implemented, as
that is not essential for us. So for us the Map interface is an abstraction. In fact everything in our
program has some abstraction behind it. E.g. the very common line System.out.println() that we use for
printing the value on console has some abstraction. We just know that it prints the value on console but
how it does we don't know, that is hidden from us since that is not essential for us.
Advantage of abstraction in Java
1. It reduces the complexity of viewing the things as it shows only essential information.
2. It helps to decouple the behavior(method) and it's implementation in a software/application.
3. It allows the flexibility to modify/change implementation logic if needed, as long as the outcome
of behavior is not affected by the modification.
4. It helps to increase security of an application or program as only important details are provided
to the user.
5. It also helps to avoid code duplication and increases reusability.
Should I really focus more to know the abstraction in detail ?
If you are a designer/architect who designs the solution or application, then it's definitely helpful for you
to have good understanding about abstraction feature, otherwise having a basic idea about it is
enough. That's all about abstraction in java. Both abstract classes and interfaces are used to achieve
abstraction and both have their own importance while designing a Java application, but developers
generally prefer to use interfaces over abstract classes for abstraction.
209 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

Encapsulation in Java with realtime Example


Encapsulation is another fundamental principal of OOP. Many programmers specially beginners find it
little difficult to understand what exactly the encapsulation is, so I will try to make it as simple as
possible. The section covers different details of encapsulation like what encapsulation is, example of
encapsulation, advantages of encapsulation, abstraction vs encapsulation etc.
What is Encapsulation
Encapsulation is a process or technique that binds the data(member variables) and behavior(methods)
together in a single unit. We call these unit's as class, interface, enum etc. The encapsulation process
ensures that the data and behavior of a unit can not be accessed directly from other unit. The first thing
that comes in mind when we hear encapsulation is capsule. The encapsulation is very similar as a
capsule, as capsule binds it's medicine within it, similarly in java the encapsulation process binds the
data and behavior of a unit with that unit. You can think of encapsulation as a cover or layer which
packages/binds related data and behavior together in a single unit.

Real world example of encapsulation


As I already mentioned, one of the real world example of encapsulation is Capsule, as capsule binds all
it's medicinal materials within it, similarly in java encapsulation units(class, interface, enums etc)
encloses all it's data and behavior within it. Another real world example can be your school or office
bag. The bag contains different stuffs like pen, pencil, notebook etc within it, in order to get any stuff
you need to open that bag, similarly in java an encapsulation unit contains it's data and behavior within
it and in order to access them you need an object of that unit.
Encapsulation example program in Java
Every class, interface, enum etc that we create is an example of encapsulation, so let's create a class
as given below to understand the encapsulation by an example :
class Person {
String name;
int age;
void walk() {
}
void talk() {
}
}
Here the Person class is an example of encapsulation. The variables(name, age) and methods(walk,
talk) of the class is packaged/binded in a single unit which is Person class. Here, the encapsulation
binds the implementation details of the Person class with it and hides it from other classes. If other
classes want's to access these detail, they need to create the object of Person class in order to access
it's data and behavior like below :
Person p = new Person();
p.name = "Rahul";
210 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
p.walk();
Similarly if you create an interface or enum, that is also an example of encapsulation. Now let's see
another form or extension of encapsulation which is data hiding.
What is Data Hiding
Data hiding or information hiding is a software development technique in object oriented programming
which is used to hide the data from outside world. The purpose of data hiding is to protect the data from
misuse by outside world. Data hiding is also known as data encapsulation.
Data Hiding = Hiding the Data
In java we use private access modifier to protect/hide the data and behavior from outside world. For
example if I declare the Person class variables like below :
class Person {
private String name;
private int age;
}
Here we are hiding the variables from outside the class. These variables will be visible within the class
only. This is basically what data hiding is wherein we hide the data of a class from outside world, so
that other classes can not change/access these data directly.
class ABC {
Person p = new Person();
p.name = "Rahul"; // compilation error, as name attribute won't be accessible here
}
Now the question is what if other classes wants to read and write these data ?, because if other classes
can't use this class data, then this class won't be that useful. So in order to allow these data to be
accessed from outside, we can create getters(getXXX()) and setters(setXXX()) methods for these
variables like below.
Data hiding program in Java
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public String getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
211 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The getters and setters methods are used to read and write the variable value of a class respectively.
In data hiding we generally allow other classes to access/modify the variables
through getters and setters only in order to avoid misuse of data.
Furthermore you can apply more control in setters method so that no one can set any unwanted value
to avoid misuse. For example if you don't want to allow other classes to set any blank or null value
in name field you can add below logic :
public void setName(String name) {
if(name == null || name.equals("")) {
throw new IllegalArgumentException("Name can not be null or empty");
}
this.name = name;
}
Similarly you can apply logics in other setter methods as well if needed, in order to protect any illegal
data. Applying such logics to avoid any illegal data basically increases the security of your application.
Why do we use data hiding
The main reason of using data hiding is security. As we use private modifiers with our variables, we can
store critical informations in such variables which will be visible within the class only, no one else can
access them directly. As we also apply conditions in setter methods whenever needed, it also
increases the security so that no one can set any illegal data for any misuse.
How to achieve encapsulation in Java
Though you are already achieving encapsulation by creating classes, interfaces, objects etc but if you
want to create a fully encapsulated class in java, follow below things :
Declare all your member variables with private access modifier.
Create public getters and setters methods of those variables in order to allow access of those variables
from outside the class.
Advantages of Encapsulation
 Security: Encapsulation helps to secure your code, since it ensures that other units(classes,
interfaces etc) can not access the data directly.
 Flexibility: Encapsulation makes your code more flexible, which in turn allows the programmer
to change or update the code easily.
 Control : Encapsulation gives the control over data stored in the member variables. For
example, you can control what value can be set in age of a Person given in above program
without breaking the code.
 Reusability: Encapsulated code or unit can be reused anywhere inside the application or
across multiple applications. For example, if you have Person or any other class in your
application you can reuse that class wherever needed.
 Maintainability: Encapsulated units are easy to maintain as you can locate or change the things
easily.
Difference between abstraction and encapsulation in Java
 Though both are quite interrelated and plays role in one another, but to list down some of the
differences :
 Abstraction focuses more or less on hiding the internal detail/logic while encapsulation focuses
more on protecting/hiding the data from misuse.
212 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 Abstraction is more or less design/modeling level concept while encapsulation is more or less
implementation level concept.
 Encapsulation focuses more on access modifiers to hide/protect the information while
abstraction focuses more on abstract methods to hide the implementation details.
 Using encapsulation, you can deny access to the fields of a unit either by declaring their getters
method as private or by not defining the getters method at all.
1. Java beans are good example of encapsulation in java, as they contains private variables with
public getters and setters methods.
2. As soon as you start increasing visibility of data and behavior with access modifier, you start
loosing their bindings with encapsulation units.
3. Using encapsulation you can make your class read only or write only. To make read only,
declare only getters method of your variables and for write only, declare only setters method of
your variables.
Polymorphism in Java with realtime Example
Polymorphism is another fundamental principal of object-oriented programming. Sometimes beginners
find it little difficult to understand what exactly the polymorphism is, so we will try to see this with some
real world examples and programs to understand this easily. This section covers different aspect of
polymorphism like what is polymorphism, real world example, advantages of polymorphism etc.
What is Polymorphism in Java
The word polymorphism is made from two words, poly which means many and morphism which
means forms or types, so the word polymorphism means many forms. Polymorphims in java is a
mechanism in which an object or it's behavior can have many different forms, we call such objects as
polymorphic object. Programmatically, in java the object of a child class can be assigned in any of its
parent classes in the inheritance hierarchy which means the object of a subclass can take the form of
any of it's parent classes in it's inheritance hierarchy, so we can say all the parent classes are basically
different forms of child class, which is what the polymorphism is. For example let's consider a scenario
in which we have class A, B and C where class C extends class B which extends class A. In this case
the object of class C can be assigned into class C, class B or class A which means the object of class
C can take form of it's own, class B or class A.

C ob = new C();
B b = c; or B b = new C(); // C class object will act as B class object
A a = c; or A a = new C(); // C class object will act as A class object
As you can see object of class C can be assigned into any of it's parent class which means class C
object can take forms of class B and class A as well along with it's own. This means object of C class is
213 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
polymorphic in nature. The same happens with class B object as well which can take the form of it's
own and class A.
Real time example of Polymorphism
To take a real time example, we can consider ourself. As a person we have many different forms like
student, teacher, player, father/mother etc. The same person can be a teacher as well as a player, so
we can say person object is polymorphic in nature. Another real world example is your mobile.
Sometime your mobile behaves as a phone, sometime as a camera, sometime as a radio etc. Here the
same mobile phone has different forms, so we can say the mobile object is polymorphic in nature.
Polymorphism program in Java
class Person {
String name;
void walk() {
System.out.println("My name is "+ name+ " and I can walk");
}
void talk() {
System.out.println("My name is "+ name+ " and I can talk");
}
}
class Teacher extends Person {
String subject;
void teach() {
System.out.println("I teaches "+subject);
}
public static void main(String [] args) {
Teacher teacher = new Teacher(); // teacher object having it's own form
teacher.name = "Rahul";
teacher.subject = "Math";
teacher.walk();
teacher.talk();
teacher.teach();
Person person = teacher; // teacher object takes the form of person object
person.walk();
person.talk();
//person.teach(); // Can't call teach method as it's not in Person class
}
}
Output:
My name is Rahul and I can walk
My name is Rahul and I can talk
I teaches Math
My name is Rahul and I can walk
My name is Rahul and I can talk
214 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Here the object of teacher class is polymorphic as it can take two forms, one as itself and other as
person. Remember if an object of subclass is behaving as parent class, then it can call the behaviors
available in parent class only. In above example once the teacher is behaving as person, it can call
only walk and talk behavior.
How to check if an object is polymorphic.
Any object which have more than one Is-A relationship will be called as polymorphic object. For
example in the scenario of class A, B, C given above, following observation will be true.
C is-a C
C is-a B
C is-a A
B is-a B
B is-a A
So the object of class C and class B will be polymorphic as they passes more than one is-a
relationship. But what about if we have the object of class A, will that be polymorphic ?. The answer is
yes, that will also be polymorphic. The reason is, every class in java internally extends Object class if it
has not extended any other class, so in above case class A will internally extend Object class, this way
the object of class A will also be polymorphic. So in java every object(except the object of Object class)
is polymorphic, no matter whether it's an object of user defined class or java's predefined class.
An is-a relation in java can be tested using instanceof operator. If an object passes more than
one instanceof test, that object will be polymorphic.
C ob = new C();
if(ob instanceof C) // true
if(ob instanceof B) // true
if(ob instanceof A) // true
Advantages of Polymorphism in Java
One advantage of polymorphism is that it allows us to reuse existing code which can make things
easier to read and maintain. In program given above the object of teacher class can access it's own
methods as well as the methods of person class. Another advantage is that, different form of objects
can be referred with same type(parent class). For example if we have multiple child classes of Person
class like student, employee, player etc, object of all such child classes can be referred with same
type(Person class). In java we have some more concepts/terminology in context of polymorphism
which are runtime and compile time polymorphism. These polymorphism are categorized on the basis
of resolving the call to a polymorphic method(A method having different forms). We will see these types
in later section.
Runtime and Compile time Polymorphism in Java
Runtime and compile-time polymorphism are the two types of polymorphism that happens in java. Both
of these polymorphism are named as per their working. As discussed in previous section,
polymorphism is a mechanism in which an object or it's behavior can have many different forms. In java
a class can have multiple methods with same name having different number/type of arguments, we call
such methods as polymorphic method or behavior. This is also known as method overloading which is
an example of compile time polymorphism. Similarly in java, a child class can also have a method with
same name having same number and type of argument as in parent class, this is known as method
overriding in java which is an example of runtime polymorphism. We will understand method
overloading and method overriding in detail in later sections.
215 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]

What is Compile time Polymorphism or Static Binding


In compile time polymorphism, the call to a polymorphic behavior(method) is resolved at compile time
rather than at runtime which means at runtime which particular form of that polymorphic method is
going to be called get's resolved at compile time itself, that is why we call it compile time polymorphism.
In other words, in compile time polymorphism, the behavior of an object in a polymorphic method call
get's decided at compile time itself rather than runtime. Let's understand this clearly with the program
given below.
Compile time polymorphism program in Java
class CompileTimePolymorphism {
void add(int a, int b) {
int sum = a + b;
System.out.println("sum of two numbers = "+sum);
}
void add(int a, int b, int c) {
int sum = a + b + c;
System.out.println("sum of three numbers = "+sum);
}
public static void main(String [] args) {
CompileTimePolymorphism obj = new CompileTimePolymorphism();
obj.add(20,30);
obj.add(20,30,40);
}
}
Output:
Sum of two numbers = 50
Sum of three numbers = 90
Here add method is an overloaded or polymorphic method since it is more than once in class. This is
known as method overloading in java. Here both methods differ on the basis of number of arguments
they accept, first add method accepts two arguments while later accepts three arguments. When
compiler compiles the lines obj.add(20,30) and obj.add(20,30,40), at the same time it binds the call
of add(int a, int b) with obj.add(20,30) and the call of add(int a, int b, int c) with obj.add(20,30,40). So
it's the compiler who made the decision to call a particular form of polymorphic method at compile time
itself. When the program runs, the binded method is called and prints it's result. Since the decision of
binding the particular form of polymorphic method is happening at compile time, that is why we call it
compile time polymorphism. Compile time polymorphism is also known as static binding, static
polymorphism, compile time binding or early binding.
Why do we call compile time polymophism as early binding?
Since the binding of method that needs to be called is happening at compile time itself rather than at
runtime, that is why we also call it as early binding.
What is Runtime polymorphism or Dynamic binding
In runtime time polymorphism, the call to a polymorphic method is resolved at runtime rather than
compile time. It simply means which particular form of polymorphic method is going to be called get's
resolved at run time rather than compile time, that is why we call it runtime polymorphism. In other
words, in runtime polymorphism, the behavior of an object in a polymorphic method call get's resolved
216 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
at runtime rather than compile time. At runtime it's java virtual machine that decides which particular
form of that polymorphic method is going to be called. Runtime polymorphism can take place only when
there is inheritance. In java child and parent classes can have method with same signature, when an
object calls such methods, the compiler can't decide whether to call parent class method or child class
method, it's jvm which makes the decision.
What is method signature ?
A method signature is part of the method declaration. It's the combination of the method name and the
parameter list. Two methods will be called as of same signature if their names as well as number, type
and order of their parameters are same.
Let's understand the runtime polymorphism with the program given below to make it more clear.
Runtime polymorphism program in Java
class Person {
void teach() {
System.out.println("I can teach ");
}
}
class Teacher extends Person {
void teach() {
System.out.println("I teaches English");
}
public static void main(String [] args) {
Teacher teacher = new Teacher();
teacher.teach();
Person person = new Teacher();
person.teach();
}
}
Output:
I teaches English
I teaches English
Here the behavior teach is in both the classes, Person and Teacher. The teach method of person class
is overridden in Teacher class. In java it is known as method overriding which is an example of runtime
polymorphism. Since the teach method is in both the classes with same signature, therefore the
compiler is unable to bind the method calls with method definition while compiling the
line teacher.teach() and person.teach(). So it's the jvm that needs to decide this at runtime.
At runtime the JVM decides which method is going to be called on the basis of actual type of object,
and then executes that method. Since the binding of polymorphic method happens at runtime, we call
this as runtime polymorphism. Runtime polymorphism is also known as Dynamic
polymophism, Dynamic binding, Runtime binding or Late binding.
Why do we call runtime polymophism as Late binding?
Since the binding of method that needs to be called is happening at runtime not at compile time, that is
why we also call it as late binding.
What is dynamic method dispatch?
217 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at
runtime. It is also referred as runtime polymorphism.
 Constructor overloading is an example of compile time polymophism.
 Method hiding is also an example of compile time polymorphism.
 Java compiler differentiates multiple methods with same name on the basis of number of
parameters or data type of parameters.
What is Method Overloading in Java
Method overloading is one of the important feature in java and is quite used in java programming. It is
quite often asked with java programmers specially with beginners in interviews. This section covers
different details about method overloading along with some questions which will clear your doubts
about method overloading.
What is method overloading
Method overloading is a technique in java which allows java programmers to write two or more than two
methods with same name but different in parameters. It simply means in java a class can have multiple
methods with same name but different in parameters, all such methods are called overloaded methods.
Below code shows an example of method overloading in java :
class Addition {
int add(int a, int b) { }
int add(int a, int b, int c) { }
double add(double a, int b) { }
}
Here add method is an overloaded method since it is more than once. You can see each add method
differs with other add method either in number of parameters or data type of parameters.
Does return type or access modifier of a method plays role in method
overloading ?
No neither return type nor access modifier of a method plays role in method overloading. Compiler will
throw error if you define two methods with same parameters but different return type or access modifier
in your class.
Parameter rules for method overloading in Java
 Each overloaded method must differ with other in one or both the parameter rules given below :
 The number of parameters in both methods are different.
 Data type of parameters in both methods are different.
 So it's only parameter that differentiates one overloaded method with other. Return type or
access modifier of a method does not matter in method overloading.
How I should compare the parameters of methods ?
Compare the parameters of two method in sequential order which means first parameter of first method
with first parameter of second method, second parameter of first method with second parameter of
second method and so on. The overloaded method must differ in one or both rules defined above.
Real time example of method overloading
Many of our real world habits like speak, teach, walk etc are polymorphic or overloaded in nature. For
example when we are happy we speak softly but when we are angry we speak differently. Here the
same behavior speak is different with different inputs(happy and angry).
218 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Similarly when we teach to student of a class we teach professionally but when we teach to a kid at
home we teach differently, so the same action teach has different behavior in different situations or
inputs.Method overloading program in Java
class MethodOverloading {
int add(int a, int b) {
return (a + b);
}
int add(int a, int b, int c) {
return (a + b + c);
}
double add(double a, double b) {
return (a + b);
}
public double add(int a, double b) {
return (a + b);
}
public static void main(String [] args) {
int sum1, sum2;
double sum3, sum4;
MethodOverloading obj = new MethodOverloading();
sum1 = obj.add(20,30);
sum2 = obj.add(20,30,40);
sum3 = obj.add(20.5,30.5);
sum4 = obj.add(20,30.5);

System.out.println("sum1 = "+sum1+" sum2 = "+sum2);


System.out.println("sum3 = "+sum3+" sum4 = "+sum4);
}}
Output:
sum1 = 50 sum2 = 90
sum3 = 51.0 sum4 = 50.5
Here add method has four different versions, all of them differs with each other either or both, in
number of parameters or data type of parameters.
Can we overload main method in java?
Yes you can overload main method any number of times by following the rules described above. At
runtime java virtual machine calls the main method having a single parameter of string array type.
Can we overload constructors as we overload methods?
Yes we can overload constructor as well. Constructor overloading is also a useful concept in java.
Use of method overloading in Java
When it comes to why or what is the use of method overloading in java, following points comes in mind
It allows you to use same name for same task which differs only in parameters. For example in above
program you can use different name for each add method but that won't have been a good practice, as
all of them are doing the same operation which is addition of numbers. It helps in reducing the
219 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
overhead of remembering different method name for same task. If we had used different name for each
method in above program, we needed to remember four names rather one name.
When we should use method overloading
When you observe that you need to add a method in your program which is going to differ only on the
basis of parameters of an existing method, you should use method overloading. In other words if you
need to perform two or more same type of task/operation which differs only in parameters, you should
use method overloading.
Example of method overloading in pre-defined java classes
There are many java classes where method overloading is used, some of the frequently used classes
like String, StringBuffer, StringBuilder etc has many overloaded methods. Methods in String class
like indexOf, lastIndexOf, startsWith, substring, toLowerCase, toUpperCase etc are overloaded
methods.
Advantages of method overloading in Java
 It increases readability and cleanliness of program. Using different name for same behavior or
operation reduces readability and understanding of program.
 It allows you to use common name for two or more than two task which perform same behavior
but slightly differ in parameters.
 It allows you to add new methods with same name in your program, if needed in future.
 It reduces your overhead to remember multiple names than a single name for same type of task.
1. Method overloading is an example of compile time polymorphism in java.
2. Call to overloaded method is bonded at compile time itself.
3. Compiler differentiates one method from other method by checking number of parameters or type of
parameters. It does not consider return type or access modifier of method while differentiating them.
4. Exception in method declaration also not considered while differentiating two overloaded methods.
5. Each overloaded methods can have same or different return types or access modifiers.
6. Both static and non static methods can be overloaded in java.
7. Methods declared with final keyword can also be overloaded in java.
Method Overriding in Java with Example
Method overriding is another important feature in java which is used quite often in java programming. It
is also very often asked with java programmers specially with beginners in interviews. This section
covers different details about method overriding along with some questions which will clear your doubts
about method overriding.
What is method overriding
In java a child class can define methods with same signature as in parent class, if we do so, we call this
as method overriding. Method overriding is a technique in java which allows java programmers to write
methods in child class with same signature as in parent class.
What is method signature?
In a method declaration, the method name along with it's parameter types is known as method
signature. For example in a method declaration public static int add(int a, int b){}, the signature will be
add(int, int). Two methods will be of same signature if their signature exactly matches with each other.
220 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
The parent class method that get's overridden is known as overridden method while the child class
method that overrides the parent class method is known as overriding method. Method overriding can
exist only in parent-child relationship which is in case of inheritance only.
Below code shows an example of method overriding in java :
class A {
int add(int a, int b) { }
int subtract(int a, long b) { }
}
class B extends A {
int add(int c, int d) { } // Overrides parent class method
int subtract(long c, int d) { } // Won't override parent class method
}
Here add method of child class B overrides the add method of parent class A, since both methods have
same signature. Here subtract method is not overridden as the signature of both methods are different,
instead it will be an overloaded method.
subtract(int, long) // Signature of A's class method
subtract(long, int) // Signature of B's class method
What exactly does it mean when a child class method overrides the parent class
method.It simply means the child class method will get preference over the parent class method
when you will call that method using the child class object. Though the parent class method was
inherited in child class but as it was overridden in child class, the JVM gives preference to child class
method over the parent class method.
Method overriding rules in Java
There must be parent child relationship which means inheritance must be there.
The signature of parent and child class methods must be same.
If return type of parent class method is a primitive type, then child class method must also have the
same return type. For example if return type of parent class method is int, then child class method's
return type must also be int. Using any other return type would result in compilation error.
If return type of parent class method is a non primitive type then a covariant return type can also be
used in child class method from java 5. The access modifier of child class method should not be more
restrictive. It should be same or more accessible modifier. For example if parent class method has
default modifier, then child class can have default, protected or public modifier. Using more restrictive
modifier would result in compilation error.
Can we override every method of parent class ?
No, private, static and final methods of parent class can not be overridden in child class.
Real time example of method overriding in Java
We can take parent child relationship as an example of inheritance. Many of the real world habits of a
parent child can be overridden in nature. For example, a parent child can have a common
behavior singing, where in the singing behavior of a child may be different than his parent. One may be
classical singer while other is a rock singer. Similarly there can be other behaviors as well like dance,
speak, teach etc where parent and child can have different approach of doing the same behavior. The
same can be applicable for other type of species or things as well.
Method overriding program in Java
class Person {
221 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
void teach() {
System.out.println("I can teach");
}
}
class Teacher extends Person {
void teach() {
System.out.println("I teaches English");
}
public static void main(String [] args) {
Teacher teacher = new Teacher();
teacher.teach();
Person person = new Teacher();
person.teach();
Person person2 = new Person();
person2.teach();
}
}
Output:
I teaches English
I teaches English
I can teach
Here the teach method is in both the classes, Person and Teacher. The teach method of person class
is overridden in Teacher class. Let's see the sample code below to make it more clear :
class A {
int add(int a, int b) { }
int add2(int a, int b) { }
int add3(int a, int b) { }
int add4(int a, int b) { }
int add5(int a, int b) { }
}
class B extends A {
int add(int c, int d) { } // It will override parent class method.
long add2(int c, int d) { } // It won't compile, return type must be same.
private int add3(int c, int d) { } // won't compile, can not reduce access modifier
int add4(int c, int d, int e) { } // won't override, will act as an overloaded method
int add5(int c, float d) { } // won't override, will act as an overloaded method
}
How does JVM decides which method to call at run time
The JVM checks the actual type of the object which is calling the method, then on that actual type it
calls the corresponding method. The actual type of an object is the type which is used
with new keyword. For example when you create the object as new Teacher(), it's actual type will be
of Teacher type, so it will call the Teacher class method, no matter whether this object was assigned
into Teacher class type or Person class type.
Teacher teacher = new Teacher(); // Actual type is Teacher
Person person = new Teacher(); // Actual type is Teacher
222 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Person person2 = new Person(); // Actual type is Person
Use of method overriding in Java
The main reason to use method overriding is to change/modify the behavior of parent class method as
per the requirement in child class. Now you may think that why not to change the parent class method
itself ?, the reason is, that parent class may have been inherited by many other classes as well. If you
modify the method of parent class, that will be reflected in all the subclasses whether they need that
change or not, which may affect the functionality of your project, so it's not a good practice at
all.Method overriding is used to achieve run time polymorphism in java which is an essential concept of
object oriented programming.
When we should use method overriding
When you find that the parent class method is not full-filling the child class requirement, in other words
when you have a need to change/modify the behavior of an existing method of parent class inside child
class, you should use method overriding. Many times in real world projects when we create a more
specific class from a generic class, we need to use method overriding to change the behavior of
generic class method. For example let's suppose you have an Animal class having a method as sound,
now if you create classes like Dog and Cat from Animal class, you would be needed to change/override
the behavior of sound method in Dog and Cat classes since a dog barks whereas a cat meows.
Example of method overriding in pre-defined java classes
There are many java classes where method overriding is used, some of the frequently used classes
like StringBuffer, StringBuilder, ArrayList, HashMap etc has many overridden methods.
The StringBuilder class has override many methods of AbstractStringBuilder class like append(String
str), substring(int start), indexOf(String str) etc.
Advantages of method overriding in Java
 The main advantages of using method overriding is that it gives child class the ability to change
the behavior of parent class method as per the requirement. Child classes can re-define the
method which is suitable or specific to them.
 Another advantage of overriding is that it provides multiple implementation of same method, one
can call parent or child class method as per the need.
 It gives you ability to achieve run time polymorphism which is an essential concept of OOPS.
★★★
1. Method overriding is an example of run time polymorphism in java.
2. Call to overridden method is resolved at run time not at compile time.
3. Only the instance methods can be overridden in Java.
4. Instance variables can not be overridden in child class.
5. We can not override main method as it is a static method.
6. Overriding method cannot throw any checked exception if parent class doesn't throws any
exception.
Difference between method overloading and method overriding in Java
This is quite often asked question with beginners in interviews. Before you start this section
refer method overloading and method overriding first if you don't know what they are. Let's see the
differences one by one.
By Definition: When a class defines two or more than two methods with same name but different in
parameters, we call it method overloading while when a subclass defines a method with same name
223 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
and same in parameters(number and type of parameters) as in parent class, we call it method
overriding.
// Example of method overloading, add method is overloaded
class A {
int add(int a, int b) { ... }
int add(int a, int b, int c) { ... }
double add(double a, int b) { ... }
}
// Example of method overriding, add method is overridden
class A {
int add(int a, int b) { ... }
}
class B extends A {
int add(int c, int d) { ... }
}
Class: Method overloading generally happens in same class while method overriding happens in two
classes related using inheritance. In method overriding the subclass overrides the method of super
class.
Parameter: In method overloading, each method must be different with other overloaded method
either in number of parameters or type of parameters while in method overriding both(parent and child
class) method must have same number or type of parameters. In other words, in method overloading
method signature of each overloaded method must be different than other while in overriding the
signature of both methods must be same.
Return type: Return type of a method doesn't play any role in method overloading but in method
overriding, if the return type of parent class method is a primitive type, then the overriding method must
also have same return type. If the return type of parent class method is non-primitive type then child
class can use same non-primitive type or covariant return type(from java 1.5 onwards) as well to
override the method.
What is covariant return type?
If parent class method returns a non primitive type, then the overriding method in child class can return
the same non primitive type or any of the subclasses of that non primitive type. All those subtypes
would be called as covariant return type.
class A {
int add(int a, int b) { ... }
A getObj() { ... }
}
class B extends A {
long add(int a, int b) { ... } // compilation error, return type must be int
A getObj() { ... } // Valid override
// OR
B getObj() { ... } // Valid override, covariant return type
}
Access modifier: Access modifier also doesn't plays any role in method overloading but in method
overriding, the subclass method should have either same access modifier or a more accessible
224 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
modifier than parent class method. The child class method should not be more restrictive, doing so will
result in compilation error.
class A {
void print(String s) { ... }
}
class B extends A {
private void print(String s) { .. } // compilation error, can't use more restrictive modifier
// OR
protected void print(String s) { ... } // valid override
// OR
public void print(String s) { ... } // valid override
}
Private, final and static method : The private, final and static methods in a class can be overloaded in
java but they can not be overridden. Subclasses can not override such methods of parent class.
class A {
private int add(int a, int b) { ... }
int print(int a, int b, int c) { ... } // valid overload
final void print(String s) { ... }
void print(String s, String t) { ... } // valid overload
}
throws clause : In method overloading, each overloaded method can throw any exception. In case of
method overriding, if parent class method doesn't throws any exception child class method can not
throw any checked exception. If parent class method throws any unchecked or runtime exception then
the child class method can throw only unchecked or runtime exception or overriding method can ignore
to declare any exception. If parent class method throws any checked or compile time exception then
the child class method can throw the same exception or a subclass of that exception. It can not throw a
superclass of parent class method exception. The subclass method can throw any unchecked or
runtime exception.
class A {
void print() { }
void message() throws NullPointerException { } // Unchecked Exception
void run() throws IOException { } // Checked Exception
}
class B extends A {
void print() throws IOException { } // compilation error, can't throw checked exception
void message() throws IOException { } // compilation error, can't throw checked exception
void message() throws NullPointerException { } // valid override
void run() throws Exception { } // compilation error, Exception is not subclass of
IOException
void run() throws IOException { } // valid override
}
Method Resolution: Method resolution is a technique in which the compiler/jvm decides which
particular form of an overloaded/overridden method will be called when the program will run. In method
overloading, this resolution happens at compile time by the compiler itself while in method overriding
the resolution happens at runtime by JVM.
225 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Polymorphism: Method overloading is an example of compile time polymorphism or static binding
or early binding while method overriding is an example of runtime polymorphism or dynamic binding or
late binding.
METHOD OVERLOADING VS METHOD OVERRIDING IN TABULAR FORMAT
METHOD OVERLOADING METHOD OVERRIDING
If a class defines two or more than two
If a subclass defines a method with
methods with same name but different
By Definition same signature as in parent class, we
in parameters, we call it method
call it method overriding.
overloading.
One method should be in parent class
Class Generally happens in same class.
while other should be in child class.
Each overloaded method must be
Both method must have same number
Parameter different in number or type of
and type of parameters in same order.
parameters from other.
Must be the same if it is primitive type, if
Return type of a method doesn't play it's a non-primitive type then a covariant
Return Type
any role in method overloading. return type can be used from java 1.5
onwards.
Subclass method must have same or
Access modifier of a method doesn't
Access modifier more accessible modifier than the
plays any role in method overloading.
parent class method.
private, final and
Such methods can also be overloaded. Such methods can not be overridden.
static method
If parent class doesn't throws any
exception, then child class can not
Each overloaded method can declare to
throws clause throw any checked exception. Refer
throw any exception.
throws clause section given above for
more details.
Method It's the compiler that resolves method It's jvm that resolves the method call at
Resolution call at compile time itself. runtime.
It is an example of compile time It is an example of run time
Polymorphism
polymorphism. polymorphism.

Covariant return type & Overriding using covariant type in Java


This section explains about covariant return type in java and how we can override a method using
covariant return type.
What is Covariant return type in Java
If type(class) B can be used as a return type while overriding a method whose return type is A, then we
call type B as a covariant type of type A. In java this is possible only when type B is a subclass of type
226 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
A. So we can say all subtypes of a type are covariant type of that type. Covariant return type is
applicable for non primitive types only.
Method overriding using covariant return type in Java
If a method in a class returns a non primitive type, then the same method in a subclass of that class
can use the same non primitive type or a subclasses of that non primitive type as the return type to
override that method. Let's understand this by an example. In java we have a class Integer which
extends a class Number which implicitly extends Object class, so the inheritance structure looks like
below.

If a class A has a method whose return type is an Object type, then the same method in a child class
B(child of class A) can use Number or Integer as return type to override that method
because Number and Integer class are covariant of Object class. Let's see this by the program given
below :
Can we override a method which returns Object type with any non
primitive type?
Yes we can, since Object class is superclass of every class in java.
Java program of method overriding using covariant return type
class A {
Object print() {
System.out.println("print method of class A");
return new Object();
}
}
class B extends A {
Integer print() {
System.out.println("print method of class B");
return new Integer(2);
}
public static void main(String [] args) {
B b = new B();
b.print();
A a = new B();
a.print();
}
227 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
Output:
print method of class B
print method of class B
As you can observe from the output, the print method in class B is overriding the print method of parent
class A though the return type of child class method is Integer type It's happening because java allows
to use covariant return type while overriding the method.
Let's see one more program to understand it more clearly.
class A { }
class B extends A { }
class C extends A { }
class D {
public A print() {
System.out.println("print method of class D");
return new A();
}
public A message() {
System.out.println("message method of class D");
return new A();
}
}
class E extends D {
public B print() {
System.out.println("print method of class E");
return new B();
}
public C message() {
System.out.println("message method of class E");
return new C();
}
public static void main(String [] args) {
E e = new E();
e.print();
D d = new E();
d.message();
}
}
Output:
print method of class E
message method of class E
Here you can see the return type of print and message method of class D is A and we are able to
override these methods in class E just by changing the return type as subclasses of class A. It's just
because class B and class C are covariant type of class A since both are it's subtypes.
Rules of overriding a method using covariant return type
228 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 The covariant return type is applicable only for non primitive or object types, not for primitive
types.
 The return type of overriding method in child class can not be a return type which is parent of
superclass method's return type. Doing so will result in compilation error.
 The overriding method's return type in child class should be either the same as the parent class
method's return type or a subclass of that type.
Advantages of covariant return type in Java
It gives you freedom to return more specific return type while overriding the method which may
eliminates unnecessary downcasting from the super type to the subtype. For example clone method of
Object class can be overriden by implementing Clonable interface and the implementing class can
return the object of its own type which will always be better than returning Object type.
It helps us in preventing runtime ClassCastException.
Java this keyword with Examples & Uses
This section explains about this keyword in java which is quite used in java programs. The section
explains different details of this keyword like what this keyword is, use of this keyword in method
and constructor, java programs of this keyword etc.
What is this keyword in Java
In java, this is a keyword which holds the reference of the current object - the object whose method or
constructor is being called. In other words, this keyword refers/holds the reference of the same object
which invoked the method or constructor. As we know, in java an instance method or constructor is
called by an object, we use this keyword to refer the same object inside that method or constructor.
Using this keyword we can access the members of that object inside the method or constructor. The
keyword this is a reference variable of non static type, it can be used inside instance method,
constructor or block only. Like other non static members, it can not be used inside static method or
static block, doing so will result in compilation error. The syntax of using this keyword is :
this.name // To access the name instance variable of current object
this.printDetail() // To call the printDetail method of current object
this(String name) // To call string parameterized constructor for current object
this keyword program in Java
class Person {
String name;
int age;
public Person(String n, int a) {
this.name = n;
this.age = a;
}
void printDetail() {
System.out.println("Reference of this keyword = "+this);
System.out.println("Detail using this keyword, name = "+this.name+" age = "+this.age);
}
public static void main(String [] args) {
Person person = new Person("Rahul", 20);
person.printDetail();
229 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
System.out.println("Reference of person object = "+person);
System.out.println("Detail using object, name = "+person.name+" age = "+person.age);

Person person2 = new Person("Pradeep", 22);


person2.printDetail();
System.out.println("Detail using object2, name = "+person2.name+" age =
"+person2.age);
System.out.println("Reference of person2 object = "+person2);
}
}
Output:
Reference of this keyword = Person@15db9742
Detail using this keyword, name = Rahul age = 20
Reference of person object = Person@15db9742
Detail using object, name = Rahul age = 20
Reference of this = Person@6d06d69c
Detail using this keyword, name = Pradeep age = 22
Detail using object2, name = Pradeep age = 22
Reference of person2 object = Person@6d06d69c
Notice the reference of object and this keyword, both are same which means this keyword refers the
same object which invokes the method. Using this keyword you can refer the properties of that object,
as you can see we are able to access name and age property of the object which invoked the method.
Let's understand it by the code given above. When code line Person person = new Person("Rahul",
20) get's executed, the constructor get's called, so inside the constructor this keyword will refer
the person object as it invoked the constructor. Similarly when code line person.printDetail() calls
the printDetial method, inside the method this keyword will point to person object as it's the one which
called the method.
Is it possible to assign reference to this?
No, doing(this = objName) so will result in compilation error.
Use of this keyword in method and constructor
One of the very common use of this keyword inside method or constructor is to access the properties of
the object which invoked it. We can also invoke a method or constructor using this keyword in java.
Another good use of this keyword is to resolve instance variable and parameter name
conflict/ambiguity. If an instance variable name and parameter name is same, this keyword can be
used to refer the instance variable inside the method or constructor to avoid the name
conflict/ambiguity.
Java program of this keyword uses inside method and constructor
class Employee {
String name, address;
int age;
public Employee(String name, int age) {
this(name, age, "NA"); // calling constructor
}
public Employee(String name, int age, String address) {
230 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
// this.name refers name instance variable while using only
//name refers name parameter, this way we resolve name conflict.
this.name = name;
this.age = age;
this.address = address;
}
void printDetail() {
System.out.println("Name = "+this.name+", age = "+this.age);
System.out.println("Address = "+this.address);
this.checkVoterEligibility(this.age); // calling method using this keyword
}
void checkVoterEligibility(int age) {
if(age > 18) { System.out.println("You are eligible for vote"); }
else { System.out.println("You are not eligible for vote"); }
}
public static void main(String [] args) {
Employee employee = new Employee("Rahul", 20);
employee.printDetail();
Employee employee2 = new Employee("Pradeep", 22, "xyz");
employee2.printDetail();
}
}
Output:
Name = Rahul, age = 20
Address = NA
You are eligible for vote
Name = Pradeep, age = 22
Address = xyz
You are eligible for vote
Can we call method using this keyword inside constructor?
Yes, we can call the method from inside constructor, just use this.methodName().
Can we use this keyword to access static method or variable?
Yes we can, but accessing static members using this keyword is not a good programming style.
Note : In java, when we call an instance method or variable without any object, java compiler internally
adds this keyword for invoking that method or variable as shown in the program below :
class Test {
String name;
void m1() {
n1();
System.out.println("Name = "+name);
}
void n1() { }
public static void main(String [] args) {
Test test = new Test();
test.m1();
231 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
}
// While compiling above class, the compiler will add this keyword inside m1 method like below
void m1() {
this.n1();
System.out.println("Name = "+this.name);
}
Different Uses of this keyword in Java
 The most common use of this keyword is to access the instance properties/variable of object
which invokes the method or constructor.
 If there is ambiguity between instance variables and parameters name, this keyword can be
used to resolve the ambiguity inside the method/constructor.
 We can use this keyword to call constructor inside another constructor. If calling a constructor
inside another constructor, then constructor call must be the first statement inside the calling
constructor.
 It can be used to call a method from inside a method or constructor.
 It can be passed as an argument inside a method call.
 It can be used to return current object from a method.
How this keyword is different from normal reference variable
 We can not assign any reference(object) to this explicitly while a normal reference variable can
refer to any other reference variable of same type.
 A normal reference variable can be created directly inside a class but this keyword can not be
used outside of method, constructor or block.
 We can not use this keyword inside static block or method but we can create normal reference
variable inside static block/method.
Java super keyword with Examples & Uses
This section explains about super keyword in java which is quite used in java programs. It covers
details like what super keyword is, uses of super keyword, difference
between this and super keyword etc. Before you start this section, you should have knowledge about
inheritance in java, if not then refer inheritance in java section first.
What is super keyword in Java
In java, super is a keyword which is used by subclasses to access the instance variable, method and
constructor of immediate superclass. The keyword super itself suggests that it's a reference variable of
superclass. It is similar as this keyword except that it is used by subclasses to access the superclass
members.
What is immediate superclass?
If class C extends class B, class B extends class A, then for class C immediate superclass will be class
B and for class B immediate superclass will be class A.
The keyword super can be used only inside instance method, constructor and block of subclass. Like
other non static members, it can not be used inside static method or static block, doing so will result in
compilation error. The syntax of using super keyword is :
super.name // To access the name instance variable of parent class
super.printDetail() // To call the printDetail method of parent class
232 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
super() // To call no-argument constructor of parent class
Using super keyword does not create an object of superclass, rather the current object is viewed as an
instance of the superclass of current class. Using super keyword in subclass is same as
using this keyword inside superclass.
Can we access private members of superclass inside subclass using super
keyword? No, using super keyword we can access only those method, constructor or variable of
superclass inside subclass which is accessible as per access modifier. Private members are accessible
only within class, not outside the class.
Super keyword program in Java
class A {
String str = "Class A string variable";
void message() {
System.out.println("Inside class A");
}
}
class B extends A {
String str = "Class B string variable";
void print() {
super.message();
System.out.println(super.str);
System.out.println(this.str);
}
public static void main(String [] args) {
B obj = new B();
obj.print();
}
}
Output:
Inside class A
Class A string variable
Class B string variable
Is it possible to assign reference to super keyword?
No, doing(super = someObjName) so will result in compilation error.
Different uses of super keyword in Java
 The super keyword is used to access superclass instance variable, method and constructor
inside subclass instance method constructor or block. To list down some of use cases :
 If a subclass has an instance variable with same name as superclass variable,
then super keyword can be used to access the superclass variable inside subclass.
 If subclass has overridden any superclass method, then super keyword can be used to access
the overridden method of superclass inside subclass.
 The subclass constructors can call superclass constructor using super keyword. If a subclass
constructor needs to call superclass constructor, then superclass constructor call must be the
first statement inside the subclass constructor.
233 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
 We can also call any normal instance method(not overridden) or variable of superclass
using super keyword.
Java program of super keyword uses inside method and constructor
class Person {
String name;
String msg;
public Person(String name, String msg) {
this.name = name;
this.msg = msg;
}
void message() {
System.out.println("Inside message method of Person class");
}
}
class Employee extends Person {
String msg;
int empId;
public Employee(String name, int id) {
super(name,"Variable of Person class"); // Superclass constructor call must be first statement
this.empId = id;
this.msg = "Variable of Employee class";
}
void printDetail() {
System.out.println("Name = "+this.name+", empId = "+this.empId);
super.message();
this.message();
System.out.println(super.msg);
System.out.println(this.msg);
}
void message() {
System.out.println("Inside message method of Employee class");
}
public static void main(String [] args) {
Employee emp = new Employee("Rahul", 20);
emp.printDetail();
}
}
Output:
Name = Rahul, empId = 20
Inside message method of Person class
Inside message method of Employee class
Variable of Person class
Variable of Employee class
234 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Note : We can not use super and this keyword together for calling constructor inside a subclass
constructor. For example using super() and this() inside a subclass constructor will result in compilation
error.
Can we use super keyword to access static method or variable? Yes we can, but
accessing static members using super keyword is not a good programming style.
Can we use super keyword in a class which doesn't extend any other class? Yes we
can, since in java every class internally extends Object class if it doesn't extend any other class.
Does java implicitly invokes superclass no-arg constructor?Yes if a subclass constructor
does not explicitly invoke a superclass constructor or another subclass constructor, the java compiler
implicitly inserts a call to the no-argument constructor of the superclass. In this case if the superclass
does not have a no-argument constructor, you will get a compile-time error.
class A {
public A() {
System.out.println("Class A constructor");
}
}
class B extends A {
public B() {
System.out.println("Class B constructor");
}
public static void main(String [] args) {
B ob = new B();
}
}
Output:
Class A constructor
Class B constructor
Here the object creation of subclass using new keyword invokes it's constructor which implicitly invokes
the superclass constructor as well. After compilation the subclass constructor would be something like
this :
public B() {
super(); Compiler implicitly inserts call to the no-argument constructor of superclass
System.out.println("Class B constructor");
}
How super keyword is different from normal reference variable
 We can not assign any reference(object) to super keyword explicitly while a normal reference
variable can refer to any other reference variable of same type.
 A normal reference variable can be created directly inside a class but super keyword can not be
used outside of instance method, constructor or block.
 We can not use super keyword inside static block or method but we can create normal reference
variable inside static block/method and then we can use that reference variable.
 The keyword super does not create a new object, instead the current object is viewed as an
instance of superclass. While a normal object must be created first before it can be used.
235 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
Should I prefer to use super keyword over normal object of superclass in
subclasses?
Yes you should prefer to use super keyword rather than creating an object of superclass to access
superclass members. Creating a normal object takes extra space in memory.
Difference between this and super keyword in java
 The keyword this is used to refer current class object while super keyword is used to refer
current object but viewed as an instance of the superclass of the current class.
 The keyword this is used to access instance variables, methods and constructor of current class
while super keyword is used to access instance variables, methods and constructors of
superclass.
 If subclass needs to call parent class constructor using super keyword explicitly, then calling
superclass constructor must be the first statement inside the subclass constructor.
 To invoke an overridden method of superclass inside a subclass we use super keyword while to
invoke overriding method we use this keyword or normal object of subclass.
 Using this keyword you can call any method of current class but super keyword can call only
those methods which are accessible as per access modifiers in subclass.
★★★
1. The super keyword can not be passed as an argument inside a method call.
2. The super keyword can not be used to return superclass object from a method.
3. We can not do super.super in java programs, doing so will result in compilation error.
4. Parent class constructor is always called before the child class constructor. This is also called
constructor chaining.
5. As superclass constructors are not inherited in subclass, so the only way to call superclass
constructor in subclasses is to use super keyword.
What is final keyword in Java
In java final is a keyword which is quite used in java programs. In real life when we say something is
final, it means we can not change that later, the same applies with final keyword in java as well. When
a member in java is declared as final, it's value or definition can not be changed later. Let's see
different uses and examples of final keyword in java.
What is the use of final keyword in Java
The final keyword is used to make a member as final. Once a member is declared as final, it's definition
or value can not be changed later. In java final keyword can be used with following members :
Variable - Value of final variable can not be changed once initialized.
Method - Final method can not be overridden.
Class - Final classes can not be inherited.
What is final variable in Java
A variable declared with final keyword is known as final variable. Once a final variable is initialized with
some value, we can not change it's values later in the program, that is what the final keyword do when
used with variable.
The syntax of declaring final variable is :
final data_type var_name = value;
Ex.
final int total_hours = 24;
236 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
final double PI = 3.141592653589793;
// Value can be assigned in constructor as well
Note : final keyword must be used before the data type of variable.
Java program using final keyword
class FinalVariableProgram {
static final double PI = 3.141592653589793;
public static void main(String [] args) {
// Doing this below will result in compilation error
// PI = 3.14;
FinalVariableProgram fvp = new FinalVariableProgram();
System.out.println("Value of PI = "+fvp.PI); ;
final int total_hours = 24;
// Doing this below will result in compilation error
// total_hours = 20;
System.out.println("Total hour in a day = "+total_hours);
}
}
Output:
Value of PI = 3.141592653589793
Total hour in a day = 24

The final keyword can be used with all variable types, local, instance and static variables. It does the
same thing with all variable types. Once you assigned some value to a final variable, you can not re-
assign some other value later. Reference(Non primitive type) variable in java can also be declared
as final. Once such variables are assigned some reference, they can not refer to any other object later
in the program. Remember the object that is assigned to a final reference variable can change it's own
properties or behavior. It's own properties and behavior won't be final. A final variable which is created
inside method, constructor or block is known as local final variable. These variables must be initialized
only once, after that you can not change it's value later in the program.
What is the difference between normal variable and final variable in Java?
The only difference is that incase of normal variable we can re-assign new value any number of times
while incase of final variable we can not re-assign after once. Value of final variable is assigned only
once.
Initializing final variable in Java
The most common way is to initialize the value of final variable while declaring it. If it is not initialized
we call it blank final variable, which must be initialized using either of below approaches. An
instance final variable can be assigned value in instance initializer block or in constructor. If the class
contains more than one constructor, then it must be initialized in all of the constructor otherwise
compiler will throw error. A static final variable can be initialized inside static block.
Program below demonstrates different ways of initializing final variable in java.
class FinalVariableInitialization {
final int maxValue = 100;
final int minValue;
final int totalValue;
237 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
static final double PI;
// Initializing static final variable in static block
static {
PI = 3.141592653589793;
}
// Initializing instance final variable in instance block
{
totalValue = 150;
}
// Initializing instance final variable in constructor
public FinalVariableInitialization() {
minValue = 50;
}
public static void main(String [] args) {
FinalVariableInitialization ob = new FinalVariableInitialization();
System.out.println("maxValue = "+ob.maxValue+", minValue = "+ob.minValue);
System.out.println("totalValue = "+ob.totalValue+", PI = "+PI);
}
}
Output:
maxValue = 100, minValue = 50
totalValue = 150, PI = 3.141592653589793
What is final method in Java
A method declared with final keyword is known as final method. Once a method is declared as final, it
can not be overridden in subclasses, hence you won't be able to change the definition of that method in
subclasses, that is what the purpose of final keyword is, it doesn't allow subclasses to change/modify
the definition of that method. As we know that in java a subclass inherits the method of parent class
and modifies the definition of that method if needed. In order to stop this we can use final keyword with
method declaration which stops the subclasses to override that method.
The syntax of declaring final method is :
final return_type methodName() { ... }
Ex.
final void print() { ... }
Note : final keyword must be used before the return type of method.
Program in java using final method
class A {
final void print() {
System.out.println("Printing from class A");
}
}
class B extends A {
// Below code will result in compilation error
void print() {
System.out.println("Printing from class B");
238 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
}
public static void main(String [] args) {
System.out.println("Trying to override final method of class A");
}
}
Above program won't compile as subclass B is trying to override the final method of parent class A. If
you remove the print method from class B, the program will compile and execute successfully. The
compilation error will look something like below :
Output:
B.java:8: error: print() in B cannot override print() in A
void print() {
^
overridden method is final
1 error
Can we use final keyword with static methods as well? Yes we can use. The
subclasses won't be able to hide such methods of parent class. We can use final keyword with main
method as well.
Can we overload final method in java?Yes, final method in java can be overloaded.
Can we call final method of a class in subclasses? Yes we can, that will not give
any issue.
What is final class in Java
A class declared with final keyword is known as final class. Once a class is declared as final, it can not
be inherited, hence you won't be able to override/hide any of it's variable or method. That is what the
purpose of final keyword is, it makes the class definition as final.
In other words if you don't want to allow your class to be inherited by other classes, declare your class
using final keyword.
The syntax of declaring final class is :
final class className { ... }
Ex.
final class MyClass { ... }
Note : final keyword must be used before class keyword.
final class program in java
final class A {
void print() {
System.out.println("Hello form class A");
}
}
class B extends A {
public static void main(String [] args) {
System.out.println("Hello form class B");
}
}
Above program won't compile as the class B is trying to inherit the class A which is declared as final.
Classes declared with final keyword can not be inherited at all.
239 JAVA PROGRAMMING by Mr. Bulega Herbert Moses 0782996265 [email protected]
What is the use of final class in Java
It stops other classes to inherit the class, So whatever you have defined, that will be final.
To create an immutable class in java you should declare your class as final. Many predefined java
classes like String, StringBuffer, StringBuilder etc are final classes.
It enhances the security of your class, as it cannot be extended/modified by other classes.
When to use final keyword in Java
For variables, if you know that the value of the variable don't need be changed throughout the program,
declare that variable as final variable. In other words for constant values you should use final variable,
for example PI.
Similarly for methods, if you don't want your methods to be overridden/modified by subclasses, declare
them as final methods. For classes, if you don't want your class to be inherited/modified by any other
classes, declare them as final classes.
★★★
1. Constructors or blocks can not be declared as final.
2. final is not an access modifier
3. We can create the object of final class but can not extend it.
4. We can also declare the parameter of a method as final.
5. We can not initialize instance final variable inside method.
6. Generally constants are declared as final variable, the good practice is to name these variables
in uppercase letter.

You might also like