Full Java Notes
Full Java Notes
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.
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.
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");
}
}
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.
●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.
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.
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.
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.
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
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.
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.
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]
Use Used for local computations Used when value of Generally used for
variable must be declaring constants
referenced by more
than one method
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.
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
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);
}
}
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,
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.
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);
}
}
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.
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
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
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 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.
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]
Bitwise
exclusive OR
^ a^b
Bitwise inclusive
| a|b
OR
Logical OR || a||b
Ternary ? : a = a>2 ? a : b
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 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]
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.
●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.
●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
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");
}
}
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
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.
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.
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);
}
}
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.
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
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.
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.
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.
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)
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]
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.
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.
}
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]
}
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.
class StaticVarDemo {
static String test = "Testing static variable";
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.
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.
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]
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.
}
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.
class StaticMethodDemo {
int count = 20;
static String test = "Learning static method";
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.
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;
----------------------------------------
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
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 {
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.
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.
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.
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.
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.
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.
/**
* 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
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
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.
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");
}
}
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.
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);
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]
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]
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);
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.