Java Programming 2025 New
Java Programming 2025 New
Course content:
1
Chapter 1: Java fundamental
1- Java overview
2- Java Terminology
Before we start learning Java, let’s get familiar with common java terms.
This is generally referred as JVM. Before, we discuss about JVM let’s see the phases of program
execution. Phases are as follows: we write the program, then we compile the program and at last we
run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included
2
in java development kit (JDK). It takes java program as input and generates java bytecode as
output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run
phase.
So, now that we understood that the primary function of JVM is to execute the bytecode produced
by compiler. Each operating system has different JVM, however the output they produce
after execution of bytecode is same across all operating systems. That is why we call java as
platform independent language.
b- Bytecode
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it
can be executed by JVM. The bytecode is saved in a .class file by compiler.
c- Java Development Kit (JDK)
As the name suggests this is complete java development kit that includes JRE (Java Runtime
Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer.
d- Java Runtime Environment (JRE)
JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system,
you can run a java program however you won’t be able to compile it. JRE includes JVM, browser plugins
and applets support. When you only need to run a java program on your computer, you would only need
JRE
e- Applet
An applet is a dynamic and interactive program that can run inside a Web page displayed
by a Java-capable browser
Compiler (javac) converts source code (.java file) to the byte code(.class file). As mentioned above,
JVM executes the bytecode produced by compiler. This byte code can run on any platform such as
Windows, Linux, and Mac OS etc. Which means a program that is compiled on windows can run on Linux
and vice-versa? Each operating system has different JVM; however the output they produce after
execution of bytecode is same across all operating systems. That is why we call java as platform
3
independent language.
b. Portable
As discussed above, java code that is written on one machine can run on many other machine (). The
platform independent byte code can be carried to any platform for execution that makes java code portable
Object oriented programming (OOP) is a way of organizing programs as collection of objects, each of
which represents an instance of a class.
The four (4) main concepts of Object Oriented programming are:
- Encapsulation (which is binding together the data and the functions that manipulates them)
example in real life situation: in a company there are different sections like the account
section, finance section….etc and each section keeps record and data related to his section)
- Abstraction or Data hiding (which is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user)
- Inheritance (which is capability of a class to derive properties and characteristics from
another class.)
- Polymorphism (which means having many forms. In simple word it is as the ability of a
message to be displayed in more than one form). An example in real life situation is that a
man can have different characteristic (a man can be a father, husband, employee…etc.)
d. Simple
Java is considered as one of simple language because it does not have complex features like Operator
overloading, multiple inheritance, pointers and explicit memory allocation.
e. Robust language
Java programming language is developed in a way that puts a lot of emphasis on early checking for
possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other
programming languages. The main features of java that makes it robust are garbage collection (which
is the process of looking at heap memory, identifying which objects are in use and which are not and
deleting the unused object), Exception Handling and memory allocation
f. Secure
We don’t have pointers and we cannot access out of bound arrays in java. That’s why several security
flaws like stack corruption or buffer overflow is impossible to exploit in Java.
4
g. Distributed
Using java programming language we can create distributed applications. RMI(Remote Method
Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In
simple words: The java programs can be distributed on more than one systems that are connected to each
other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a
remote JVM.
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU.
Basically a computer language is either compiled or interpreted. Java comes together both these approach
thus making Java a two-stage system.
Java compiler translates Java code to Bytecode instructions and Java Interpreter generate machine code
that can be directly executed by machine that is running the Java program.
JRE: JRE(Java Runtime Environment) is the environment within which the java virtual machine runs.
JRE contains Java virtual Machine (JVM), class libraries, and other files excluding development tools
such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.
5
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as
compiler, debugger etc.
6
JAVA C++
Java is true Object oriented language. C++ is basically C with Object-oriented extension
Java does not support operator overloading C++ supports operator overloading
Java compiled into byte code for the Java Source code can be written to be platform
Virtual Machine. The source code is independent and written to take advantage of
independent on operating system. platform. C++ typically compiled into machine
code.
Java does not support multiple inheritances of
C++ supports multiple inheritances of classes.
classes but it supports interface.
Does not use pointers use pointers
Java does not support global variable. Every
C++ support global variable.
variable should declare in class.
It Strictly enforces an object oriented It Allows both procedural programming and object
programming paradigm. oriented programming.
There are no header files in Java. We have to use header file in C++.
7
Chapter 2: Local environmental setup and first java program
As usual before doing any sort of Java programming, we must first prepare our development machine
(computer). In this chapter we will explain how to do this.
2.1- Requirements
Before starting programming in java, we need:
➢ Java Development Kit (JDK.)
➢ Text editor or IDE (NetBeans or Eclipse)
2.2- Installation and configuration of JDK
2.2-1. Installation
Download the latest version of Java development kits and install it in your computer by double clicking
on the Setup file and follow the instructions.
The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not required to be set
because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path of JDK.
➢ Temporary
➢ Permanent
a- Process of Setting Temporary the path
To set the temporary path of JDK, you need to follow the following steps:
8
For setting the permanent path of JDK, you need to follow these steps:
• Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user
variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok ->
ok
As in the previous programming language that we have learned, we have two possibility of software that
we can use to start programming with java.
Possibility 1: Download and install a text editor in your computer or just choose one on the
existing one
Possibility 2: Download and install a java support programming software such as ECLIPSE or
NETBEANS
2.4- Simple java program
In this part, we will see how to write, compile and run a java program. I will also cover java syntax, code
conventions and several ways to run a java program.
Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the above program and
paste it in the text editor.
You can also use IDE like Eclipse or Netbeans to run the java program but we will cover that part later in
the coming tutorials. For the sake of simplicity, I will only use text editor and command prompt (or
terminal) for this tutorial
Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have named the file as
FirstJavaProgram, the thing is that we should always name the file same as the public class name. In our
program, the public class name is FirstJavaProgram, that’s why our file name should be
FirstJavaProgram.java.
9
Step 3: In this step, we will compile the program. For this, open command prompt (cmd).
To compile the program, type the following command and hit enter.
javac FirstJavaProgram.java
You may get this error when you try to compile the program: “javac’ is not recognized as an internal or
external command, operable program or batch file“. This error occurs when the java path is not set in
your system. If you get this error then you first need to set the path before compilation.
Step 4: After compilation the .java file gets translated into the .class file (Bytecode). Now we can run the
program. To run the program, type the following command and hit enter:
java FirstJavaProgram
Note that you should not append the .java extension to the file name while running the program.
Now that we have understood how to run a java program, let have a closer look at the program we have
written above.
This is the first line of our java program. Every java application must have at least one class definition that
consists of class keyword followed by class name.
When I say keyword, it means that it should not be changed; we should use it as it is. However the class
name can be anything.
This is our next line in the program, let’s break it down to understand it:
public: It is an access modifier which represents visibility. This makes the main method public that means
that we can call the method from outside the class.
static: We do not need to create object for static methods to run. They can run itself.
void: It is the return type of the method. It means it does not return any value.
10
main: It is the method name. This is the entry point method from which the JVM can run your program.
String[] args: Used for command line arguments that are passed as strings.
System.out.println("This is my first program in java in this academic year"): This method prints the
contents inside the double quotes into the console and inserts a newline after.
Note: the keyword Javac is the java compiler while java in an interpreter.
Input is any information that is needed by your program to complete its execution. There are many forms
that program input may take. Some programs use graphical components like a popup dialog box to accept
and return the character string that is typed by the user. You are certainly familiar with programs that are
controlled simply by clicking the mouse in a specific area of the screen. Still other programs, like word
processing programs, get some of their input from a file that is stored on the computer's floppy or hard
disk drive. Some programs, like web browsers, get their data from a network connection, while others get
data from devices like scanners, digital cameras and microphones. The possibilities are limited only by
computer scientists' imagination.
3.1.2-Output
Output is any information that the program must convey to the user. The information you see on your
computer screen is being output by one or more programs that are currently running on your computer.
When you decide to print a document, a program is told to send some output to the printer. Any sound
that your computer makes is because some program sent output to the speakers on your computer. The
possibilities for program output are also limited only by our imaginations.
11
3.2- Console Input in java
The console window is the window that is automatically launched when you run a program from within
Eclipse or NetBeans. Console input is any input that is entered in the console window instead of typing it
into a field or dialog box that pops up in a window. For example, when the nextLine method is called, the
program waits for the user to enter information. Whatever the user types is returned to the program in the
form of a String object.
There are many ways to get information from the user. In many cases, the user must be told that they
should enter some information. This is known as prompting the user. A user prompt is a line of text that
is output to the user that explains what information they should input next. We can prompt the user by
displaying information in a dialog box, a program frame, or even the console window. All programs that
require the user to input information while the program is running must prompt the user for that
information in some manner.
When a program is waiting for input at the console, there is sometimes a blinking cursor in the console
window indicating that the user should type some information. But, this is not always the case. The user
will only know what information to type if the program describes that information in the form of a user
prompt.
The use of several of the Java I/O classes may be required to successfully receive input that is typed by the
user. The java.io package contains most, if not all, of the classes you will need to use. The java.util
package also contains some classes that are useful for input and output. Don't worry, you won't need to
use all 50+ classes.
The Scanner class has a method called nextLine that returns a line of text as typed by the user. There are
two available constructors for creating a Scanner object. For console input, we will use the one that
requires only one argument, an instance of an InputStream object.
We will use the System.in object as our InputStream object and then use that object to create an instance
of the Scanner class.
12
3. Use the Scanner object to read a line of text from the user.
Application:
// 4. Now, you can do anything with the input string that you need to.
Note that the Scanner class is not in the standard java.lang package. You must import the
java.util.Scanner class to declare and create instances of the Scanner class. You must import the java.io
package to declare and create instances of any of the other Java I/O classes discussed in this document.
It's easiest to add the import java.util.*; statement (and, if you are using the other Java I/O classes, the
import java.io.*; statement) to your list of other import statements. Here's a complete program example
that prompts the user for input and then repeats that data to the console window:
/** A Java program that demonstrates console based input and output. */
// Display the input back to the user. System.out.println( "input = " + input );
Integer input
Getting data from the user isn't so hard after all. But, it does require some additional work. There may be
even more work to do, if you want to get an integer (or other numeric value) from the user. If the user
types in "123", that will be still be returned as a String object by the nextLine method
of Scanner. You will need to parse (convert) the String object into
an int value if you wish to store it in an int variable or data member. Here's one way to do this:
2. Use the Integer class to parse the string of characters into an integer.
changing String data into int values and vice versa. The Integer class is one of several wrapper classes
that are defined in the standard Java API (Application Programming Interface). Wrapper classes have
class methods for parsing and are also used when you need to store a primitive value as an object.
14
In our case, we needed to convert a String object into an int value.
As you can see, the Scanner class contains a method named nextInt that returns the next input data
available as an int value, that is, if the next input in the input stream is a valid integer format. If the next
input is not a valid integer format, an InputMismatchException is thrown.
You may be wondering why there are two ways to read integers from the user. This flexibility allows you,
the programmer, the option of which form is best for your program. The correct form to use depends
upon what you wish to do with the rest of the line that remains after an integer is read from the current
input line. The first example should be used if the only thing available on the current input line is the
integer value. The second example should be used if there are multiple data values to read on the same
input line.
Most programming languages have the ability to display a string of characters to the screen or some other
standard display device. We call this console output because the string of characters appears in a console
window.
The System.out object is an instance of the PrintStream class, which is a type of OutputStream
Exercises:
1- Write a java program prompting the user to enter 4 numbers and display the average
2- Write a program for computing the area and the circumference of a circle with 10 cm
of radius
15
Chapter 4: Data types, variables, constants and arrays in Java
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, String, and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Note: Java is a statically-typed programming language. It means, all variables must be declared before its
use. That is why we need to declare variable's type and name
There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
16
Data Type Default Value Default size
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
17
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127.
Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data
type.
Example: byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
18
point numbers. The float data type should never be used for precise values, such as currency. Its default
value is 0.0d.
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited.
The double data type is generally used for decimal values just like float. The double data type also should
never be used for precise values, such as currency.Its default value is 0.0d.
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.
• String
o It is class in java provided with several methods used to store group of characters.
o For example, abcd, india123 etc.
o String is not a primitive data type because it has methods and only class can have methods.
Primitive data types cannot have methods. So, String is a class which is non-primitive
type.
o 'String' is used to represent string class.
o Example: String s="World"
• Objects and Array
Objects and Array are non-primitive data types because it refers to the memory location
19
4.2- Java Variables
A variable is a container which holds the value while the java program is executed. A variable is assigned
with a datatype.
A variable is a combination of "vary + able" that means its value can be changed.
Also a Variable can be seen as a name of memory location. There are three types of variables in java:
local, instance and static.
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.
class A{
void method(){
20
int n=90;//local variable
}//end of class
class Simple{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}
class Simple{
float f=10.5f;
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
21
Java Variable Example: Overflow
class Simple{
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in
support for constants, but the variable modifiers static and final can be used to effectively create one.
Constants can make your program more easily read and understood by others. In addition, a constant is
cached by the JVM as well as your application, so using a constant can improve performance.
This allows a variable to be used without first creating an instance of the class; a static class member is
associated with the class itself, rather than an object. All class instances share the same copy of the
variable.
This means that another application or main() can easily use it.
22
Because this variable is static, it can be used elsewhere without explicitly creating a myClass object:
The final modifier means that the variable's value cannot change. Once the value is assigned, it cannot be
reassigned.
Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) can be made
immutable/unchangeable using the final modifier.
Note that we declared DAYS_IN_WEEK in all caps once we added the final modifier. It's a long-
standing practice among Java programmers to define constant variables in all caps, as well as to separate
words with underscores.
Java doesn't require this formatting but it makes it easier for anyone reading the code to immediately
identify a constant.
4.4- Array in Java
Arrays in Java, as in other languages, are a way to store collections of items into a single unit. The array
has some number of slots, each of which holds an individual item. You can add and delete items to those
slots as needed. Unlike in other languages, however, arrays in Java are actual objects that can be passed
around and treated just like other objects.
New Time
23
An array is a collection of items. Each slot in the array can hold an object or a
primitive value. Arrays in Java are objects that can be treated just like other objects
in the language.
Arrays can contain any type of element value (primitive types or objects), but you can't store different
types in a single array. You can have an array of integers or an array of strings or an array of arrays, but
you can't have an array that contains, for example, both strings and integers.
The first step in creating an array is creating a variable that will hold the array, just as you would any
other variable. Array variables indicate the type of object the array will hold (just as they do for any
variable) and the name of the array, followed by empty brackets ([]). The following are all typical array
variable declarations:
String difficultWords[];
Point hits[];
int temps[];
An alternate method of defining an array variable is to put the brackets after the type instead of after the
variable. They are equivalent, but this latter form is often much more readable. So, for example, these
three declarations could be written like this:
String[] difficultWords;
Point[] hits;
int[] temps;
Creating Array Objects
The second step is to create an array object and assign it to that variable. There are two ways to do this:
• Using new
• Directly initializing the contents of that array
24
The first way is to use the new operator to create a new instance of an array:
That line creates a new array of Strings with 10 slots (sometimes called elements). When you create a
new array object using new, you must indicate how many slots that array will hold. This line does not put
actual String objects in the slots-you'll have to do that later.
Array objects can contain primitive types such as integers or booleans, just as they can contain objects:
When you create an array object using new, all its slots are initialized for you (0 for numeric arrays, false
for boolean, '\0' for character arrays, and null for objects). You can then assign actual values or objects to
the slots in that array. You can also create an array and initialize its contents at the same time. Instead of
using new to create the new array object, enclose the elements of the array inside braces, separated by
commas:
Technical Note
Note that the Java keyword null refers to a null object (and can be used for any
object reference). It is not equivalent to zero or the '\0' character as the NULL
constant is in C.
Each of the elements inside the braces must be of the same type and must be the same type as the variable
that holds that array (the Java compiler will complain if they're not). An array the size of the number of
elements you've included will be automatically created for you. This example creates an array of String
objects named chiles that contains five elements.
Once you have an array with initial values, you can test and change the values in each slot of that array.
To get at a value stored within an array, use the array subscript expression ([]):
25
myArray[subscript];
The myArray part of this expression is a variable holding an array object, although it can also be an
expression that results in an array. The subscript part of the expression, inside the brackets, specifies the
number of the slot within the array to access. Array subscripts start with 0, as they do in C and C++. So,
an array with 10 elements has 10 array slots accessed using subscript 0 to 9.
Note that all array subscripts are checked when your Java program is run to make sure that they are inside
the boundaries of the array (greater than or equal to 0 but less than the array's length). Unlike in C, it is
impossible in Java to access or assign a value to an array slot outside the boundaries of the array (thereby
avoiding a lot of the common problems and bugs that result from overrunning the bounds of an array in
C-like languages). Note the following two statements, for example:
A program with that last statement in it produces an error at that line when you try to run it. The array
stored in arr has only 10 slots numbered from 0, the element at subscript 10 doesn't exist.
If the array subscript is calculated at runtime (for example, as part of a loop) and ends up outside the
boundaries of the array, the Java interpreter also produces an error.
How can you keep from accidentally overrunning the end of an array in your own programs? You can test
for the length of the array in your programs using the length instance variable-it's available for all array
objects, regardless of type:
However, just to reiterate: The length of the array is 10, but its subscript can only go up to 9. Arrays start
numbering from 0. Whenever you work with arrays, keep this in mind and subtract 1 from the length of
the array to get its largest element.
To assign an element value to a particular array slot, merely put an assignment statement after the array
access expression:
26
myarray[1] = 15;
sentence[0] = "The";
sentence[10] = sentence[0];
An important thing to note is that an array of objects in Java is an array of references to those objects
(similar in some ways to an array of pointers in C or C++). When you assign a value to a slot in an array,
you're creating a reference to that object, just as you do for a plain variable. When you move values
around inside arrays (as in that last line), you just reassign the reference; you don't copy the value from
one slot to another. Arrays of primitive types such as ints or floats do copy the values from one slot to
another.
Arrays of references to objects, as opposed to the objects themselves, are particularly useful because you
can have multiple references to the same objects both inside and outside arrays. For example, you can
assign an object contained in an array to a variable and refer to that same object by using either the
variable or the array position.
Got it? Arrays are pretty simple to create and modify, but they provide an enormous amount of
functionality for Java. You'll find yourself running into arrays a lot the more you use Java.
To finish up the discussion on arrays, here's a simple program that shows how to create, initialize,
modify, and examine parts of an array. Listing 5.1 has the code.
1: class ArrayTest {
2:
3: String[] firstNames = { "Dennis", "Grace", "Bjarne", "James" };
4: String[] lastNames = new String[firstNames.length];
5:
6: void printNames() {
7: int i = 0;
8: System.out.println(firstNames[i]
9: + " " + lastNames[i]);
10: i++;
11: System.out.println(firstNames[i]
27
12: + " " + lastNames[i]);
13: i++;
14: System.out.println(firstNames[i]
15: + " " + lastNames[i]);
16: i++;
17: System.out.println(firstNames[i]
18: + " " + lastNames[i]);
19: }
20:
21: public static void main (String args[]) {
22: ArrayTest a = new ArrayTest();
23: a.printNames();
24: System.out.println("----------");
25: a.lastNames[0] = "Ritchie";
26: a.lastNames[1] = "Hopper";
27: a.lastNames[2] = "Stroustrup";
28: a.lastNames[3] = "Gosling";
29: a.printNames();
30: }
31:}
Dennis null
Grace null
Bjarne null
James null
----------
Dennis Ritchie
Grace Hopper
Bjarne Stroustrup
James Gosling
Analysis
28
This somewhat verbose example shows you how to create and use arrays. The class
we've created here, ArrayTest, has two instance variables that hold arrays of String
objects. The first, called firstNames, is declared and initialized in the same line
(line 3) to contain four strings. The second instance variable, lastNames, is
declared and created in line 4, but no initial values are placed in the slots. Note also
that we created the lastNames array to have exactly the same number of slots as the
firstNames array by using the firstNames.length variable as the initial array index.
The length instance variable on array objects returns the number of slots in the
array.
The ArrayTest class also has two methods: printNames() and main(). printNames(), defined in lines 6
through 19, is a utility method that does nothing but go through the firstNames and lastNames arrays
sequentially, printing the values of each slot, one name per line. Note that the array index we've defined
here (i) is initially set to 0 because Java array slots all start numbering from 0.
Finally, there is main(), which performs the actual actions of this example. The main() method here does
four things:
• Line 22 creates an initial instance of ArrayTest, so we can set and modify its instance variables
and call its methods.
• Line 23 calls printNames() to show what the object looks like initially. The result is the first four
lines of the output; note that the firstNames array was initialized, but the values in lastNames are
all null. If you don't initialize an array when you declare it, the values of the initial slots will be
empty (or, actually, null for object arrays, 0 for numbers, and false for booleans).
• Lines 25 through 28 set the values of each of the slots in the lastNames array to actual strings.
• Finally, line 29 calls printNames() once again to show that the lastNames array is now full of
values, and each first and last name prints as you would expect. The results are shown in the last
four lines of the output.
Note
Who are the people in this example? They're inventors of computer programming
languages. Dennis Ritchie is the inventor of C, Bjarne Stroustrup did C++, Grace
29
Hopper is credited with COBOL, and, finally, James Gosling is the principal
designer of Java.
One other note I should make about Listing 5.1 is that it's a terrible example of programming style.
Usually when you deal with arrays you do not hard code the number of elements into the code as we have
here; instead you use a loop to go through each element of the array in turn. This makes the code a lot
shorter and, in many cases, easier to read. You'll learn about loops later in this section, and we'll rewrite
this example so that it works more flexibly.
Multidimensional Arrays
One last thing to note about arrays before we move on to the rest of this lesson is about multidimensional
arrays. Java does not directly support multidimensional arrays. However, you can declare and create an
array of arrays (and those arrays can contain arrays, and so on, for however many dimensions you need)
and access the arrays as you would C-style multidimensional arrays:
30
5.1.1- Literals
Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables. Java language specifies five major types of literals are as
follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
5.1.2- Identifiers
Identifiers are programmer-created tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
Identifier must be meaningful, easily understandable and descriptive
For example:
Private and local variables like “length”.
Name of public methods and instance variables begin with lowercase letter like “addition
5.1.3- Keywords
Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and method.
Following table shows keywords.
31
This volatile import protected
Class throws byte else
Float final public transient
Native instanceof case extends
Int null const new
Return try for switch
interface void while synchronized
Short continue goto super
Assert const
Java carries a broad range of operators. An operator is symbols that specify operation
to be performed may be certain mathematical and logical operation. Operators are used in
programs to operate data and variables. They frequently form a part of mathematical or
logical expressions.
Categories of operators are as follows: (Unary, Arithmetic, Relational, Assignment, Logical,
Bitwise, Ternary)
1. Unary Operator
The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value of a Boolean
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
32
The following program, UnaryDemo, tests the unary operators:
class UnaryDemo {
System.out.println(result);
System.out.println(result);
System.out.println(result);
System.out.println(result);
System.out.println(success); // false
System.out.println(!success); // true
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code
result++; and ++result; will both end in result being incremented by one. The only difference is that the
prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++)
evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really
matter which version you choose. But if you use this operator in part of a larger expression, the one that
you choose may make a significant difference.
The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:
33
class PrePostDemo {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
2. Arithmetic Operator
There are following arithmetic operators supported by java language:
Assume variable A holds 10 and variable B holds 20, then:
34
Example of Arithmetic Operators
3. Relational Operator
there are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
35
of right operand, if yes then
condition becomes true.
4. Assignment Operator
36
Example of Assignment Operators
5. Bitwise Operator
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as
follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
37
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then:
Binary Ones Complement (~A ) will give -61 which is 1100 0011 in 2's
~ Operator is unary and has the complement form due to a signed binary
effect of 'flipping' bits. number.
6. Logical Operator
38
Logical Operators are used with binary variables. They are mainly used in conditional statements and
loops for evaluating a condition.
There are following logical operators supported by Java language.
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
This operator evaluates a Boolean expression and assign the value based on the result.
Syntax:
variable num1 = (expression) ? value if true : value if false
If the expression results true then the first value before the colon (:) is assigned to the variable num1 else
the second value is assigned to the num1.
39
public class TernaryOperatorDemo {
Assignment
1- Write a Java Program to find Largest of three numbers using Ternary Operator
2- Write a Java Program to find the smallest of three numbers using Ternary Operator
5.1.5- Separators
Separators help define the structure of a program. The separators used in HelloWorld are parentheses, ( ),
braces, { }, the period, ., and the semicolon, ;. The table lists the six Java separators (nine if you count
opening and closing separators as two).
Separator
Purpose
40
{} defines blocks of code and automatically initializes arrays
; terminates statements
Selects a field or method from an object; separates package names from sub-package and
.
class names
41
Chapter 6: Control structure in java
When we need to execute a set of statements based on a condition then we need to use control flow
statements. For example, if a number is greater than zero then we want to print “Positive Number” but if
it is less than zero then we want to print “Negative Number”. In this case we have two print statements in
the program, but only one print statement executes at a time based on the input value. We will see how to
write such type of conditions in the java program using control statements.
In this chapter, we will see four types of control statements that you can use in java programs based on
the requirement: In this tutorial we will cover following conditional statements:
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
a) If statement
if(condition){
Statement(s);
The statements gets executed only when the given condition is true. If the condition is false then the
statements inside if statement body are completely ignored.
42
b) Nested If statement
if(condition_2) {
Statement2(s);
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the
conditions( condition_1 and condition_2) are true.
c) If-Else statement
43
if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else” would
execute if the condition is false.
d-if-else-if Statement
44
if-else-if statement is used when we need to check multiple conditions. In this statement we have only one
“if” and one “else”, however we can have multiple “else if”. It is also known as if else if ladder. This is
how it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
45
Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is met then
the statements inside “else” gets executed.
Example of if-else-if
}
}
}
ASSIGNMENT:
1- Write a Java Program to find the largest of three numbers using if..else..if
2- Write a Java Program to check if number is positive or negative
3- Write a Java Program to check if number is even or odd
46
Chapter 7: Loops (For, while, do--while) and others statements in JAVA
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java
we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for
loop” in Java.
statement(s);
As a program executes, the interpreter always keeps track of which statement is about to be executed. We
call this the control flow, or the flow of execution of the program.
47
First step: In for loop, initialization happens first and only one time, which means that the initialization
part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the
statements inside for loop body gets executed. Once the condition returns false, the statements in for loop
does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes
that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
class ForLoopExample {
Note: In the above example, I have declared the num as int in the enhanced for loop. This will change
depending on the data type of array. For example, the enhanced for loop for string type would look like
this:
String arr[]={"hi","hello","bye"};
for (String str : arr) {
System.out.println(str);
}
48
EXERCISES:
In the last tutorial, we discussed for loop. In this part we will discuss while loop. As discussed in
previous part, loops are used to execute a set of statements repeatedly until a particular condition is
satisfied.
while(condition)
{
statement(s);
}
Note: The important point to note when using while loop is that we need to use increment or decrement
statement inside while loop so that the loop variable gets changed on each iteration, and at some point
condition returns false. This way we can end the execution of while loop otherwise the loop would
execute indefinitely.
49
Simple while loop example
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}
50
while(i>1)
{
System.out.println(i);
i++;
}
}
}
This loop would never end, its an infinite while loop. This is because condition is i>1 which would
always be true as we are incrementing the value of i inside while loop.
while (true){
statement(s);
51
Example: Iterating an array using while loop
Here we are iterating and displaying array elements using while loop.
class WhileLoopExample3 {
int arr[]={2,11,45,9};
int i=0;
while(i<4){
System.out.println(arr[i]);
i++;
Exercises:
In the last tutorial, we discussed while loop. In this tutorial we will discuss do-while loop in java. do-
while loop is similar to while loop, however there is a difference between them: In while loop, condition
is evaluated before the execution of loop’s body but in do-while loop condition is evaluated after the
execution of loop’s body.
52
Syntax of do-while loop:
do{
statement(s);
} while(condition);
53
do-while loop example
class DoWhileLoopExample {
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
} Exercises:
Switch case statement is used when we have number of options (or choices) and we may need to
perform a different task for each choice.
54
switch (variable or an integer expression)
case constant:
//Java code
case constant:
//Java code
default:
//Java code
Switch Case statement is mostly used with break statement even though it is optional. We will first see an
example without break statement and then we will discuss switch case with break
55
public class SwitchCaseExample1 {
public static void main(String args[]){
int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where num value
is 2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default
case got executed. This is why we should use default in switch case, so that if there is no catch that
matches the condition, the default block gets executed.
First the variable, value or expression which is provided in the switch parenthesis is evaluated and then
based on the result, the corresponding case block is executed that matches the result.
56
Break statement in Switch Case
Break statement is optional in switch case but you would use it almost every time you deal with switch
case. Before we discuss about break statement, let’s have a look at the example below where I am not
using the break statement:
57
public class SwitchCaseExample2 {
Break statements are used when you want your program-flow to come out of the switch body. Whenever
a break statement is encountered in the switch body, the execution flow would directly come out of the
switch, ignoring rest of the cases
Let’s take the same example but this time with break statement.
58
Example with break statement
Now you can see that only case 2 had been executed, rests of the cases were ignored.
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case
keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order
based on the requirement.
59
2) You can also use characters in switch case. for example –
3) The expression given inside switch should result in a constant value otherwise it would not be valid.
For example:
switch(1+2+23)
switch(1*2+3%4)
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch statements inside another
switch. However nested switch statements should be avoided as it makes program more complex and less
readable.
60
Exercises:
1. Write a Java Program to check whether a char is vowel or Consonant using Switch Case
2. Write a Java Program to make a Simple Calculator using Switch Case
a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered
inside a loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations.
It is used along with if statement, whenever used inside loop so that the loop gets terminated for a
particular condition.
The important point to note here is that when a break statement is used inside a nested loop, then only the
inner loop gets terminated.
b) It is also used in switch case control. Generally all cases in switch case are followed by a break
statement so that whenever the program control jumps to a case, it doesn’t execute subsequent cases (see
the example below). As soon as a break is encountered in switch-case block, the control comes out of the
switch-case body.
break;
61
Example: break statement inside for loop
System.out.print(j+" ");
}
}
}
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control
directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside
loop’s body for the current iteration. This is particularly useful when you want to continue the loop but do
not want the rest of the statements(after continue statement) in loop body to execute for that particular
iteration.
Syntax:
continue word followed by semi colon.
continue;
62
Example: continue statement inside for loop
System.out.print(j+" ");
}
As you may have noticed, the value 4 is missing in the
}
} output, why? because when the value of variable j
is 4, the program encountered a continue statement, which makes it to jump at the beginning of for loop
for next iteration, skipping the statements for current iteration (that’s the reason println didn’t execute
when the value of j was 4).
63
Example: Use of continue in While loop
Same thing you can see here. We are iterating this loop from 10 to 0 for counter value and when the
counter value is 7 the loop skipped the print statement and started next iteration of the while loop.
64
Chapter 8: Applet
Much of Java's current popularity has come about because of Java-enabled World Wide Web browsers
and their support for applets-Java programs that run on Web pages and can be used to create dynamic,
interactive Web sites. Applets, as noted at the beginning of this book, are written in the Java language,
and can be viewed in any browser that supports Java, including Netscape's Navigator and Microsoft's
Internet Explorer. Learning how to create applets is most likely the reason you bought this book, so let's
waste no more time.
Last week, you focused on learning about the Java language itself, and most of the little programs you
created were Java applications. This week, now that you have the basics down, you'll move on to creating
and using applets, which includes a discussion of many of the classes in the standard Java class library.
Today you'll start with the basics:
65
embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads
a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on
the local system (the one the browser is running on). (The Java interpreter is built into the browser and
runs the compiled Java class file from there.)
Because Java applets run inside a Java browser, they have access to the structure the browser provides: an
existing window, an event-handling and graphics context, and the surrounding user interface.
Note that a single Java program can be written to operate as both a Java application and a Java applet.
While you use different procedures and rules to create applets and applications, none of those procedures
or rules conflict with each other. The features specific to applets are ignored when the program runs as an
application, and vice versa. Keep this in mind as you design your own applets and applications.
One final significant difference between Java applets and applications-probably the biggest difference-is
the set of restrictions placed on how applets can operate in the name of security. Given the fact that Java
applets can be downloaded from any site on the World Wide Web and run on a client's system, Java-
enabled browsers and tools limit what can be done to prevent a rogue applet from causing system damage
or security breaches. Without these restrictions in place, Java applets could be written to contain viruses
or trojan horses (programs that seem friendly but do some sort of damage to the system), or be used to
compromise the security of the system that runs them. The restrictions on applets include the following:
• Applets can't read or write to the reader's file system, which means they cannot delete files or test
to see what programs you have installed on the hard drive.
• Applets can't communicate with any network server other than the one that had originally stored
the applet, to prevent the applet from attacking another system from the reader's system.
• Applets can't run any programs on the reader's system. For UNIX systems, this includes forking a
process.
• Applets can't load programs native to the local platform, including shared libraries such as DLLs.
All these rules are true for Java applets running Netscape Navigator or Microsoft Internet Explorer. Other
Java-enabled browsers or tools may allow you to configure the level of security you want-for example,
the appletviewer tool in the JDK allows you to set an access control list for which directories an applet
can read or write. However, as an applet developer, it's safe to assume that most of your audience is going
to be viewing your applets in a browser that implements the strictest rules for what an applet can do. Java
applications have none of these restrictions.
66
Chapter 9: Java Exception Handling
Lesson 1: Java exceptions
In this lesson, we will learn about exceptions in Java. We will cover about errors,
exceptions and different types of exceptions in Java.
• Device failure
• Code errors
67
Here is a simplified diagram of the exception hierarchy in Java.
As you can see from the image above, the Throwable class is the root class in the
hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
3- Errors
4- Exceptions
68
It contains information about the exception such as the name and description of the
exception and state of the program when the exception occurred.
We will learn how to handle these exceptions in the next tutorial. In this tutorial, we
will now focus on different types of exceptions in Java.
5.1 . RuntimeException
A runtime exception happens due to a programming error. They are also known
as unchecked exceptions.
These exceptions are not checked at compile-time but at run-time. Some of the
common runtime exceptions are:
You can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if you had checked whether the
variable was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if you tested the array
index against the array bounds.
5.2. IOException
69
An IOException is also known as a checked exception. They are checked by the
compiler at the compile-time and the programmer is prompted to handle these
exceptions.
Some of the examples of checked exceptions are:
Now we know about exceptions, we will learn about handling exceptions in the next
Lesson.
In the last Lesson, we learned about exceptions. Exceptions are unexpected events
that occur during program execution.
try {
// code
} catch (ExceptionType e) {
// catch block
} finally {
// finally block
}
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
In the example,
• When the exception occurs, the program skips the rest of the code in the try block.
71
Example 2: Multiple catch blocks
class ListOfNumbers {
public int[] arrayOfNumbers = new int[10];
try {
arrayOfNumbers[10] = 11;
} catch (NumberFormatException e1) {
System.out.println("NumberFormatException => " + e1.getMessage());
} catch (IndexOutOfBoundsException e2) {
System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
Output
72
For each try block, there can be only one finally block.
The finally block is optional. However, if defined, it is always executed (even if the
exception doesn't occur).
If an exception occurs, it is executed after the try...catch block. If no exception
occurs, it is executed after the try block.
The basic syntax of finally block is:
try {
//code
} catch (ExceptionType1 e1) {
// catch block
} catch (ExceptionType1 e2) {
// catch block
} finally {
// finally block always executes
}
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
} finally {
System.out.println("Finally block is always executed");
}
}
}
Output
73
Having a finally block is considered a good practice. It is because it includes
important cleanup code such as:
• code that might have been accidentally skipped
by return , continue or break statements
We have mentioned that finally always executes and that is usually the case.
However, there are some cases when a finally block does not execute:
• Use of System.exit() method
• An exception occurs in the finally block
• The death of a thread
Let’s take an example where we try to create a new file using FileWriter and write
data to it using PrintWriter .
import java.io.*;
class ListOfNumbers {
private int[] list = new int[10];
public ListOfNumbers() {
// storing integer values in the list array
for (int i = 0; i < 10; i++) {
list[i] = i;
}
}
try {
System.out.println("Entering try statement");
74
for (int i = 0; i < 10; i++) {
out.println("Value at: " + i + " = " + list[i]);
}
} catch (IndexOutOfBoundsException e1) {
System.out.println("IndexOutOfBoundsException => " + e1.getMessage());
} catch (IOException e2) {
System.out.println("IOException => " + e2.getMessage());
} finally {
// checking if PrintWriter has been opened
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
When you run this program, there are two possibilities that may occur:
When exception doesn't occur and the try block executes normally, we will get the
following output.
75
Entering try statement
Closing PrintWriter
Value at: 0 = 0
Value at: 1 = 1
Value at: 2 = 2
Value at: 3 = 3
Value at: 4 = 4
Value at: 5 = 5
Value at: 6 = 6
Value at: 7 = 7
Value at: 8 = 8
Value at: 9 = 9
Let's try to understand the flow of exception handling in detail with the help of above
example.
76
The above figure describes the flow of program execution when an exception occurs
while creating a new FileWriter .
• To get to the method where the exception occurs, the main method calls
the writeList() method which then calls the FileWriter() method to create a
new OutputFile.txt file.
• When an exception occurs, the runtime system skips the rest of the code in
the try block.
• It starts searching through the call stack in reverse order to find an appropriate
exception handler.
• Here, FileWriter does not have an exception handler, so runtime system checks the
next method in the call stack i.e writeList .
• The first handler in this example handles IndexOutOfBoundsException . This does not
match the IOException thrown by the try block.
• So, the next handler is checked which is the IOException handler. This matches the
type of exception thrown so the code in the catch block is executed.
• After the exception handler executes, the finally block is executed.
• In this scenario, since an exception occurred in the FileWriter ,
the PrintWriter object out was never opened and does not need to be closed.
Now, let us suppose that the exception doesn’t occur while running this program and
the try block executes normally. An OutputFile.txt is created and written to in this
case.
As we know, the finally block is executed regardless of the exception handling.
Since no exception occurred, the PrintWriter is open and needs to be closed. This is
done by out.close() statement in the finally block.
77
From Java SE 7 and later, we can now catch more than one type of exception with
one catch block.
This reduces code duplication and increases code simplicity and efficiency.
Each exception type that can be handled by the catch block is separated using a
vertical bar | .
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
The try-with-resources statement is a try statement that has one or more resource
declarations.
The resource is an object to be closed at the end of the program. It must be declared
and initialized in the try statement.
78
The try-with-resources statement is also referred to as automatic resource
management. This statement automatically closes all the resources at the end of the
statement.
79
This tutorial will now focus on how to handle checked exceptions
using throw and throws .
We use the throws keyword in the method declaration to declare the type of
exceptions that might occur within it.
Its syntax is:
As you can see from the above syntax, we can use throws to declare multiple
exceptions.
import java.io.*;
class Main {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
80
}
}
Output
When we run this program, if the file test.txt does not exist, FileInputStream throws
a FileNotFoundException which extends the IOException class.
If a method does not handle exceptions, the type of exceptions that may occur within
it must be specified in the throws clause so that methods further up in the call stack
can handle them or specify them using throws keyword themselves.
The findFile() method specifies that an IOException can be thrown. The main() method
Here's how we can throw multiple exceptions using the throws keyword.
import java.io.*;
class Main {
public static void findFile() throws NullPointerException, IOException,
InvalidClassException {
81
public static void main(String[] args) {
try{
findFile();
} catch(IOException e1){
System.out.println(e1.getMessage());
} catch(InvalidClassException e2){
System.out.println(e2.getMessage());
}
}
}
There might be several methods that can cause exceptions. Writing try...catch for
each method will be tedious and code becomes long and less-readable.
throws is also useful when you have checked exception (an exception that must be
handled) that you don't want to catch in your current method.
82
Its syntax is:
throw throwableObject;
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
exit status 1
import java.io.*;
class Main {
public static void findFile() throws IOException {
83
throw new IOException("File not found");
}
Output
The findFile() method throws an IOException with the message we passed to its
constructor.
Note that since it is a checked exception, we must specify it in the throws clause.
The methods that call this findFile() method need to either handle this exception or
specify it using throws keyword themselves.
We have handled this exception in the main() method. The flow of program execution
transfers from the try block to catch block when an exception is thrown. So, the rest
of the code in the try block is skipped and statements in the catch block are executed.
84
Lesson 4: Java catch Multiple Exceptions
In this tutorial, we will learn to handle multiple exceptions in Java with the help
of examples.
Before Java 7, we had to write multiple exception handling codes for different types
of exceptions even if there was code redundancy.
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
85
}
Output
/ by zero
In Java SE 7 and later, we can now catch more than one type of exception in a
single catch block.
Each exception type that can be handled by the catch block is separated using a
vertical bar or pipe | .
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
86
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Output
/ by zero
Catching multiple exceptions in a single catch block reduces code duplication and
increases efficiency.
The bytecode generated while compiling this program will be smaller than the
program having multiple catch blocks as there is no code redundancy.
Note: If a catch block handles multiple exceptions, the catch parameter is
implicitly final . This means we cannot assign any values to catch parameters.
When catching multiple exceptions in a single catch block, the rule is generalized to
specialized.
This means that if there is a hierarchy of exceptions in the catch block, we can catch
the base exception only instead of catching multiple specialized exceptions.
Let’s take an example.
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
87
}
Output
/ by zero
We know that all the exception classes are subclasses of the Exception class. So,
instead of catching multiple specialized exceptions, we can simply catch
the Exception class.
If the base exception class has already been specified in the catch block, do not use
child exception classes in the same catch block. Otherwise, we will get a compilation
error.
Let’s take an example.
class Main {
public static void main(String[] args) {
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Output
• state
• behavior
1. Lamp is an object
o It can be in on or off state.
o You can turn on and turn off lamp (behavior).
2. Bicycle is an object
o It has current gear , two wheels , number of gear etc. states.
o It has braking , accelerating , changing gears etc. behavior.
You will learn about 3 main features of an object-oriented programming: data
encapsulation, inheritance and polymorphism in later chapters. This article will focus
on class and objects to keep things simple.
Java Class
Before you create objects in Java, you need to define a class.
We can think of class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows etc. Based on these descriptions we build the
house. House is the object.
89
Since, many houses can be made from the same description, we can create many
objects from a class.
class ClassName {
// variables
// methods
}
Here's an example:
class Lamp {
// instance variable
private boolean isOn;
// method
public void turnOn() {
isOn = true;
}
// method
public void turnOff() {
isOn = false;
}
}
The class has one instance variable (variable defined inside class) isOn and two
methods turnOn() and turnOff() . These variables and methods defined within a class
are called members of the class.
90
Notice two keywords, private and public in the above program. These are access
modifiers which will be discussed in detail in later chapters. For now, just remember:
• The private keyword makes instance variables and methods private which can be
accessed only from inside the same class.
• The public keyword makes instance variables and methods public which can be
accessed from outside of the class.
In the above program, isOn variable is private
whereas turnOn() and turnOff() methods are public.
If you try to access private members from outside of the class, compiler throws error.
Java Objects
When class is defined, only the specification for the object is defined; no memory or
storage is allocated.
To access members defined within the class, you need to create objects. Let's create
objects of Lamp class.
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(); // create l1 object of Lamp class
91
Lamp l2 = new Lamp(); // create l2 object of Lamp class
}
}
l1.turnOn();
This statement calls turnOn() method inside Lamp class for l1 object.
We have mentioned word method quite a few times. You will learn about Java
methods in detail in the next chapter. Here's what you need to know for now:
When you call the method using the above statement, all statements within the body
of turnOn() method are executed. Then, the control of program jumps back to the
statement following l1.turnOn() ;
92
Similarly, the instance variable can be accessed as:
l2.isOn = false;
It is important to note that, the private members can be accessed only from inside the
class. If the code l2.isOn = false; lies within the main() method (outside of
the Lamp class), compiler will show error.
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
void displayLightStatus() {
class ClassObjectsExample {
public static void main(String[] args) {
l1.turnOn();
l2.turnOff();
93
l1.displayLightStatus();
l2.displayLightStatus();
}
}
• Two objects l1 and l2 of Lamp class are created in the main() function.
• Here, turnOn() method is called using l1 object: l1.turnOn();
94
Lesson 2: Java Methods
In this lesson, you’ll learn about Java methods, how to define a Java method
and use them in your program with the help of examples.
What is a method?
In mathematics, you might have studied about functions. For example, f(x) = x2 is a
function that returns squared value of x .
If x = 2, then f(2) = 4
If x = 3, f(3) = 9
and so on.
95
Depending on whether a method is defined by the user, or available in standard
library, there are two types of methods:
• User-defined Methods
For example,
96
User-defined Method
You can also define methods inside a class as per your wish. Such methods are
called user-defined methods.
// method body
97
Here,
• modifier - defines access type whether the method is public, private and so on.
• static - If you use static keyword in a method then it becomes a static method. Static
methods can be called without creating an instance of a class.
For example, the sqrt() method of standard Math class is static. Hence, we can
directly call Math.sqrt() without creating an instance of Math class.
It can return native data types (int, float, double etc.), native objects (String, Map, List
etc.), or any other built-in and user defined objects.
If the method does not return a value, its return type is void.
You can give any name to a method. However, it is more conventional to name it
after the tasks it performs. For example, calculateInterest , calculateArea , and so on.
• Parameters (arguments) - Parameters are the values passed to a method. You can
pass any number of arguments to a method.
• Method body - It defines what the method actually does, how the parameters are
manipulated with programming statements and what values are returned. The codes
inside curly braces { } is the body of the method.
98
Now you defined a method, you need to use it. For that, you have to call the method.
Here's how:
myMethod();
This statement calls the myMethod() method that was declared earlier.
1. While Java is executing the program code, it encounters myMethod(); in the code.
2. The execution then branches to the myFunction() method, and executes code inside
the body of the method.
3. After the codes execution inside the method body is completed, the program returns
to the original state and executes the next statement.
class Main {
// method call
myMethod();
99
System.out.println("Method was executed successfully!");
}
// method definition
private static void myMethod(){
System.out.println("Printing from inside myMethod()!");
}
}
The method myMethod() in the above program doesn't accept any arguments. Also, the
method doesn't return any value (return type is void ).
Note that, we called the method without creating object of the class. It was possible
because myMethod() is static.
Here's another example. In this example, our method is non-static and is inside
another class.
class Main {
class Output {
Note that, we first created instance of Output class, then the method was called
using obj object. This is because myMethod() is a non-static method.
class SquareMain {
public static void main(String[] args) {
int result;
result = square();
System.out.println("Squared value of 10 is: " + result);
}
101
In the above code snippet, the method square() does not accept any arguments and
always returns the value of 10 squared.
Notice, the return type of square() method is int . Meaning, the method returns an
integer value.
As you can see, the scope of this method is limited as it always returns the same
value.
Now, let's modify the above code snippet so that instead of always returning the
squared value of 10, it returns the squared value of any integer passed to the
method.
n = 3
result = square(n);
System.out.println("Square of 3 is: " + result);
n = 4
result = square(n);
102
System.out.println("Square of 4 is: " + result);
}
Now, the square() method returns the squared value of whatever integer value
passed to it.
Java is a strongly-typed language. If you pass any other data type except int (in the
above example), compiler will throw an error.
The argument passed n to the getSquare() method during the method call is called
actual argument.
result = getSquare(n);
103
You can pass more than one argument to the Java method by using commas. For
example,
10 + 20 = 30
20 x 40 = 800
The data type of actual and formal arguments should match, i.e., the data type of first
actual argument should match the type of first formal argument. Similarly, the type of
second actual argument must match the type of second formal argument and so on.
// method defined
private static int getSquare(int x){
return x * x;
}
104
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
// method call
result = getSquare(i)
System.out.println("Square of " + i + " is : " + result); }
}
}
Square of 1 is : 1
Square of 2 is : 4
Square of 3 is : 9
Square of 4 is : 16
Square of 5 is : 25
In above code snippet, the method getSquare() takes int as a parameter. Based on
the argument passed, the method returns the squared value of it.
Here, argument i of type int is passed to the getSquare() method during method call.
result = getSquare(i);
The parameter x accepts the passed argument [in the function definition getSquare(int
x) ].
return i * i; is the return statement. The code returns a value to the calling method
and terminates the function.
Did you notice, we reused the getSquare method 5 times?
105
• Methods make code more readable and easier to debug. For
example, getSalaryInformation() method is so readable, that we can know what this
method will be doing than actually reading the lines of code that make this method.
What is a Constructor?
A constructor is similar to a method (but not actually a method) that is invoked
automatically when an object is instantiated.
Java compiler distinguish between a method and a constructor by its name and
return type. In Java, a constructor has same name as that of the class, and doesn’t
return any value.
class Test {
Test() {
// constructor body
Here, Test() is a constructor; it has same name as that of the class and doesn’t have
a return type.
class Test {
void Test() {
// method body
106
}
Here, Test() has same name as that of the class. However, it has a return type void .
// constructor
private ConsMain(){
System.out.println("Constructor Called");
x = 5;
}
Constructor Called
Value of x = 5
No-Arg Constructor
107
If a Java constructor does not accept any parameters, it is a no-arg constructor. It's
syntax is:
accessModifier ClassName() {
// constructor body
int i;
108
However, if the object was created outside of the class, you have to declare the
constructor public to access it. For example:
class Company {
String domainName;
// object is created in another class
public Company(){
domainName = "programiz.com";
}
}
Default Constructor
If you do not create constructors yourself, the Java compiler will automatically
create a no-argument constructor during run-time. This constructor is known as
default constructor. The default constructor initializes any uninitialized instance
variables.
Boolean false
Byte 0
109
Type Default Value
Short 0
Int 0
Long 0L
Char \u0000
Float 0.0f
Double 0.0d
int a;
boolean b;
int a;
boolean b;
private DefaultConstructor() {
a = 0;
b = false;
}
a = 0
b = false
Parameterized Constructor
A constructor may also accept parameters. It's syntax is:
// constructor body
111
Example: Parameterized constructor
class Vehicle {
int wheels;
private Vehicle(int wheels){
wheels = wheels;
System.out.println(wheels + " wheeler vehicle created.");
}
Here, we have passed an argument of type int (number of wheels) to the constructor
during object instantiation.
class Company {
String domainName;
public Company(){
this.domainName = "default";
}
defaultObj.getName();
programizObj.getName();
}
}
default
programiz.com
Important notes
• Constructors are invoked implicitly when you instantiate objects.
o A Java constructor name must exactly match with the class name (including case).
113
o Default Constructor - a constructor that is automatically created by the Java compiler
if it is not explicitly defined.
114
Lesson 4: Java Access Modifiers
In this article, you will learn about different Access Modifiers in Java and how
they work in different scenarios.
You cannot set visibility modifier of getters (retrieving value of a variable) as they
always take the same visibility as that of the property.
Using access modifiers forces better encapsulation to your code. Meaning, with
encapsulation you can control what part of a program can access the members of a
class. So that misuse of data can be prevented.
Modifier Description
Default Declarations are visible only within the package (package private)
115
Protected Declarations are visible within the package or and all sub classes
package defaultPackage;
class Logger {
void message(){
System.out.println(“This is a message”);
}
}
Here, Logger class has the default access modifier. And this logger class is visible to
the classes that belong to the defaultPackage package. If you import Logger class in
different package and try to instantiate it, you’ll get compilation error.
Programiz
Here, name is a private variable and it is visible only inside the Data class. But, it can
be accessed in another class Main by the help of public getter and setter methods.
// Logger.java
package package1;
117
public class Logger {
protected void debug(String logLine){
System.out.println("Debug line: "+logLine);
}
}
// Main.java
package package2;
import package1.Logger;
As you can see, the Logger.java and Main.java are in different package.
The debug() method in Logger class in protected and this method can be accessed
only inside the package1 . But, however, it is accessed in the Main class as well. And
this is all possible because Main class inherits the Logger class.
118
Example 4: Define Public Access Modifiers
// Logger.java
public class Logger {
public int debugLevel = 1;
public void debug(String logLine){
System.out.println("Debug: "+logLine);
}
public void info(String logLine){
System.out.println("Info: "+logLine);
}
}
// LoggerImp.java
public class LoggerImp {
Here, in LoggerImp class, you were able to instantiate the Logger class because it’s
access modifier is public. The variables and methods inside the LoggerImp class are
also public. Hence, you are able to use it directly in your LoggerImp class.
119
All Access Modifiers summarized in one figure
120
Lesson 5: Java this Keyword
In this article, you'll learn about this keyword in Java; how and where they are
used with the help of examples.
this Keyword
In Java, this refers to the current object inside methods or constructors. Let's take an
example to prove it.
class MyClass {
int instVar;
MyClass(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}
Notice that the object id of obj and this is same. Meaning, this is nothing but the
reference to the current object.
There are 3 situations where this keyword are commonly used.
121
In Java, it is not allowed to declare two or more variables having same name inside a
scope (class scope or method scope). However, instance variables and parameters
may have same name. Like this:
class MyClass {
instVar = instVar;
In the above program, the Java compiler is confused due to name ambiguity. Hence,
to address this problem, this keyword is used.
First, let’s see an example without using this keyword:
class MyClass {
int instVar;
MyClass(int instVar){
instVar = instVar;
}
mc.instVar = 0
122
You might have expected 8 as an output, but, instead you get 0. This is because the
Java compiler gets confused because of the ambiguity in names between the
instance variable and the constructor parameter.
Now, let’s rewrite the above code and use this keyword to solve this issue.
class MyClass{
int instVar;
MyClass(int instVar){
this.instVar = instVar;
}
mc.instVar = 8
Now, you’ll get the expected output. It’s because when you are create an object, the
Java compiler knows which object has invoked the constructor.
When Java compiler invokes the constructor, this inside the constructor is replaced
by the object which called the constructor.
Note: If you pass a parameter that has different name than that of instance variables,
the compiler automatically appends this keyword.
This code
class MyClass {
123
int instVar;
MyClass(int i) {
instVar = i;
is equivalent to:
class MyClass {
int instVar;
MyClass(int i) {
this.instVar = i;
Another common use of this keyword is in setters and getters methods of a class.
For example:
class POJO {
String name;
String getName(){
return this.name;
}
124
public static void main( String[] args ) {
POJO pojo = new POJO();
pojo.setName("Toshiba");
System.out.println("pojo.name: "+pojo.getName());
}
}
pojo.name: Toshiba
this(arg-list)
Here's how you can call a constructor from another constructor using this .
class Complex {
private int a, b;
// parameterize constructor
private Complex( int i, int j ){
this.a = i;
this.b = j;
}
125
private Complex(int i){
this(i, i); // invokes Complex(int i, int j);
}
private Complex(){
this(0); // invokes Complex(int i);
}
@Override
public String toString(){
return this.a + " + " + this.b + "i";
}
2 + 3i
3 + 3i
0 + 0i
In the above program, no matter which constructor is called during the object
instantiation, the parameterized constructor will be called eventually.
You must be careful while using this() . Constructors that call this() executes slow
because calling another overloaded constructor adds overhead. If your class is used
to create only handful of objects, then using this() is fruitful. Another huge advantage
of using this() is to reduce the amount of duplicate code.
By the way, invoking one constructor from another constructor is called explicit
constructor invocation.
126
3. Passing this as an Argument
If you need to pass the current object as an argument to a method, you can use this .
class ThisExample {
int x;
int y;
ThisExample(int x, int y) {
this.x = x;
this.y = y;
System.out.println("Before passing this to addTwo() method:");
System.out.println("x = " + this.x + ", y = " + this.y);
addTwo(this);
System.out.println("After passing this to addTwo() method:");
System.out.println("x = " + this.x + ", y = " + this.y);
}
class Demo {
public static void main( String[] args ) {
ThisExample obj = new ThisExample(1, -2);
}
}
Here, addTwo() method is called with this as an argument from inside the constructor.
127
Lesson 6: Java Recursion
In this article, you will learn to create recursive function; a function that calls
itself. Also, you will learn about its advantages and disadvantages.
A method that calls itself is known as a recursive method. And, this technique is
known as recursion.
128
A physical world example would be to place two parallel mirrors facing each other.
Any object in between them would be reflected recursively.
In the above program, recurse() method is called from inside the main method at first
(normal method call).
Also, recurse() method is called from inside the same method, recurse() . This is a
recursive call.
The recursion continues until some condition is met to prevent it from execution. If
not, infinite recursion occurs.
Hence, to prevent infinite recursion, if...else statement (or similar approach) can be
used where one branch makes the recursive call and other doesn't.
4 factorial = 24
Initially, factorial() is called from the main() method with number passed as an
argument.
Inside factorial() method, the value of n is 4 initially. During the next recursive call, 3
is passed to the factorial() method. This process continues until n is equal to 0.
When n is equal to 0, if condition fails and the else part is executed which returns 1,
and accumulated result is passed to the main() method.
This figure will give you a better idea on how the above program works.
In Java, we use the extends keyword to inherit from a class. Here, we have inherited
the Dog class from the Animal class.
The Animal is the superclass (parent class or base class), and the Dog is a subclass
(child class or derived class). The subclass inherits the fields and methods of the
superclass.
131
is-a relationship
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
class Animal {
class Main {
public static void main(String[] args) {
dog1.eat();
132
dog1.sleep();
dog1.bark();
}
}
Output
I can eat
I can sleep
I can bark
Here, we have inherited a subclass Dog from superclass Animal . The Dog class inherits
the methods eat() and sleep() from the Animal class.
Hence, objects of the Dog class can access the members of both the Dog class and
the Animal class.
133
protected Keyword
private Yes No No No
class Animal {
protected String type;
private String color;
134
public void sleep() {
System.out.println("I can sleep");
}
class Main {
public static void main(String[] args) {
dog1.type = "mammal";
dog1.setColor("black");
dog1.displayInfo(dog1.getColor());
}
}
Output
I can eat
I can sleep
I can bark
I am a mammal
My color is black
135
Here, the type field inside the Animal class is protected. We have accessed this field
from the Main class using
dog1.type = "mammal";
It is possible because Animal and Main class are in the same package (same file).
From the above examples, we know that objects of a subclass can also access
methods of its superclass.
What happens if the same method is defined in both the superclass and
subclass?
Well, in that case, the method in the subclass overrides the method in the
superclass. For example,
class Animal {
protected String type = "animal";
@Override
public void eat() {
System.out.println("I eat dog food");
}
136
public void bark() {
System.out.println("I can bark");
}
}
class Main {
public static void main(String[] args) {
Output
Here, eat() is present in both the superclass Animal and subclass Dog . We created an
object dog1 of the subclass Dog .
When we call eat() using the dog1 object, the method inside the Dog is called, and the
same method of the superclass is not called. This is called method overriding.
In the above program, we have used the @Override annotation to tell the compiler that
we are overriding a method. However, it's not mandatory. We will learn about method
overriding in detail in the next tutorial.
If we need to call the eat() method of Animal from its subclasses, we use
the super keyword.
Example 4: super Keyword
class Animal {
public Animal() {
System.out.println("I am an Animal");
}
@Override
public void eat() {
super.eat();
System.out.println("I eat dog food");
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.eat();
dog1.bark();
}
}
Output
I am an Animal
I am a dog
I can eat
I eat dog food
I can bark
Here, we have used the super keyword to call the constructor using super() . Also, we
have called the eat() method of Animal superclass using super.eat() .
Note the difference in the use of super while calling constructor and method. To learn
more, visit the super keyword.
138
Types of inheritance
• The most important use is the reusability of code. The code that is present in the
parent class doesn’t need to be written again in the child class.
139
140
Advantages and Disadvantages of Recursion
When a recursive call is made, new storage location for variables are allocated on
the stack. As, each recursive call returns, the old variables and parameters are
removed from the stack. Hence, recursion generally use more memory and are
generally slow.
On the other hand, recursive solution is much simpler and takes less time to write,
debug and maintain.
141
Lesson 8: Java Method Overriding
In this tutorial, we will learn about method overriding in Java with the help of
examples.
In the last tutorial, we learned about inheritance. Inheritance is an OOP property that
allows us to derive a new class (subclass) from an existing class (superclass). The
subclass inherits the attributes and methods of the superclass.
Now, if the same method is defined in both the superclass class and the subclass
class, then the method of the subclass class overrides the method of the superclass.
This is known as method overriding.
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
In the above program, the displayInfo() method is present in both the Animal
Notice the use of the @override annotation in our example. In Java, annotations are
the metadata that we used to provide information to the compiler. Here,
the @override annotation specifies the compiler that the method after this annotation
overrides the method of the superclass.
It is not mandatory to use @override . However, when we use this, the method should
follow all the rules of overriding. Otherwise, the compiler will generate an error.
• Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.
143
• We cannot override the method declared as final and static .
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
I am an animal.
I am a dog.
144
In the above example, the subclass Dog overrides the method displayInfo() of the
superclass Animal .
When we call the method displayInfo() using the d1 object of the Dog subclass, the
method inside the Dog subclass is called; the method inside the superclass is not
called.
Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to
call displayInfo() of the superclass.
It is important to note that constructors in Java are not inherited. Hence, there is no
such thing as constructor overriding in Java.
However, we can call the constructor of the superclass from its subclasses. For that,
we use super() .
The same method declared in the superclass and its subclasses can have different
access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide larger access
than the access specifier of the superclass. For example,
Suppose, a method myClass() in the superclass is declared protected . Then, the same
method myClass() in the subclass can be either public or protected , but not private .
class Animal {
protected void displayInfo() {
System.out.println("I am an animal.");
145
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
I am a dog.
In the above example, the subclass Dog overrides the method displayInfo() of the
superclass Animal .
Whenever we call displayInfo() using the d1 (object of the subclass), the method
inside the subclass is called.
Notice that, the displayInfo() is declared protected in the Animal superclass. The same
method has the public access specifier in the Dog subclass. This is possible because
the public provides larger access than the protected .
In Java, abstract classes are created to be the superclass of other classes. And, if a
class contains an abstract method, it is mandatory to override it.
We will learn more about abstract classes and overriding of abstract methods in later
tutorials.
146
147
Lesson 9: Java super
In this tutorial, we will learn about the super keyword in Java with the help of
examples.
2. To access attributes (fields) of the superclass if both superclass and subclass have
attributes with the same name.
If methods with the same name are defined in both superclass and subclass, the
method in the subclass overrides the method in the superclass. This is called method
overriding.
148
Example 1: Method overriding
class Animal {
// overridden method
public void display(){
System.out.println("I am an animal");
}
}
// overriding method
@Override
public void display(){
System.out.println("I am a dog");
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
Output
I am a dog
In this example, by making an object dog1 of Dog class, we can call its
method printMessage() which then executes the display() statement.
Since display() is defined in both the classes, the method of subclass Dog overrides
149
What if the overridden method of the superclass has to be called?
We use super.display() if the overridden method display() of superclass Animal needs
to be called.
Example 2: super to Call Superclass Method
class Animal {
// overridden method
public void display(){
System.out.println("I am an animal");
}
}
// overriding method
@Override
public void display(){
System.out.println("I am a dog");
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
Output
I am a dog
I am an animal
151
2. Access Attributes of the Superclass
The superclass and subclass can have attributes with the same name. We use
the super keyword to access the attribute of the superclass.
Example 3: Access superclass attribute
class Animal {
protected String type="animal";
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printType();
}
}
I am a mammal
I am an animal
In this example, we have defined the same instance field type in both the
superclass Animal and the subclass Dog .
We then created an object dog1 of the Dog class. Then, the printType() method is
called using this object.
Inside the printType() function,
• type refers to the attribute of the subclass Dog .
152
Hence, System.out.println("I am a " + type); prints I am a mammal .
class Animal {
System.out.println("I am a dog");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
153
}
}
Output
I am an animal
I am a dog
Here, when an object dog1 of Dog class is created, it automatically calls the default or
no-arg constructor of that class.
Inside the subclass constructor, the super() statement calls the constructor of the
superclass and executes the statements inside it. Hence, we get the output I am an
animal .
The flow of the program then returns back to the subclass constructor and executes
the remaining statements. Thus, I am a dog will be printed.
However, using super() is not compulsory. Even if super() is not used in the subclass
constructor, the compiler implicitly calls the default constructor of the superclass.
So, why use redundant code if compiler automatically invokes super()?
154
It is required if the parameterized constructor (a constructor that takes
arguments)of the superclass has to be called from the subclass constructor.
The parameterized super() must always be the first statement in the body of the
constructor of the subclass, otherwise, we get a compilation error.
Example 5: Call Parameterized Constructor Using super()
class Animal {
// parameterized constructor
Animal(String type) {
System.out.println("Type: "+type);
}
}
// default constructor
Dog() {
System.out.println("I am a dog");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Output
Type: Animal
I am a dog
155
The compiler can automatically call the no-arg constructor. However, it cannot call
parameterized constructors.
156
Java Abstract Class and Abstract
Methods
In this tutorial, we will learn about abstraction in Java. We will learn about Java
abstract classes and methods and how to use them in our program.
An abstract class is a class that cannot be instantiated (we cannot create objects of
an abstract class). In Java, we use the abstract keyword to declare an abstract class.
If we try to create objects of an abstract class, we will get a compilation error. For
example,
Though abstract classes cannot be instantiated, we can create subclasses from it.
We can create objects of subclasses to access members of the abstract class.
157
Java Abstract Method
We use the same keyword abstract to create abstract methods. An abstract method
is declared without an implementation. For example,
An abstract class can contain both abstract and non-abstract methods. Here's an
example.
158
}
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
I am an animal.
In the above example, we have created an abstract class Animal . We cannot create
objects of Animal . To access the displayInfo() of Animal , we have inherited a
subclass Dog of Animal .
Note: If the subclass is also declared abstract, it's not mandatory to override abstract
methods.
Example 2: Overriding Abstract Method
159
public void eat() {
System.out.println("I can eat.");
}
}
Bark bark.
I can eat.
In the above example, we have created an abstract class Animal . The class contains
an abstract method makeSound() and a non-abstract method eat() .
We have inherited a subclass Dog from the superclass Animal . Here, the
subclass Dog overrides the abstract method displayInfo() .
160
Animal() {
….
}
}
Here, we have used the super() inside the constructor of Dog to access the
constructor of the Animal .
Note that the super should always be the first statement of the subclass constructor.
The major advantage of hiding the working of the brake is that now the manufacturer
can implement brake differently for different motorbikes, however, what brake does
will be the same.
}
161
class Dog extends Animal {
public void makeSound() {
System.out.println("Bark bark.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.makeSound();
Bark bark
Meows
We cannot implement makeSound() in Animal in such a way that it can be correct for all
subclasses of Animal . So, the implementation of makeSound() in Animal is kept hidden.
In the above example, Dog makes its own implementation
of makeSound() and Cat makes its own implementation of makeSound() .
162
Key Points to Remember
• A subclass must override all abstract methods of an abstract class. However, if the
subclass is declared abstract, it's not mandatory to override abstract methods.
• We can access the static attributes and methods of an abstract class using the
reference of the abstract class. For example,
Animal.staticMethod();
Java Interface
In this tutorial, we will learn about Java interfaces. We will learn how to
implement interfaces and when to use them in detail with the help of examples.
interface Polygon {
public void getArea();
}
163
The getArea() method is a specification defined in the Polygon interface. All classes
that use this interface must implement the getArea() method.
An interface can include abstract methods and constants. For example,
interface Polygon {
public static final String color = "blue";
It is important to note that, all methods inside an interface are implicitly public and all
fields are implicitly public static final . Hence, it's not necessary to specify the
access specifier inside interfaces. For example, we can write the above code as
interface Polygon {
String color = "blue";
void getArea();
}
interface Polygon {
void getArea(int length, int breadth);
}
164
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output
In the above program, we have created an interface Polygon . The Polygon interface
has an abstract method getArea() .
This means that any class that implements Polygon must provide an implementation
for the getArea() method.
Notice that, the Rectangle class (which implements Polygon interface) has the
method getArea() with implementation.
Now that we know what interfaces are, let’s learn about why interfaces are used in
Java.
Interfaces provide specifications that a class (which implements it) must follow.
165
different for different polygons. Hence, the implementation of getArea() is
independent of one another.
Interfaces are also used to achieve multiple inheritance in Java. If a subclass is
inherited from two or more classes, it's multiple inheritance.
interface Line {
...
}
interface Polygon {
...
}
class Rectangle implements Line, Polygon{
...
}
With the release of Java 8, interfaces now can include static methods.
Similar to a class, we can access static methods of an interface using its references.
For example,
Polygon.staticMethod();
Also, interfaces support private methods with the release of Java 9. Now you can
use private methods and private static methods in interfaces.
166
Since you cannot instantiate interfaces, private methods are used as helper methods
that provide support to other methods in interfaces.
With the release of Java 8, methods with implementation (default methods) were
introduced inside an interface. Before that, all the methods were abstract in Java.
To declare default methods inside interfaces, we use the default keyword. For
example,
Let's take a scenario to understand why default methods are introduced in Java.
We can add the method in our interface easily without implementation. However,
that's not the end of the story. All our classes that implement that interface must
provide an implementation for the method.
If a large number of classes were implementing this interface, we need to track all
these classes and make changes in them. This is not only tedious but error-prone as
well.
To resolve this, Java introduced default methods. Default methods are inherited like
ordinary methods.
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea();
r1.getSides();
Output
168
In the above example, we have created an interface Polygon . Polygon has a default
method getSides() and an abstract method getArea() .
We have created another class Square that also implements Polygon . Here, Square only
interface Polygon {
void getArea();
169
}
class Main {
public static void main(String[] args) {
Triangle t1 = new Triangle(2, 3, 4);
Output
Area: 2.9047375096555625
Perimeter: 9
170
extends Keyword in Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is
used for extending interfaces. For example,
interface Line {
//members of Line interface
}
In the above example, the interface Polygon extends the Line interface. Now, if a class
implements Polygon , it should provide implementations for all abstract classes of
both Line and Polygon .
Note that an interface can extend multiple interfaces similar to a class implementing
multiple interfaces. For example,
interface A {
...
}
interface B {
...
}
Interface C extends A, B {
...
}
Java Polymorphism
In this tutorial, we will learn about polymorphism, different types of
polymorphism and how to implement them in Java with the help of examples.
171
The + operator in Java is used to perform two specific functions. When it is used with
numbers (integers and floating-point numbers), it performs addition.
int a = 5;
int b = 6;
int sum = a + b; // Output = 11
And when we use + operator with strings, it performs string concatenation. For
example,
Types of Polymorphism
• Run-time Polymorphism
• Compile-time Polymorphism
Run-time Polymorphism
Suppose the same method is created in the superclass and its subclasses. In this
case, the method that will be called depends upon the object used to call the method.
For example,
172
class Dog extends Animal {
@override
public void makeSound() {
System.out.println("Bark bark..");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.makeSound();
Bark bark…
Meow-meow...
In the above example, the method makeSound() has different implementations in two
different classes. When we run the program,
• the expression d1.makeSound() will call the method of Dog class. It is because d1 is an
object of the Dog class.
• the expression c1.makeSound() will call the method of Cat class. It is because c1 is an
object of the cat class.
173
The method that will be called is determined during the execution of the program.
Hence, method overriding is a run-time polymorphism.
Compile-time Polymorphism
Method Overloading
In a Java class, we can create methods with the same name if they differ in
parameters. For example,
class Demo {
public void displayPattern(){
for(int i = 0; i < 10; i++) {
System.out.print("*");
}
}
class Main {
public static void main(String[] args) {
Demo d1 = new Demo();
d1.displayPattern();
System.out.println("\n");
d1.displayPattern('#');
}
}
**********
##########
175
Java Method Overloading Vs Method Overriding
176
• Method overriding is performed at run-time whereas method overloading is
performed at compile-time.
Operator Overloading
Some operators in Java behave differently with different operands. For example,
The + operator in Java is used to perform two specific functions. When it is used with
numbers (integers and floating-point numbers), it performs addition. For example,
int a = 5;
int b = 6;
int sum = a + b; // Output = 11
And when we use + operator with strings, it performs string concatenation. For
example,
In languages like C++, we can define operators to work differently for different
operands. However, Java doesn’t support user-defined operator overloading.
Why Polymorphism?
Polymorphic Variables
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Main {
public static void main(String[] args) {
I am an animal.
I am a dog.
In the above example, we have created an object variable a1 of the Animal class.
Here, a1 is a polymorphic variable.
It is because,
Java Encapsulation
In this tutorial, you will learn about encapsulation and data hiding in Java with
the help of examples.
Java Encapsulation
Bundling similar fields and methods inside a class together also help in data hiding.
179
Encapsulating fields and Methods
In Java, we can bundle fields and methods that operate together inside a single
class. For example,
class Rectangle {
int length;
int breadth;
public void getArea() {}
}
In the above program, the method getArea() calculates the area of a rectangle. To
calculate the area, it needs length and breadth . Hence, the data
fields length , breadth and the method getArea() are kept together in
the Rectangle class.
Data hiding is a way of restricting the access of our data members by hiding the
implementation details.
Data hiding can be achieved with the help of access modifiers. In Java, there are four
access modifiers:
class Person {
private int age;
class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.setAge(24);
System.out.println("My age is " + p1.getAge());
}
}
Output
My age is 24
In the above example, we have a private field age . Since it is private, it cannot be
accessed from outside the class. In order to access age , we have
used public methods getAge() and setAge() . These methods are called getter and
setter methods.
B lo9ooooooo
If we try to access the age field from the Main class, we will get an error.
181
p1.age = 24; // error: age has private access in Person
Making age private allowed us to restrict unauthorized access from outside the class.
This is data hiding.
class Person {
protected String profession;
Output
I am a teacher
We have accessed these members from the Teacher class (which is a subclass
of Person ).
182
Why Encapsulation?
• In Java, encapsulation helps us to keep related fields and methods together, which
makes our code cleaner and easy to read.
• It helps to control the modification of our data fields. Consider a situation where we
want the age field in a class to be non-negative. Here we can make age private and
can apply logic inside the method setAge() . For example,
class Person {
private int age;
• The getter and setter methods provide read-only or write-only access to our class
fields. For example,
People often consider encapsulation as data hiding, but that’s not entirely true.
Encapsulation refers to the bundling of related fields and methods together. This
allows us to achieve data hiding. Encapsulation in itself is not data hiding.
183
184