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

Java Set2

Uploaded by

Jiju Abutelin Ja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Set2

Uploaded by

Jiju Abutelin Ja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 161

Java

JAVA - Introduction part2


FROM
Genesis coding School

Genesis Coding School An initiative by IT Professionalss


Java

Table of Contents

IDE for Jav

........................................................................................................................................................................ 4
IDE - Integrated Development Environment..............................................................................................5
Installing Eclipse.............................................................................................................................................7
Install Eclipse in Windows..........................................................................................................................8
Install Eclipse in Ubuntu/Linux.................................................................................................................22
Welcome to Eclipse......................................................................................................................................29
Welcome to Eclipse...................................................................................................................................30
Eclipse Window.........................................................................................................................................31
Eclipse Menus...........................................................................................................................................33
Views.........................................................................................................................................................35
Eclipse Workspace....................................................................................................................................37
Running A Programme..............................................................................................................................39
Java Conditional Operators 1.......................................................................................................................40
Conditional Operators..............................................................................................................................40
if statement..............................................................................................................................................42
if-else statement.......................................................................................................................................44
Java Conditional Operators 2.......................................................................................................................47
if-else-if statement...................................................................................................................................47
nested if statement..................................................................................................................................50
Switch statement..........................................................................................................................................53
Switch Statement in Java..........................................................................................................................53
Java for loop.................................................................................................................................................59
for loop.....................................................................................................................................................60
Simple For Loop........................................................................................................................................60
Enhanced For loop....................................................................................................................................62

1
Genesis Coding School An initiative by IT Professionals
Java

Nested For Loop........................................................................................................................................63


Java while loop.............................................................................................................................................65
Java while loop.........................................................................................................................................65
Java do while loop........................................................................................................................................70
do while loop............................................................................................................................................71
Java Break and Continue..............................................................................................................................76
Java Break and Continue..........................................................................................................................76
break;........................................................................................................................................................76
continue;...................................................................................................................................................80
Java Enum.....................................................................................................................................................83
Enum.........................................................................................................................................................83
Java Date and Time.......................................................................................................................................86
Date and Time...........................................................................................................................................87
Java Methods................................................................................................................................................95
Methods....................................................................................................................................................95
Types of Java methods.............................................................................................................................96
Creating Method.......................................................................................................................................97
Calling a Method.......................................................................................................................................99
Exceptions in Java.......................................................................................................................................103
Exception................................................................................................................................................104
Exception Hierarchy in java....................................................................................................................107
Exception Handling.................................................................................................................................108
Exception Handling in Java.........................................................................................................................110
Java try and catch...................................................................................................................................110
Try block..................................................................................................................................................110
Catch block..............................................................................................................................................111
Finally block............................................................................................................................................113
The throw keyword................................................................................................................................115
Object Oriented Programming...................................................................................................................118
Object Oriented Programming...............................................................................................................119
2
Genesis Coding School An initiative by IT Professionals
Java

Java Classes and Objects............................................................................................................................121


Classes.....................................................................................................................................................122
Objects....................................................................................................................................................125
Java Core Concepts of OOPs.......................................................................................................................128
Core Concepts of OOPS...........................................................................................................................128
Inheritance..............................................................................................................................................128
Types of Inheritance in Java...................................................................................................................132
Types of Inheritance in Java.......................................................................................................................132
Single Inheritance...................................................................................................................................133
Multi Level Inheritance...........................................................................................................................134
Hierarchical Inheritance.........................................................................................................................136
Inheritance and Interface...........................................................................................................................137
Interface..................................................................................................................................................138
Multiple Inheritance...............................................................................................................................140
Hybrid Inheritance..................................................................................................................................142
OOPS - Polymorphism................................................................................................................................143
Polymorphism in Java.............................................................................................................................144
Types of Polymorphism..........................................................................................................................147
Types of Polymorphism..............................................................................................................................147
Compile-time Polymorphism..................................................................................................................147
Run-time Polymorphism.........................................................................................................................151
Abstraction in Java......................................................................................................................................153
Abstraction.............................................................................................................................................153
Abstraction using Interface....................................................................................................................155
Abstract Class and Abstraction...................................................................................................................157
Abstract Class..........................................................................................................................................157
Abstract Method.....................................................................................................................................158
Abstraction using Abstract Class............................................................................................................161
Encapsulation in Java..................................................................................................................................163
Encapsulation..........................................................................................................................................164
3
Genesis Coding School An initiative by IT Professionals
Java

Access modifiers 1......................................................................................................................................168


Access modifiers.....................................................................................................................................168
Default access modifier..........................................................................................................................170
Private access modifier...........................................................................................................................172
Access modifiers 2......................................................................................................................................173
Protected Access Modifier......................................................................................................................173
Public access modifier............................................................................................................................175
Implementing Encapsulation and Getters & Setters..................................................................................177
Implementing Encapsulation..................................................................................................................177
Getter and Setter Methods.....................................................................................................................178
this keyword in java................................................................................................................................180

IDE for Jav

 IDE - Integrated Development Environment

4
Genesis Coding School An initiative by IT Professionals
Java

IDE - Integrated Development Environment

So far we've learnt to write and execute a Simple Java code.


But where did you write your codes, was that actually the real coding environment........?
Actually no!

Sublime is just like a notepad in your computer, or can say it's more like a sophisticated text editor
for code, markup etc

So what do we need. What's out there in the tech world for advanced Java coder. Yeah! it's IDE

5
Genesis Coding School An initiative by IT Professionals
Java

Integrated Development Environment

An integrated development environment is a software application that provides comprehensive


facilities to computer programmers for software development. An IDE normally consists of at least
a source code editor, build automation tools and a debugger.

Let me explain,

As you know a text editor is used for writing or modifying text/code. But we can't run our code
using Text editors.

And when we work in more complicated problems we need to see the output line by line as we
code.
It's not possible to open and execute the code using our primitive Command Prompt/Terminal
each time.

What if there was a COMPILE and RUN switch, that Compiles/Run the code within no time. Fun
Right??

Why do we use them?

For a software engineer like you, to build a large scale systems you might need technological
support at the point of typing the code. At that point IDE comes in and helps you to sort it out.
Most of the IDE's are capable of predicting the upcoming keywords as we code.

Also if some errors came up it's difficult to identify the real scenario by reading the error message

6
Genesis Coding School An initiative by IT Professionals
Java

from Command Prompt/Terminal. IDE's can help us solving the errors like typing mistakes,
method of implimentation errors etc.

The developers who are skilled in IDE can successfully understand, correct and improve large
software systems faster. Although IDE's are a little hard to master(in its's full capacity). But
compiling and running a code using IDE's are as simple as 1+1 = 2.

Now you are in the game. Let's see some IDE's used in Java programming.

 Eclipse
 NetBeans
 IntelliJ IDEA
 BlueJ
 jEdit
 DrJava etc

Even though there are a lot more IDE's for Java, The most used Java IDE's are Eclipse and
Netbeans. We will be studying Eclipse IDE for Java from now on.

Installing Eclipse

 Install Eclipse in Windows


 Install Eclipse in Ubuntu/Linux

7
Genesis Coding School An initiative by IT Professionals
Java

Install Eclipse in Windows

To download Eclipse goto the official website of Eclipse. And click the download button to
download the package.

The next page also has a download button. By clicking this you'll be able to download eclipse
executable into your pc.

8
Genesis Coding School An initiative by IT Professionals
Java

After successful completion of the download please double click the installer file to proceed the
installation. Then the installer will show us the available Eclipse Tools through the installer
windown. From that select Eclipse IDE for Enterprise Java Developers. We will be working with
this version of eclipse.

Look at the description of the Eclipse IDE for Enterprise Java Developers, See Tools for Enterprise
java developers and Web application. Here, it is the road to a "Web developer".

9
Genesis Coding School An initiative by IT Professionals
Java

Here is the last step of installation, Here you can see the version of JDK and the installation path
of the Eclipse. If you need you can change the installation directory. We recommend the default

10
Genesis Coding School An initiative by IT Professionals
Java

installation directory.

Then Click the Install button. It will take time and the installation time varies with the network and
processing speed of your PC.

Before starting the installation Eclipse will ask you to Accept the User Agreement. Accept it to
proceed the Installation.

11
Genesis Coding School An initiative by IT Professionals
Java

Also in between there will be prompts to accept certificates Eclipse.org click always accept
certification and Select All, them proceed.

12
Genesis Coding School An initiative by IT Professionals
Java

Tada!!!!...Here you go. Click Launch to start using Eclipse.

13
Genesis Coding School An initiative by IT Professionals
Java

Install Eclipse in Ubuntu/Linux

Using Terminal

Open the ubuntu Terminal and Run the update command given below.

sudo apt update

14
Genesis Coding School An initiative by IT Professionals
Java

Now we need to install the snap package into ubuntu to install eclipse through snap.

sudo apt install snapd

15
Genesis Coding School An initiative by IT Professionals
Java

Now final step, run this command to install eclipse through terminal using snap.

sudo snap install --classic eclipse

16
Genesis Coding School An initiative by IT Professionals
Java

Using Ubuntu Software Centre

Open ubuntu software center from Activities and search Eclipse. Click Eclipse to get into
installation page.

17
Genesis Coding School An initiative by IT Professionals
Java

Click the install button to Install Eclipse

18
Genesis Coding School An initiative by IT Professionals
Java

Either way after installation you can access Eclipse through the Activities in Ubuntu

Welcome to Eclipse

 Welcome to Eclipse
 Eclipse Window
 Eclipse Menus
 Views
 Eclipse Workspace
 Running A Programme

Welcome to Eclipse
Eclipse is one of the most popular open source Java IDEs available today.

Most Java developers use Eclipse more than any other Java tool available on the internet. The
19
Genesis Coding School An initiative by IT Professionals
Java

Eclipse Foundation allows development by providing the infrastructure, and a structured process
of development. The Eclipse Foundation has built its open source community and ecosystem of
products and services since 2001.

Eclipse for Java


Eclipse IDE (integrated development environment) for Java has been the leading development
environment with a market share of 65% as of today. It can be extended with an additional
software component. Eclipse calls these software components as plugins, which can grouped into
features. Many companies have extended Eclipse IDE on top of the Eclipse framework. It is also
available as IDE for other languages.

Basic concepts

 Workspace: This is at a physical location of file path where you store certain meta data of
development artefacts. Projects, source files, images, and other artefacts are stored either
inside or outside of your workspace.
 Views and editors: Eclipse offers views and editors to navigate and change content. A view
is used to work on a set of data, which is in a hierarchical structure. If data is changed via
view, the underlying data is directly changed.
 Eclipse project: This is an open source, configuration and binary file that is related to a
certain task. Eclipse project groups these files into a buildable and reusable units. These
projects can have natures assigned to it which describes describes the purpose of this
project.

20
Genesis Coding School An initiative by IT Professionals
Java

Eclipse Window
The major visible parts of an eclipse window are,

 Views
 Editors
 Menu Bar
 Toolbar

An eclipse perspective is the name given to an initial collection and arrangement of views and an
editor area.

A perspective has only one editor area in which multiple editors can be open. The editor area is
usually surrounded by multiple views. In general, editors are used to edit the project data and
views are used to view the project metadata. For example the package explorer shows the java

21
Genesis Coding School An initiative by IT Professionals
Java

files in the project and the java editor is used to edit a java file.

The eclipse window can contain multiple editors and views but only one of them is active at any
given point of time. The title bar of the active editor or view looks different from all the others.

The UI elements on the menu bar and tool bar represent commands that can be triggered by an
end user.

Eclipse Menus

 File menu
 Edit menu
 Source Menu
 Refactor Menu
 Navigate Menu
 Search Menu
 Project Menu
 Run Menu
 Window Menu
 Help Menu

22
Genesis Coding School An initiative by IT Professionals
Java

Sr.N Menu Name & Description


o
File

1 The File menu allows you to open files for editing, close editors, save editor content and rename
files. Among the other things, it also allows you to import and export workspace content and
shutdown Eclipse.
Edit
2
The Edit menu presents items like copy & paste.
3 Source

The Source menu is visible only when a java editor is open. It presents a number of useful menu

23
Genesis Coding School An initiative by IT Professionals
Java

items related to editing java source code.


Refractor

4
The goal of Java program refactoring is to make system-wide code changes without affecting the
behavior of the program. The Java tools provide assistance in easily refactoring code.
Navigate
5
The Navigate menu allows you to quickly locate resources and navigate to them.
Search

6
The Search menu presents items that allow you to search the workspace for files that contain
specific data.
Project
7
The menu items related to building a project can be found on the Project menu.
Run

8
The menu items on the Run menu allow you to start a program in the run mode or debug mode. It
also presents menu items that allow you to debug the code.
Window

9
The Window menu allows you to open and close views and perspectives. It also allows you to bring
up the Preferences dialog.
Help

10
The Help menu can be used to bring up the Help window, Eclipse Marketplace view or Install new
plug-ins. The about Eclipse menu item gives you version information.

24
Genesis Coding School An initiative by IT Professionals
Java

Views
Eclipse views allow users to see a graphical representation of project metadata. For example the
project navigator view presents a graphical representation of the folders and files associated with
a project and properties view presents a graphical representation of an element selected in
another view or editor.

An eclipse perspective can show any number of views and editors. All editor instances appear in a
single editor area, whereas views are placed inside view folders. A workbench window can display
any number of view folders. Each view folder can display one or more views.

25
Genesis Coding School An initiative by IT Professionals
Java

Eclipse Workspace
The eclipse workspace contains resources such as,

 Projects
 Files
 Folders

The workspace has a hierarchical structure. Projects are at the top level of the hierarchy and
inside them you can have files and folders. Plug-ins use an API provided by the resources plug-in

26
Genesis Coding School An initiative by IT Professionals
Java

to manage the resources in the workspace.

For creating a new file, goto File->New

27
Genesis Coding School An initiative by IT Professionals
Java

Running A Programme
For Running a program first we have to select a class.

Then The Run item on the Run menu can be used to Run the selected java class or to restart the
java application that was previously started.

Java Conditional Operators 1

 Conditional Operators
 if statement
 if-else statement

28
Genesis Coding School An initiative by IT Professionals
Java

Conditional Operators
Java uses boolean variables to evaluate conditions. The boolean values true and false are returned
when an expression is compared or evaluated. For example:

int a = 4;
boolean b = a == 4;

if (b) {
System.out.println("It's true!");
}

Of course we don't normally assign a conditional expression to a boolean. Normally, we just use
the short version:

int a = 4;

if (a == 4) {
System.out.println("Ohhh! So a is 4!");
}

This is how conditional operators evaluate the expression!!!!!!


OK.....Now let's look into different conditional operators in JAVA

 if statement
 if-else statement

29
Genesis Coding School An initiative by IT Professionals
Java

 if-else-if statement
 nested if statement

if statement
If statement consists a condition, followed by statement or a set of statements as shown below:
COPY

if (expression) {
// statements
}

Here expression is a boolean expression. A boolean expression returns either true or false.

 if the expression is evaluated to true, statement(s) inside the body of if (statements inside
parenthesis) are executed
 if the expression is evaluated to false, statement(s) inside the body of if are skipped from
execution

30
Genesis Coding School An initiative by IT Professionals
Java

This image will show how exactly an if statement executes:

Working of Java if statement


Example :

class genesis {
public static void main(String[] args) {

int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("Hello GENESIS");
}
System.out.println("JAVA from GENESIS");
}
}

Output :

31
Genesis Coding School An initiative by IT Professionals
Java

Hello GENESIS
JAVA from GENESIS

In the above example, we have a variable named number. Here, the test expression checks if the
number is greater than 0 (number > 0).

Since the number is greater than 0. So the test expression evaluates to true. Hence code inside
the body of if is executed.

Now, change the value of the number to a negative integer. Let's say -5.
Which is,

class genesis {
public static void main(String[] args) {

int number = -5;

// checks if number is greater than 0


if (number > 0) {
System.out.println("Hello Genesis");
}
System.out.println("JAVA from Genesis");
}
}

If we run the above program with the new value of the number, the output will be,

32
Genesis Coding School An initiative by IT Professionals
Java

Output :
JAVA from Genesis

Here, the value of number is less than 0. So, the test expression number > 0 evaluates to false.
Hence, the body of if is executed.

if-else statement

The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.

Syntax :

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Here, if statements are executed from the top towards the bottom. As soon as the
expression/condition is true, codes inside the body of that the if statement is executed. Then, the
control of the program jumps outside the if-else.

If expressions/condition are false, codes inside the body of else is executed.

33
Genesis Coding School An initiative by IT Professionals
Java

Example : To check if a number is true or false

public class IfElseExample {


public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}

Output :
odd number

Exercise

34
Genesis Coding School An initiative by IT Professionals
Java

Q: What will be the output of following program ?

public class temp


{
public static void main(String args[])
{
int x=1;
if(x)
System.out.println("True");
else
System.out.println("False");
}
}

a) True
b) False
c) Error

Java Conditional Operators 2

 if-else-if statement
 nested if statement

35
Genesis Coding School An initiative by IT Professionals
Java

if-else-if statement

In Java, we have an if...else...if ladder, that can be used to execute one block of code among
multiple other blocks.

Syntax :

if (expression1) {
// codes
}
else if(expression2) {
// codes
}
else if (expression3) {
// codes
}
.
.
else {
// codes
}

Here, if statements are executed from the top towards the bottom. As soon as the test expression
is true, codes inside the body of that the if statement is executed. Then, the control of the
program jumps outside the if-else-if ladder.

if test expression is false then else if 's condition is evaluated

36
Genesis Coding School An initiative by IT Professionals
Java

If all test expressions are false, codes inside the body of else if is executed.

Example :

class Ladder {
public static void main(String[] args) {

int number = 0;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}
else {
System.out.println("The number is 0.");
}
}
}

Output :
The number is 0.

37
Genesis Coding School An initiative by IT Professionals
Java

In the above example, we are checking whether the number is positive, negative or zero. Here, we
have two test expressions:

 number > 0 - checks if the number is greater than 0


 number < 0 - checks if the number is less than 0

Here, the value of number is 0. So both the test expression evaluates to false. Hence the
statement inside the body of else is executed.

nested if statement

In Java, it is also possible to if..else statements inside a if..else statement. It's called nested if...else
statement.

Example :
Here's a program to find largest of 3 numbers:

class Number {
public static void main(String[] args) {

// declaring double type variables


Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;

// checks if n1 is greater than or equal to n2


if (n1 >= n2) {
// if...else statement inside the if block

38
Genesis Coding School An initiative by IT Professionals
Java

// checks if n1 is greater than or equal to n3


if (n1 >= n3) {
largestNumber = n1;
}
else {
largestNumber = n3;
}
}
else {
// if..else statement inside else block
// checks if n2 is greater than or equal to n3
if (n2 >= n3) {
largestNumber = n2;
}
else {
largestNumber = n3;
}
}
System.out.println("The largest number is " + largestNumber);
}
}

Output:
The largest number is 4.5
Note: In the above programs, we have assigned the value of variables ourselves to make this
easier. However, in real-world applications, these values may come from user input data, log files,

39
Genesis Coding School An initiative by IT Professionals
Java

form submission, etc.

Ternary operator

Java provides a special operator called ternary operator, which is a kind of shorthand notation of
if...else statement.let's go through an example :
Example :

class Operator {
public static void main(String[] args) {

Double number = -5.5;


String result;

result = (number > 0.0) ? "positive" : "not positive";


System.out.println(number + " is " + result);
}
}

Output :
-5.5 is not positive

Exercise

40
Genesis Coding School An initiative by IT Professionals
Java

Q: The condition of a Java Ternary operator should evaluate to ________.


a) 1 or 0
b) true or false
c) TRUE or FALSE
d) None

Switch statement

 Switch Statement in Java

Switch Statement in Java

The switch statement is a multi-way branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression. Basically, the expression
can be byte, short, char, and int primitive data types. Beginning with JDK7, it also works with
enumerated types ( Enums in java), the String class and Wrapper classes.

41
Genesis Coding School An initiative by IT Professionals
Java

switch case flow chart

we have used the if..else..if ladder to execute a block of code among multiple blocks. However,
the syntax of if...else...if ladders are too long.Hence, we can use the switch statement as a
substitute for long if...else...if ladders. The use of switch statements makes our code more
42
Genesis Coding School An initiative by IT Professionals
Java

readable.

The syntax of the switch statement is:

switch (variable/expression) {
case value1:
// statements of case1
break;

case value2:
// statements of case2
break;

.. .. ...
.. .. ...

default:
// default statements
}

The switch statement evaluates the expression (mostly variable) and compares it with values (can
be expressions) of each case label.

Now, if the value matches a certain case label, then all the statements of the matching case label
are executed.

43
Genesis Coding School An initiative by IT Professionals
Java

For example, if the variable/expression is equal to value2. In this case, all statements of that
matching case (statements of case2) are executed.

Notice, the use of break statements in each case. The break statement is used to terminate the
execution of the switch statement.

It is important because if break is not used all the statements after the matching case are
executed in sequence until the end of the switch statement.

Example :

// Java program to demonstrate switch case


// with primitive(int) data type
public class GenesisAcademyExample1 {
public static void main(String[] args)
{
int day = 5;
String dayString;

// switch statement with int data type


switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;

44
Genesis Coding School An initiative by IT Professionals
Java

case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
break;
}
System.out.println(dayString);
}
}

Output :
Friday

45
Genesis Coding School An initiative by IT Professionals
Java

Explanation :
The integer day is initialised as day=5 and a string variable daySting is declared at the beginning.
Then we switch day to different cases from 1 to 7. Inside each cases we
assign Monday to Sunday respectively.
While executing the switch statement variable day will be equated with different cases. Since day
= 5, case 5 will be executed and the string daySting will be assigned
with Friday. System.out.println(dayString); will print Friday.

Example2 :

public class GenesisAcademyExample2 {


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

46
Genesis Coding School An initiative by IT Professionals
Java

Output :
Default: Value is: 2

Explanation :
If no cases matches with the expression inside switch, Then default: executes bydefault . Here int
num=2;. So none of these cases matches with num+2. Then default: executes.
(We will study break; and continue; in detail on the Java Break and Continue chapter)

Exercise

Q:Which is the alternative to SWITCH in Java language?


a) break, continue
b) for, while
c) if, else
d) goto, exit

Java for loop

 for loop
 Simple For Loop
 Enhanced For loop
 Nested For Loop

47
Genesis Coding School An initiative by IT Professionals
Java

for loop

for loop provides a concise way of writing the loop structure. Unlike other loops, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a
shorter, easy to debug structure of looping.

Simple For Loop

1. Initialization condition: Here, we initialize the variable in use. It marks the start of a for
loop. An already declared variable can be used or a variable can be declared, local to loop
only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the statements in the loop
body are executed.
48
Genesis Coding School An initiative by IT Professionals
Java

4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination:When the condition becomes false, the loop terminates marking the end
of its life cycle.

Syntax : simple for loop

for(initialization;condition;incr/decr){
//statement or code to be executed
}

Example of Simple For loop :

class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

Output :
The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7

49
Genesis Coding School An initiative by IT Professionals
Java

The value of i is: 6


The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

In the above program:


int i=1 is initialization expression
i>1 is condition(Boolean expression)
i–- Decrement operation

Enhanced For loop

The For-each or Enhanced For Loop is used to traverse array or collection in java. It is easier to
use than simple for loop because we don't need to increment value or use conditional expression.
It works on elements basis not index and returns element one by one in the defined variable.

Syntax : Enhanced for Loop

for(Type var:array){
//code to be executed
}

Example : Enhanced for Loop

50
Genesis Coding School An initiative by IT Professionals
Java

public class ForEachExample {


public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}

Output :
12
23
44
56
78

Nested For Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.

Example :

public class NestedForExample {

51
Genesis Coding School An initiative by IT Professionals
Java

public static void main(String[] args) {


//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}

Output :
11
12
13
21
22
23
31
32
33

Exercise

52
Genesis Coding School An initiative by IT Professionals
Java

Q: What is the output of the below Java code with a FOR loop?

for(int i=1; i<5; i++)


{
System.out.print(i +",");
}

a) 1,2,3,4
b) 1,2,3,4
c) 1,2,3,4,5
d) 1,2,3,4,5

Java while loop

 Java while loop

Java while loop

Java while loop is a control flow statement that allows code to be executed repeatedly based on a
given Boolean condition. The while loop can be thought of as a repeating if statement.
The image below will explain the way of processing while loop

53
Genesis Coding School An initiative by IT Professionals
Java

Step by step flow of execution

1. Control falls into the while loop.


2. The flow jumps to Condition
3. Condition is tested
o If Condition yields true, the flow goes into the Body.
o If Condition yields false, the flow goes outside the loop
4. The statements inside the body of the loop get executed.
5. Updation takes place
6. Control flows back to Step 2.
7. The do-while loop has ended and the flow has gone outside.

54
Genesis Coding School An initiative by IT Professionals
Java

Syntax :

while (test_expression)
{
// statements

update_expression;
}

Explanation :

Test Expression: In this expression we have to check the condition. If the condition evaluates to
true then we will execute the body of the loop and go to update expression. Otherwise, we will
exit from the while loop.

Update Expression: After executing the loop body, this expression increments/decrements the
loop variable by some value. Update expression is the one which lead the while loop expression's
execution forward. Just like increment/decrement in for loop.

Statements: Statements are the executable logic that we write inside the loop to iterate .

Example : while loop

public class WhileExample {


public static void main(String[] args) {
int i=1;

55
Genesis Coding School An initiative by IT Professionals
Java

while(i<=5){
System.out.println(i);
i++;
}
}
}

Output :
1
2
3
4
5

Example Explained
In this example, test expression is i<=5 and update expression is i++;. The variable int i =1, so
while loop executes till i = 5 and from i = 1 to i = 5 will be updated by the update expression i++;.
The logic inside the while loop will be executed as long as the loop runs.

Q: What is the output of the below Java program with a decrement operator and WHILE-loop?

int a=4;
while(a>0)

56
Genesis Coding School An initiative by IT Professionals
Java

{
System.out.print(a + " ");
a--;
}

a) 4 3 2 1
b) 3 2 1
c) Compiler error
d) None

Java do while loop

 do while loop

do while loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.

57
Genesis Coding School An initiative by IT Professionals
Java

Step by step flow of execution

1. Control falls into the do-while loop.


2. The statements inside the body of the loop get executed.
3. Updation takes place.
4. The flow jumps to Condition
5. Condition is tested.
o If Condition yields true, goto Step 6.
o If Condition yields false, the flow goes outside the loop
6. Flow goes back to Step 2.

58
Genesis Coding School An initiative by IT Professionals
Java

Syntax :

do
{
// statements
update_expression
}
while (test_expression);

Explenation :

Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of the loop and go to update expression. Otherwise, we will
exit from the while loop.

Update Expression: After executing the loop body, this expression increments/decrements the
loop variable by some value.

Statements: Statements are the executable logic that we write inside the loop to iterate .

Example : do while loop

public class DoWhileExample {


public static void main(String[] args) {
int i=1;

59
Genesis Coding School An initiative by IT Professionals
Java

do{
System.out.println(i);
i++;
}while(i<=5);
}

Output :
1
2
3
4
5

Example Explained
In this example, test expression is i<=5 and update expression is i++;. The text expressions won't
affect the first iteration because, The do while loop execute the code block once, before checking
if the condition is true. While the first execution the first update expression will execute and then
check if the test expression is true or false and the loop will continue until the test expression
become false.

Exercise

Q: What is the main difference between a WHILE and a DO-WHILE loop in Java?
a) WHILE loop executes the statements inside of it at least once even if the condition is false.
60
Genesis Coding School An initiative by IT Professionals
Java

b) DO-WHILE loop executes the statements inside of it at least once even if the condition is false.
c) WHILE loop is fast.
d) DO-WHILE loop is fast.

Q: What is the value of "age" in the below Java program with a DO-WHILE loop?

int age=20;
do
{
age++;
}while(age<20);
System.out.println(age);

a) 20
b) 21
c) Compiler error
d) None

Java Break and Continue

61
Genesis Coding School An initiative by IT Professionals
Java

 break;
 continue;

Java Break and Continue

While working with loops, it is sometimes desirable to skip some statements inside the loop or
terminate the loop immediately without checking the test expression. In such cases, break and
continue statements are used.

break;

The break statement in Java programming language has the following two usages ?

1. When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement (covered in the previous
chapter).

62
Genesis Coding School An initiative by IT Professionals
Java

Working of Java break Statement

Example : break inside a loop

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}

63
Genesis Coding School An initiative by IT Professionals
Java

}
}

Output :
10
20

Example : break with switch case


Lets take a look at the example program that we studied in the Switch statement chapter.

public class GenesisAcademyExample1 {


public static void main(String[] args)
{
int day = 5;
String dayString;

// switch statement with int data type


switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";

64
Genesis Coding School An initiative by IT Professionals
Java

break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
break;
}
System.out.println(dayString);
}
}

In switch case, the break statement is used to execute the statements of a single case statement.
If no break appears, the flow of control will fall through all the subsequent cases until a break is
reached or the closing curly brace '}' is reached. So in this example, after executing the case 5: the
flow of execution will go through all the cases below. It is a good programming practice to avoid

65
Genesis Coding School An initiative by IT Professionals
Java

unnecessary executions, so that we can reduce the time of execution.

continue;

The continue statement in Java skips the current iteration of a loop (for, while, do...while, etc) and
the control of the program moves to the end of the loop
OR
It causes the loop to immediately jump to the next iteration of the loop.

Working of Java continue Statement

Example : continue inside for loop

66
Genesis Coding School An initiative by IT Professionals
Java

public class GenesisAcademyExample {


public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}

Output :
1
2
3
4
6
7
8
9
10

Exercise

67
Genesis Coding School An initiative by IT Professionals
Java

Q: A BREAK statement inside a Loop like WHILE, FOR, DO WHILE and Enhanced-FOR causes the
program execution _____________ Loop.
a) Exit
b) Continuation with next iteration
c) Never exit
d) None

Q: A CONTINUE statement inside a Loop like WHILE, FOR, DO-WHILE and Enhanced-FOR causes
the program execution _____________
a) Skip
b) Skip present iteration and continue with next iteration of the loop
c) Exit
d) None

Java Enum

 Enum

Enum

A Java Enum is a special data type used to define collections of constants, methods etc. More
precisely, a Java enum type is a special kind of Java class which contains variables, methods and
constructors to it. The main objective of enum is to define our own data types(Enumerated Data
Types).
68
Genesis Coding School An initiative by IT Professionals
Java

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST), season (SPRING,
SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc. According to the Java naming conventions, we should have all constants in capital
letters. So, we have enum constants in capital letters. Also Enum types can’t have duplicate
constants.

To create an enum, use the enum keyword , and separate the constants with a comma. Note that
they should be in uppercase letters:

69
Genesis Coding School An initiative by IT Professionals
Java

enum Vehicle {
CAR,
BIKE,
BUS
}

Example

// enum declaration inside a class.


public class Test
{
enum Color
{
RED, GREEN, BLUE;
}

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Output :
RED

70
Genesis Coding School An initiative by IT Professionals
Java

Exercise

Q: Can you find out the error in the below code?

enum Enums
{
ONE, TWO, THREE, ONE, FOUR;
}

Java Date and Time

 Date and Time

71
Genesis Coding School An initiative by IT Professionals
Java

Date and Time

Java does not have a built-in Date class, so java provides the Date class available in java.util
package, this class encapsulates the current date and time.

The Date class supports two constructors as shown in the following table :

Sr.No. Constructor & Description


1 Date( )

This constructor initializes the object with the current date and time.
2 Date(long millisec)

This constructor accepts an argument that equals the number of milliseconds that have elapsed
since midnight, January 1, 1970

And the package includes many date and time classes. For example :

Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
72
Genesis Coding School An initiative by IT Professionals
Java

LocalTime Represents a time (hour, minute, second and milliseconds (HH-mm-ss-zzz))


LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss.zzz)
DateTimeFormatter Formatter for displaying and parsing date-time objects
ZonedDateTime represents the date with time and zone information. ZonedDateTime =
LocalDateTime + Zone Information.

Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method:
Example

import java.time.LocalDate; // import the LocalDate class

public class GenesisAcademyExample {


public static void main(String[] args) {
LocalDate currDate = LocalDate.now(); // Create a date object of type LocalDate
System.out.println(currDate); // To display the current date
}
}

The output will be:


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

73
Genesis Coding School An initiative by IT Professionals
Java

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

Display Current Time

To display the current time (hour, minute, second, and milliseconds), import the
java.time.LocalTime class, and use its now() method:
Example

import java.time.LocalTime; // import the LocalTime class

public class GenesisAcademyExample {


public static void main(String[] args) {
LocalTime currTime = LocalTime.now();// Create a object of type LocalTime
System.out.println(currTime);// To display the current time
}
}

The output will be:


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

74
Genesis Coding School An initiative by IT Professionals
Java

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

Display Current Date and Time

To display the current date and time, import the java.time.LocalDateTime class, and use its now()
method:
Example

import java.time.LocalDateTime; // import the LocalDateTime class

public class GenesisAcademyExample1 {


public static void main(String[] args) {
LocalDateTime currDateTime = LocalDateTime.now();
System.out.println(currDateTime);
}
}

The output will be:


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

75
Genesis Coding School An initiative by IT Professionals
Java

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

Formatting Date and Time

The "T" in the example above is used to separate the date from the time. You can use the
DateTimeFormatter class with the ofPattern() method in the same package to format or parse
date-time objects. The following example will remove both the "T" and milliseconds from the
date-time:
Example

import java.time.LocalDateTime; // Import the LocalDateTime class


import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class GenesisAcademyExample1 {


public static void main(String[] args) {
LocalDateTime currDateTime = LocalDateTime.now();
System.out.println("Before formatting: " + currDateTime);
DateTimeFormatter formatDateTime = DateTimeFormatter.ofPattern("dd-MM-yyyy
HH:mm:ss");

String formattedDate = currDateTime.format(formatDateTime);


System.out.println("After formatting: " + formattedDate);
}
}

76
Genesis Coding School An initiative by IT Professionals
Java

The output will be:


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

-----------------------------------------------------------------------------------
The ofPattern() method accepts all sorts of values, if you want to display the date and time in a
different format. For example:
yyyy-MM-dd >>"2000-01-15"
dd/MM/yyyy >>"15/01/2000"
dd-MMM-yyyy >>"15-jan-2000"
E, MMM dd yyyy >>"Sat, Sep 21 2000"

Example : dd-MMM-yyyy >>"2000-01-15"

import java.time.LocalDateTime; // Import the LocalDateTime class


import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class GenesisAcademyExample1 {


public static void main(String[] args) {

77
Genesis Coding School An initiative by IT Professionals
Java

LocalDateTime myDateObj = LocalDateTime.now();


System.out.println("Before Formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MMM-yyyy
HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);


System.out.println("After Formatting: " + formattedDate);
}
}

Output :
Before Formatting: 2020-05-25T03:34:38.720524
After Formatting: 25-May-2020 03:34:38

Example : dd/mm/yyyy "29/09/1988"

import java.time.LocalDateTime; // Import the LocalDateTime class


import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class GenesisAcademyExample1 {


public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before Formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);

78
Genesis Coding School An initiative by IT Professionals
Java

System.out.println("After Formatting: " + formattedDate);


}
}

Output :
Before Formatting: 2020-05-25T03:32:17.271922
After Formatting: 25/05/2020 03:32:17

Example : dd-mm-yyyy "29-Sep-1988"

import java.time.LocalDateTime; // Import the LocalDateTime class


import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class GenesisAcademyExample1 {


public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);


System.out.println("After formatting: " + formattedDate);
}
}

Output :

79
Genesis Coding School An initiative by IT Professionals
Java

Before Formatting: 2020-05-25T03:24:20.184709


After Formatting: 25-05-2020 03:24:20

Java Methods

 Methods
 Types of Java methods
 Creating Method
 Calling a Method

Methods

In mathematics, we might have studied about functions. For example, f(x) = x+x is a function that
returns a doubled value of x.

If x = 2, then f(2) = 4
If x = 3, f(3) = 6

Similarly, in computer programming, a function is a block of code that performs a specific task.

80
Genesis Coding School An initiative by IT Professionals
Java

In object-oriented programming, the method is another name used for function. Methods are
bound to a class and they define the behavior of a class.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

Types of Java methods

Depending on whether a method is defined by the user, or available in the standard library, there
are two types of methods in Java:

 Standard Library Methods


 User-defined Methods

81
Genesis Coding School An initiative by IT Professionals
Java

Standard Library Methods

The Standard library methods are built-in methods in Java that are readily available for use. These
standard libraries come along with the Java Class Library that is present in a Java archive (*.jar)
file with JVM and JRE.
Example : print() method comes under java.io.PrintSteam which prints the string that is written
within the quotation.

User-defined Methods

We can also create methods of our own choice to perform some task. Such methods are called
user-defined methods.

Creating Method

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}

 Modifier : Defines access type of the method i.e. from where it can be accessed in your
application.
82
Genesis Coding School An initiative by IT Professionals
Java

 Return Type : The data type of the value returned by the method or void if does not return
a value.
 Name of Method : the rules for field names apply to method names as well, but the
convention is a little different.
 Parameter List : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
 Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

Example : Creating a method

public int methodName(int a, int b) {


// body

83
Genesis Coding School An initiative by IT Professionals
Java

 public static : Modifier


 int : Return Type
 methodName : Name of the Method
 int a, int b : list of parameters

Example : Method with a body

/** the snippet returns the minimum between two numbers */


public int sum(int n1, int n2) {
int sum;
sum = n1 + n2;
return sum; //returns the value ar the variable sum into the method call
}

Calling a Method

Now that we know how to define methods, we need to learn to use them. For that, we have to
call the method.

sum();

This statement calls sum(); method that was declared earlier.

84
Genesis Coding School An initiative by IT Professionals
Java

Methods won't be going to perform anything until and unless you call them on a specific part of
your program to do some action. In other words, to use method(s), programmers should call them
by the method name. Two approaches are there to call a method. One, where a method returns a
value and the other where methods do not return anything (i.e., no return value).

Example : Methods

public class GenesisAcademyExample{


public int sum(int n1, int n2) {
int sum;
sum = n1 + n2;
return sum; //returns the value ar the variable sum into the method call
}
public static void main(String argu[]) {
GenesisAcademyExample s = new GenesisAcademyExample ();
System.out.println(s.sum(3,4));
}

85
Genesis Coding School An initiative by IT Professionals
Java

Output :
7

Call By Value

Call by Value means calling a method with a parameter as value. Through this, the argument value
is passed to the parameter.

While Call by Reference means calling a method with a parameter as a reference. Through this,
the argument reference is passed to the parameter.

In call by value, the modification done to the parameter passed does not reflect in the caller's
scope while in the call by reference, the modification done to the parameter passed are persistent
and changes are reflected in the caller's scope.

86
Genesis Coding School An initiative by IT Professionals
Java

Call By Reference

Java uses only call by value while passing reference variables. It creates a copy of references and
passes them as valuable to the methods. As reference points to same address of object, creating a
copy of reference is of no harm. But if new object is assigned to reference it will not be reflected.

In pass by reference, the formal parameter is just an alias to the actual parameter. It refers to the
actual argument. Any changes done to the formal argument will reflect in actual argument and
vice versa.

Exceptions in Java

 Exception
 Exception Hierarchy in java
 Exception Handling

87
Genesis Coding School An initiative by IT Professionals
Java

Exception

An exception is an unwanted or unexpected event, which occurs during the execution of a


program i.e at run time, that disrupts the normal flow of the program’s instructions.

An exception can occur for many reasons. Some of them are:

1. Invalid user input


2. Device failure
3. Loss of network connection
4. Physical limitations (out of disk memory)
5. Code errors
6. Opening an unavailable file

88
Genesis Coding School An initiative by IT Professionals
Java

ERRORS and EXCEPTION

Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.

Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object.

It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.

89
Genesis Coding School An initiative by IT Professionals
Java

Exception Hierarchy in java

1. RuntimeException

A runtime exception happens due to a programming error. They are also known as
unchecked exceptions.

2. IOException

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.

90
Genesis Coding School An initiative by IT Professionals
Java

We will learn how to handle these exceptions in this chapter.

Exception Handling

Default Exception Handling by JVM

Whenever inside a method, if an exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system(JVM). The exception object contains
name and description of the exception, and current state of the program where exception has
occurred. Creating the Exception Object and handling it to the run-time system is called throwing
an Exception.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.


Keywor Description
d
try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether

91
Genesis Coding School An initiative by IT Professionals
Java

an exception is handled or not.


throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Exercise

Q: When does Exceptions in Java arises in code sequence?


a) Run Time
b) Compilation Time
c) Can Occur Any Time
d) None of the mentioned

Exception Handling in Java

 Java try and catch


 Try block
 Catch block
 Finally block
 The throw keyword

92
Genesis Coding School An initiative by IT Professionals
Java

Java try and catch

Try block

The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in associated try block. A try
block must be followed by catch blocks or finally block or both.

Syntax : try block


COPY

try{
//statements that may cause an exception
}

While writing a program, if you think that certain statements in a program can throw a exception,
enclosed them in try block and handle that exception.

Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single try
block can have several catch blocks associated with it. You can catch different exceptions in
different catch blocks. When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes. For example if an arithmetic exception occurs in try
block then the statements enclosed in catch block for arithmetic exception executes.
93
Genesis Coding School An initiative by IT Professionals
Java

Syntax : try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))?
{
//error handling code
}

Example :

public class GenesisAcademyExample {


public static void main(String[ ] args) {
int[] myExample = {1, 2, 3};
System.out.println(myExample[8]); // error!
}
}

Output :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at GenesisAcademyExample.main(GenesisAcademyExample.java:4)

Since myExample[8] does not exists, exception occurs. This exception was handled by the JVM

94
Genesis Coding School An initiative by IT Professionals
Java

itself. If we want to handle the exception such as show a custom message in the output console
when the exception occurs, then we can use try...catch to catch the error and execute some code
to handle it:

public class GenesisAcademyExample {


public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[8]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :
Something went wrong.

Finally block

A finally block contains all the crucial statements that must be executed whether exception occurs
or not. The statements present in this block will always execute regardless of whether exception
occurs in try block or not.

95
Genesis Coding School An initiative by IT Professionals
Java

Syntax : Finally block

try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}

Example :
COPY

public class GenesisAcademyExample


{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}

finally{

96
Genesis Coding School An initiative by IT Professionals
Java

System.out.println("The 'try catch' is finished.");


}
System.out.println("Out of try-catch-finally");
}
}

Output :
Number should not be divided by zero
This is finally block
Out of try-catch-finally

The throw keyword

In Java we have already defined exception classes such as ArithmeticException,


NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger
on different conditions. For example when we divide a number by zero, this triggers
ArithmeticException, when we try to access the array element out of its bounds then we get
ArrayIndexOutOfBoundsException.

We can define our own set of conditions or rules and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException when we divide number by 5, or any
other numbers, what we need to do is just set the condition and throw any exception using throw
keyword.

97
Genesis Coding School An initiative by IT Professionals
Java

The throw statement allows you to create a custom error.

Syntax : throw keyword

throw new exception_class("error message");

for example:

throw new ArithmeticException("dividing a number by 5 is not allowed in this program");

Example :

public class GenesisAcademyExample {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

98
Genesis Coding School An initiative by IT Professionals
Java

Output :
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18
years old.
at MyClass.checkAge(MyClass.java:4)
at MyClass.main(MyClass.java:12)

And if age was 20

Example :

public class GenesisAcademyExample {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(20); // Set age to 20 (which is above 18...)
}
}

99
Genesis Coding School An initiative by IT Professionals
Java

Output :
Access granted - You are old enough!

Exercise

Q: Exception generated by try block is caught by ____________ block.


a) catch
b) throw
c) throws
d) finally

Object Oriented Programming

 Object Oriented Programming

100
Genesis Coding School An initiative by IT Professionals
Java

Object Oriented Programming

Object-oriented programming System(OOPs) is a programming paradigm based on the concept of


“objects” that contain data and methods. The primary purpose of object-oriented programming is
to increase the flexibility and maintainability of programs.

Object-oriented programming aims to implement real-world entities like inheritance, hiding,


polymorphism etc in programming. The main aim of OOP is to bind together the data and the
101
Genesis Coding School An initiative by IT Professionals
Java

functions that operate on them so that no other part of the code can access this data except that
function.

The basic concept of OOPs is to create objects, re-use them throughout the program, and
manipulate these objects to get results. We will cover each and every feature of OOPs in detail so
that you won’t face any difficultly understanding OOPs Concepts.

Object Oriented Programming popularly known as OOP, is used in modern programming


languages like Java. Core OOPS concepts are :

1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

1) Class

The class is a group of similar entities. It is only an logical component and not the physical entity.
For example, if you had a class called “Vehicle” it could have objects like Car, Bike, Scooter, etc. Its
properties(data) can be price and speed of these vehicles. While the methods may be performed
with these vehicles are driving, reverse, braking etc.

102
Genesis Coding School An initiative by IT Professionals
Java

2) Object

An object can be defined as an instance of a class, and there can be multiple instances of a class in
a program. An Object contains both the data and the function, which operates on the data. For
example - if we have a class Vehicle and we've created an object Car of Vehicle, then our object
Car can have the properties price and speed, and the methods driving, reverse, braking etc.

We will study Class and Object in detail at the next chapter....

Java Classes and Objects

 Classes
 Objects

103
Genesis Coding School An initiative by IT Professionals
Java

Classes

A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type.

 It is a user defined data type which serves as a blueprint for an object.


 It is a logical entity i.e. no storage is assigned when we define a class.
 A single class can be used to create multiple objects.
 A class describes the contents of the objects that belong to it.

104
Genesis Coding School An initiative by IT Professionals
Java

Following is a sample of a class :

Example

public class Car{


Private String _color;
Private String _model;
Private String _makeYear;
Private String _fuelType;

public void Start() {


}

public void Stop() {


}

public void Accelerate() {


}
}

105
Genesis Coding School An initiative by IT Professionals
Java

In the above example we have our Car Class having 4


variables color, model, makeYear and fuelType. And have 3
methods Start(), Stop() and Accelerate(). So by using the Car Class we can represent real world
cars in our programme. So the main advantage of Classes and Objects are to represent real world
examples in our projects, so that we can easily relate real world and virtual world.

Syntax to declare a class:

class Class_name{
attribute_lists;
method_definitions;
}

106
Genesis Coding School An initiative by IT Professionals
Java

Objects

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An object
consists of,

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


object.
 Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
 Identity : It gives a unique name to an object and enables one object to interact with other
objects.

If we create an object alto of class Car then alto can represent a real world Car. The state of the
real world car will be represented by the attributes color, model, makeYear and fuelType.
The Behavior of the class can be represented by the methods, in our
case Start(), Stop() and Accelerate(). And finally identity of our object of Class Car is the name of
the object itself, which is alto.

Syntax : to create an Object

Car alto= new Car ();

107
Genesis Coding School An initiative by IT Professionals
Java

Example :
// Class Declaration

class Lamp {

// Attributes
boolean isOn;

// method 1
void turnOn() {
// initialize variable with value true
isOn = true;
System.out.println("Light is on");
}

// method 1
void turnOff() {
// initialize variable with value false
isOn = false;
System.out.println("Light is off");
}
}

class Main {
public static void main(String[] args) {

108
Genesis Coding School An initiative by IT Professionals
Java

// create objects l1 and l2


Lamp l1 = new Lamp();
Lamp l2 = new Lamp();

// call methods turnOn() and turnOff()


l1.turnOn();
l2.turnOff();
}
}

Output :
Light is on
Light is off

After carefully reading these notes try assuming a Class Animal and findout the
possible States and Behaviors of the Class Animal.

Excercise

Q: Which of these class is superclass of every class in Java?


a) String class
b) Object class
c) Abstract class
d) ArrayList class

109
Genesis Coding School An initiative by IT Professionals
Java

Java Core Concepts of OOPs

 Core Concepts of OOPS


 Inheritance
 Types of Inheritance in Java

Core Concepts of OOPS

OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming. They are
an abstraction, encapsulation, inheritance, and polymorphism. Grasping them is key to
understanding how Java works. Basically, Java OOP concepts let us create working methods and
variables, then re-use all or part of them without compromising security.

Inheritance

Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the
parent object. It’s creating a parent-child relationship between two classes. It offers robust and
natural mechanism for organizing and structure of any software.Inheritance in Java is a
mechanism in which one object acquires all the properties and behaviors of a parent object. It is
an important part of OOPs (Object Oriented programming system).

Inheritance in java is just like children inherits qualities from their parents. The child will get
selected qualities from their parents. Not all qualities, only selected properties get inherited.

110
Genesis Coding School An initiative by IT Professionals
Java

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
IS-A Relationship : It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is
a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a
House.

We use inheritance in java to achieve Method Overriding and Code Reusability.

111
Genesis Coding School An initiative by IT Professionals
Java

Important terminologies in Inheritance :

1. Super Class: The class whose features are inherited is known as super class(or a base class
or a parent class).
2. Sub Class: The class that inherits the other class is known as sub class(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.
3. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.

Syntax of Java Inheritance :

class Subclass-name extends Superclass-name


{
//methods and fields
}

Example: In below example of inheritance, class Principal is a base class/parent class, class
Teacher is a derived/child class which extends Principal class.

class Principal{
int salary=30000;
}
class Teacher extends Principal{
int bonus=18000;
public static void main(String args[]){
112
Genesis Coding School An initiative by IT Professionals
Java

Teacher t=new Teacher();


System.out.println("Principal's salary is:"+t.salary);
System.out.println("Bonus of Teacher is:"+t.bonus);
}
}

Output :
Principal's salary is:30000
Bonus of Teacher is:18000

Types of Inheritance in Java

There are 5 different types of inheritance in JAVA.

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Through Interfaces)
5. Hybrid Inheritance(Through Interfaces)

Types of Inheritance in Java

 Single Inheritance
113
Genesis Coding School An initiative by IT Professionals
Java

 Multi Level Inheritance


 Hierarchical Inheritance

Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. In image below, the class A
serves as a base class for the derived class B.

In the example below the Teacher class is inherited from Principal class. So Single Inheritance,
subclass derived from the superclass.

class Principal{ //base class


int salary=30000;
}
class Teacher extends Principal{ //derived class extends/inherits from base class
int bonus=18000;
public static void main(String args[]){
Teacher t=new Principal();
System.out.println("Principal's salary is:"+t.salary); //printing base class
attribute/variable(salary) using derived class object
System.out.println("Bonus of Teacher is:"+t.bonus);
114
Genesis Coding School An initiative by IT Professionals
Java

}
}

Output :
Principal's salary is:30000
Bonus of Teacher is:18000

Multi Level Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived
class also act as the base class to other class. In below image, the class A serves as a base class for
the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.

Simply, a derived class is created from another derived class is called Multi Level Inheritance.
For example, in our previous example Teacher Class was inherited from from Principal Class. Lets
Extend our Teacher Class towards a new Student Class so that we can achieve Multi Level
115
Genesis Coding School An initiative by IT Professionals
Java

Inheritance.

class Principal{ //base class


int salary=30000;
}
class Teacher extends Principal{ //derived class extends from base class
int bonus=18000;
}
class Student extends Teacher{ //inherited from a derived class
int scholarship=5000;
}
public class GenesisAcademyExample {
public static void main(String args[]){
Student s=new Student();
System.out.println("Principal's salary is:"+s.salary);
System.out.println("Bonus of Teacher is:"+s.bonus);
System.out.println("Scholarship for Student is:"+s.scholarship);
}
}

Output :
Principal's salary is:30000
Bonus of Teacher is:18000
Scholarship for Student is:5000

116
Genesis Coding School An initiative by IT Professionals
Java

Hierarchical Inheritance

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
image given below, there are three derived classes inherited from a single base class, so there is
hierarchical inheritance.

Example :

class Principal{ //base class


int salary=30000;
}
class Teacher extends Principal{ //derived class extends/inherits from base class
int bonus=18000;
}
class Student extends Principal{
int scholarship=5000;
}
public class GenesisAcademyExample {
public static void main(String args[]){
Teacher t=new Teacher();
Student s=new Student();
117
Genesis Coding School An initiative by IT Professionals
Java

System.out.println("Principal's salary is:"+t.salary);


System.out.println("Principal's salary is:"+s.salary);
}
}

Output :
Principal's salary is:30000
Principal's salary is:30000

There is two more types of inheritance, Multiple Inheritance and Hybrid Inheritance. We will
discuss them in the next chapter

Inheritance and Interface

 Interface
 Multiple Inheritance
 Hybrid Inheritance

118
Genesis Coding School An initiative by IT Professionals
Java

Interface

An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods(methods does not have a body). A class implements an interface, thereby inheriting the
abstract methods of the interface.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors
of an object. And an interface contains behaviors that a class implements.

119
Genesis Coding School An initiative by IT Professionals
Java

Example

// interface
interface Vehicle{
public void start(); // interface method (does not have a body)
public void stop(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform some specific behaviors of the interface. If a class does not define all the behaviors of the
interface, the class must declare itself as abstract.

Example

interface Vehicle{
public void start();
public void stop();
}

120
Genesis Coding School An initiative by IT Professionals
Java

public class Car implements Vehicle{

public void start() {


System.out.println("Vehicle Starts");
}

public void stop() {


System.out.println("Vehicle stop");
}
public static void main(String args[]) {
Car m = new Car ();
m.start();
m.stop();
}
}

Output :
Vehicle Starts
Vehicle stop

Multiple Inheritance

When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance.

121
Genesis Coding School An initiative by IT Professionals
Java

Java doesn’t allow multiple inheritance. The problem occurs when there exist methods with same
signature in both the super classes and subclass. On calling the method, the compiler cannot
determine which class method to be called and even on calling which class method gets the
priority.

Example :

interface fuelVehicle{
void fuel();
}
interface electricVehicle{
void electric();
}
class Vehicle implements fuelVehicle, electricVehicle{
public void fuel() {
System.out.println("Fuel Vehicle");
}
122
Genesis Coding School An initiative by IT Professionals
Java

public void electric() {


System.out.println("Electric Vehicle");
}
}
public class GenesisAcademyExample {
public static void main(String args[]) {
Vehicle a = new Vehicle();
a.fuel();
a.electric();
}
}

Output :
Fuel Vehicle
Electric Vehicle

Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple
inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can
achieve hybrid inheritance only through Interfaces.

123
Genesis Coding School An initiative by IT Professionals
Java

In the above image we can split it into two parts,

 Class B and C inherits the superclass A


 Class D inherits both B and C

OOPS - Polymorphism

 Polymorphism in Java
 Types of Polymorphism

Polymorphism in Java

All living beings can make sound in one way or another. So the sound is a common quality.

124
Genesis Coding School An initiative by IT Professionals
Java

Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance(like living beings class can have subclasses like dogs, cats etc). We can
define polymorphism as the ability of a message to be displayed in more than one form.

125
Genesis Coding School An initiative by IT Professionals
Java

When compared to a real time example, a child at the same time can have different characteristic.
Like a child, at the same time is a student at school, at home behave like a son etc. So the same
person posses different behaviour in different situations. This is called polymorphism.

For example, think of a superclass called vehicle that has a method called horn() and sound().
Subclasses of Vehicle could be Car, Bike, Bus, Taxi- And they also have their own implementation
of vehicle horn and sound. This is where we use polymorphism.In this case the subclasses(car,bus
etc.) have properties same as vehicle but the can behave in different ways such as all the
vehicles(car, bus etc.) can have same type of horn as well as different type. That depends upon
the characteristics of that subclass.

Let's look into a example of polymorphism which is implemented by the Java itself. The + operator
in Java is used to perform two specific functions. When it is used with numbers (integers and

126
Genesis Coding School An initiative by IT Professionals
Java

floating-point numbers), it performs addition.

int a = 10;
int b = 5;
int sum = a + b;

Output :
15

And when we use + operator with strings, it performs string concatenation. This is
Called Operator Overloading. In languages like C++, we can define operators to work differently
for different operands. However, Java doesn’t support user-defined operator overloading.

String firstName = "Genesis";


String lastName = "Academy";
name = firstName + lastName;

Output :
GenesisAcademy

So + operator behave according to the situation. Which is a type of Polymorphism.

127
Genesis Coding School An initiative by IT Professionals
Java

Types of Polymorphism

In Java, Polymorphism can be divided into two types:

 Compile-time Polymorphism
 Run-time Polymorphism

Types of Polymorphism

 Compile-time Polymorphism
 Run-time Polymorphism

Compile-time Polymorphism

Polymorphism that is resolved during compiling is known as Compile-time Polymorphism. Method


overloading is an example of compile time polymorphism or Static polymorphism or Early binding.
( Same method is overridden with different signature in same class)

Method Overloading

Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different.

128
Genesis Coding School An initiative by IT Professionals
Java

If we have to perform only one operation, having the same name of the methods increases the
readability of the program. Suppose you have to perform addition of the given numbers but there
can be any number of arguments(ie, method can accept any number of parameter), if you write
the method such as sum(int,int) for two parameters, and sum2(int,int,int) for three parameters
then it may be difficult for you as well as other programmers to understand the behavior of the
method because its name differs. So, we perform method overloading to figure out the program
quickly.

It is similar to constructor overloading in Java, that allows a class to have more than one
constructor having different argument lists. We will study Constructors and Constructor
overloading later. Just keep this in mind : Constructor is a special type of method with
method_name same as Class_name.

129
Genesis Coding School An initiative by IT Professionals
Java

Example : changing number of arguments

class GenesisAcademyExample {
void sum(int a,int b) //sum with 2 arguments
{
System.out.println(a+b);
}
void sum(int a,int b,int c){ //sum with 3 arguments
System.out.println(a+b+c);
}

public static void main(String args[]){


GenesisAcademyExample obj=new GenesisAcademyExample();
obj.sum(10,10,10);
obj.sum(20,20);

}
}

Output :
30
40

Example : changing the data type

class GenesisAcademyExample {

130
Genesis Coding School An initiative by IT Professionals
Java

void sum(int a,int b){ //sum with 2 int arguments


System.out.println(a+b);
}
void sum(double a,double b){ //sum with 2 double arguments
System.out.println(a+b);
}

public static void main(String args[]){


GenesisAcademyExample obj=new GenesisAcademyExample();
obj.sum(6.5,7.5);
obj.sum(15,25);

}
}

Output :
14.0
40

In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity.

Run-time Polymorphism

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the

131
Genesis Coding School An initiative by IT Professionals
Java

overridden method is resolved at Runtime. 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. Its also called as Dynamic Polymorphism or Late Binding. ( Same method is
overridden with same signature in different classes.)
This type of polymorphism is achieved by Method Overriding.

Method Overriding

In any object-oriented programming language, Overriding is a feature that allows a subclass or


child class to provide a specific implementation of a method that is already provided by one of its
super-classes or parent classes.

When a method in a subclass has the same name, same parameters or signature, and same return
type as a method in its super-class, then the method in the subclass is said to override the method
in the super-class.

Example :

class BaseClass{
public void myMethod(){
System.out.println("This is Overridden Method");
}
}
public class DerivedClass extends BaseClass{

132
Genesis Coding School An initiative by IT Professionals
Java

public void myMethod(){


System.out.println("This is Overriding Method");
}
public static void main(String args[]){
BaseClass obj = new DerivedClass();
obj.myMethod();
}
}

Output :
This is Overriding Method

Overloading can happen in same class as well as parent-child class relationship whereas
overriding happens only in an inheritance relationship.

Abstraction in Java

 Abstraction
 Abstraction using Interface

Abstraction

An abstraction is an act of representing essential features without including background details. It

133
Genesis Coding School An initiative by IT Professionals
Java

is a technique of creating a new data type that is suited for a specific application.

Data Abstraction only the essential details are displayed to the user. The non-essentials units are
not displayed to the user. In the below image, a car is viewed as a car rather than its individual
components. This is the basic concept of Abstraction.

134
Genesis Coding School An initiative by IT Professionals
Java

While discussing Data Abstraction in a more technical way, Abstraction is a process of hiding the
implementation from the user, only the functionality is exposed here. So you are aware only of
what the application does, not how it does it.

Example : When you log into your email, compose and send a mail. Again there is a whole lot of
background processing involved, verifying the recipient, sending request to the email server,
sending your email. Here you are only interested in composing and clicking on the send button.
What really happens when you click on the send button, is hidden from you. Hope you understand
the concept thoroughly.

135
Genesis Coding School An initiative by IT Professionals
Java

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

Abstraction using Interface

Example : Abstraction using Interface

interface ClassRoom{
void display();
}
class Bench implements ClassRoom{
public void display() {
System.out.println("This is a display method of the Bench class");
}
}
class Chair implements ClassRoom{
public void display() {
System.out.println("This is a display method of the Chair class");
}
}
public class GenesisAcademyExample {
public static void main(String args[]) {
ClassRoom obj1 = new Bench();
obj1.display();
ClassRoom obj2 = new Chair();

136
Genesis Coding School An initiative by IT Professionals
Java

obj2.display();
}
}

Output :
This is a display method of the Bench class
This is a display method of the Chair class

Interface with abstract methods is not necessary to define abstraction. interface is purely
abstract(Since the methods inside interface does not have any body) and hides the details of
implementation.

Level of Abstraction

 Abstract class (0 to 100%)


 Interface (100%)

We will study Abstraction using abstract class in the next chapter.

Abstract Class and Abstraction

 Abstract Class
 Abstract Method
 Abstraction using Abstract Class
137
Genesis Coding School An initiative by IT Professionals
Java

Abstract Class

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.

Syntax :

abstract class Class_Name {


//attributes and methods
}

Though abstract classes cannot create objects. , we can create subclasses from it. We can create
objects of subclasses to access members of the abstract class.

Before we learn about abstract class and abstraction using abstract class in detail, we need to
understand abstract methods first.

Abstract Method

We can use the same keyword abstract to create a abstract methods. An abstract method is
declared without an implementation(abstract method ). Only an abstract class can contain
abstract methods.

Example : Declaration of an abstract class

138
Genesis Coding School An initiative by IT Professionals
Java

abstract void start();

Here, start() is an abstract method. The body of start() is replaced by ; . An abstract class can
contain both abstract and non-abstract methods.

Example : Abstract Class

abstract class Vehicle {


public void start() {
System.out.println(“horn blown”);
}
abstract void stop();
}

In the above example, we have created an abstract class Vehicle. It contains an abstract method
stop() and a non-abstract method start().

Inheritance of Abstract Class

An abstract class cannot create objects of an abstract class. So, to access the members of an
abstract class, we must inherit it.

Example : Inheritance of an Abstract Class

139
Genesis Coding School An initiative by IT Professionals
Java

abstract class Vehicle{ //abstract class


public void start() {
System.out.println("Vehicle is about to start");
}
}

class DieselVehicle extends Vehicle{ //abstract class is inherited

}
class GenesisAcademyExample {
public static void main(String[] args) {
DieselVehicle car = new DieselVehicle();
car.start();
}
}

Output :
Vehicle is about to start

Overriding of Abstract Methods

In Java, it is mandatory to override abstract methods of the superclass in the subclass. It is


because the subclass inherits abstract methods of the superclass.

If our subclass includes abstract methods(from abstract super class), we need to override them.

140
Genesis Coding School An initiative by IT Professionals
Java

Example : Overriding Abstract Method

abstract class Vehicle{


abstract void start();

public void stop() {


System.out.println("Vehicle stops here");
}
}

class PetrolVehicle extends Vehicle{

public void start() {


System.out.println("Vehicle is about to start");
}
}
class GenesisAcademyExample {
public static void main(String[] args) {
PetrolVehicle car= new PetrolVehicle();
car.start();
car.stop();
}
}

Output :

141
Genesis Coding School An initiative by IT Professionals
Java

Vehicle is about to start


Vehicle stops here

In the above example, we have created an abstract class Vehicle. The class contains
an abstract method start() and a non-abstract method stop().

We have inherited a subclass PetrolVehicle from the superclass Vehicle. Here, the
subclass PetrolVehicle overrides the abstract method start().

We then created an object car of PetrolVehicle, we then called car.start() and car.stop() methods.

Abstraction using Abstract Class

Example : Abstraction using Abstract Class

abstract class Vehicle{


abstract void makeSound();

class PetrolVehicle extends Vehicle{


public void makeSound() {
System.out.println("petrol vehicle is less noisy");
}
}

142
Genesis Coding School An initiative by IT Professionals
Java

class DieselVehicle extends Vehicle{


public void makeSound() {
System.out.println("diesel vehicle is a bit noisy");
}
}

class GenesisAcademyExample {
public static void main(String[] args) {
PetrolVehicle car1= new PetrolVehicle ();
car1.makeSound();

DieselVehicle car2= new DieselVehicle();


car2.makeSound();
}
}

Output :
petrol vehicle is less noisy
diesel vehicle is a bit noisy

In the above example, we have a superclass Vehicle. The superclass Vehicle has an abstract
method makeSound(). The makeSound() method cannot be implemented inside Vehicle. It is
because every vehicle makes different type of sounds. So, all the subclasses of Vehicle would have
different implementation of makeSound().

143
Genesis Coding School An initiative by IT Professionals
Java

We cannot implement makeSound() in Vehicle in such a way that it can be correct for all
subclasses of Vehicle(PetrolVehicle and DieselVehicle). So, the implementation
of makeSound() in Vehicle is kept hidden.

In the above example, PetrolVehicle makes its own implementation


of makeSound() and DieselVehicle makes its own implementation of makeSound().

Encapsulation in Java

 Encapsulation

Encapsulation

Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the
variables of a class are always hidden from other classes. It can only be accessed using the
methods of their current class. For example - in school, a student cannot exist without a class.

144
Genesis Coding School An initiative by IT Professionals
Java

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side
capsule.

Combining of state and behavior in a single container is known as encapsulation. In java language
encapsulation can be achieve using class keyword, state represents declaration of variables on
attributes and behavior represents operations in terms of method. In the above image the
variables and methods of class car is binded together to achieve Encapsulation. The variables of
class car can be hidden from the outside world. And still the methods will be available to outside,
145
Genesis Coding School An initiative by IT Professionals
Java

So that the available methods can access the hidden data members(variable) since they are of the
same class. This is how encapsulation is achieved.

Benefits of encapsulation

 Provides abstraction between an object and its clients.


 Protects an object from unwanted access by clients.

Example : A bank application forbids (restrict) a client to change an Account's balance.

In Java, encapsulation helps us to keep related fields and methods together, which makes our
code cleaner and easy to read.

Access modifiers are a specific part of programming language that used to facilitate the
encapsulation of components. Java supports four access modifiers that you can use to define the
visibility of classes, methods, and attributes. Each of them specifies a different level of
accessibility, and you can only use one modifier per class, method or attribute.

We will be studying Access modifiers and How encapsulation is done using Access modifiers in the
next chapter.

Access modifiers 1

146
Genesis Coding School An initiative by IT Professionals
Java

 Access modifiers
 Default access modifier
 Private access modifier

Access modifiers

In Java, access modifiers are used to set the accessibility or scope(visibility) of classes, interfaces,
variables, methods, constructors, data members, and the setter methods etc. by applying the
access modifier on it.

There are four types of access modifiers available in java:

1. Default
2. Private
3. Protected

147
Genesis Coding School An initiative by IT Professionals
Java

4. Public

Default access modifier

When we do not mention any access modifier, it is called default access modifier. The scope of
this modifier is limited to the package only. This means that if we have a class with the default
access modifier in a package, only those classes that are in this package can access this class. No
other class outside this package can access this class. Similarly, if we have a default method or
data member in a class, it would not be visible in the class of another package.
For example, if we have two classes A(default) and B(public) and both of them are of the different
packages. When B tries to access a method of the class A (A is of default access modifier) then
there will be a compilation error due to lack of access to class A. This is how the default access
modifier work with classes.

File Name : A.java

package packageforaclass;

class A{
/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}

148
Genesis Coding School An initiative by IT Professionals
Java

File Name : B.java

package packageforbclass;

/* We are importing the abcpackage


* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import packageforaclass.*; //in the packageforbclass, we are importing package packageforaclass
public class B{
public static void main(String args[]){
A obj = new A();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(6, 8);
}
}

Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method addTwoNumbers(int, int) from the type Addition is not visible
at packageforbclass.Test.main(Test.java:12)

149
Genesis Coding School An initiative by IT Professionals
Java

Private access modifier

The private access modifier is specified using the keyword private. The scope of private modifier is
limited to the class only

 Private Data members and methods are only accessible within the class
 Class and Interface cannot be declared as private
 If a class has private constructor then you cannot create the object of that class from
outside of the class.

Example : private

class Test{
private double number = 100;
private int square(int a){
return a*a;
}
}
public class GenesisAcademyExample {
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.number);
System.out.println(obj.square(3));
}
}

Output :
150
Genesis Coding School An initiative by IT Professionals
Java

Compile - time error

Example above throws compilation error because we are trying to access the private data
member and method of class Test in the class GenesisAcademyExample. The private data member
and method are only accessible within the class.

Access modifiers 2

 Protected Access Modifier


 Public access modifier

Protected Access Modifier

Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is
similar to default access modifier with one exception that it has visibility in sub classes. Classes
cannot be declared protected. This access modifier is generally used in a parent child relationship.

A.java

package packageforclassa;
public class A{

protected int myMethod(int a, int b){


return a+b;

151
Genesis Coding School An initiative by IT Professionals
Java

}
}

B.java

package packageforclassb;
import packageforclassa.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
System.out.println(obj.myMethod(10, 10));
}
}

Output :
20

In this example the class B which is present in another package with respect to class B, is able to
call the myMethod() method, which is declared protected. This is because the class B extends
class A and the protected modifier allows the access of protected members in subclasses (in any
packages).

Public access modifier

The members, methods and classes that are declared public can be accessed from anywhere. This
modifier doesn’t put any restriction on the access.
152
Genesis Coding School An initiative by IT Professionals
Java

A.java

package packageforclassa;

public class A{

public int myMethod(int a, int b){


return a+b;
}
}

B.java

package packageforclassb;
import packageforclassa.*;
class B{
public static void main(String args[]){
A obj = new A();
System.out.println(obj.myMethod(10,10));
}
}

Output :
20

153
Genesis Coding School An initiative by IT Professionals
Java

In the example above method myMethod() has public modifier and class B is able to access this
method without even extending the class A. This is because public modifier has visibility
everywhere.

Lets see the scope of these access modifiers in tabular form:

Implementing Encapsulation and Getters & Setters

 Implementing Encapsulation
 Getter and Setter Methods
 this keyword in java

Implementing Encapsulation

Consider the example below. In this programme we have a Bank Account class with deposit and

154
Genesis Coding School An initiative by IT Professionals
Java

show balance methods.

class Account {
private int account_number;
private int account_balance;

public void show Data() {


//code to show data
}

public void deposit(int a) {


if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
}

Suppose an outsider gain access to the code of our Account class and if he tries to deposit an
amount of 500 into the account by some way, then our code fails and banking function will be
vulnerable.

class Hacker{
Account a = new Account();
a.account_balance = 500;
}

155
Genesis Coding School An initiative by IT Professionals
Java

But since the data members are private the class Hacker won,t be able to get into our account
class. This is the basics of encapsulation. Protecting data from outside world.

Getter and Setter Methods

If a data member is declared "private", then it can only be accessed within the same class. No
outside class can access data member of that class. If you need to access these variables, you have
to use public "getter" and "setter" methods.

Getter and Setter's methods are used to create, modify, delete and view the variables values. By
convention, getters start with the word "get" and setters with the word "set", followed by a
variable name.

The following code is an example of getter and setter methods:

class Vehicle {
private String color;

// Getter
public String getColor() {
return color;
}

// Setter
public void setColor(String c) {
156
Genesis Coding School An initiative by IT Professionals
Java

this.color = c;
}
}
class GenesisAcademyExample {
public static void main(String[] args) {
Vehicle car= new Vehicle();
car.setColor("Red");
System.out.println(car.getColor());
}
}

Output :
Red

The getter method returns the value of the attribute. The setter method takes a parameter and
assigns it to the attribute. Once the getter and setter have been defined, we use it in our main.

this keyword in java

Keyword THIS is a reference variable in Java that refers to the current object.

The various usages of 'THIS' keyword in Java are as follows:

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
157
Genesis Coding School An initiative by IT Professionals
Java

3. this() can be used to invoke current class constructor.


4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Take a look at the Java code below :

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println("roll no : "+rollno+"; Name :"+name+"; Fees :"+fee);}
}
class GenesisAcademyExample {
public static void main(String args[]){
Student s1=new Student(1024,"rahul",15000f);
Student s2=new Student(1025,"pranav",20000f);
s1.display();
s2.display();
}}

While executing the code at the student class, the compiler is unable to distinguish local variable
158
Genesis Coding School An initiative by IT Professionals
Java

and instance variable. We can use this inside the method to avoid this problem.

Using this

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println("roll no : "+rollno+"; Name : "+name+"; Fees : "+fee);}
}

class GenesisAcademyExample {
public static void main(String args[]){
Student s1=new Student(1024,"rahul",15000f);
Student s2=new Student(1025,"pranav",20000f);
s1.display();
s2.display();
}}

Output :

roll no : 1024; Name :rahul; Fees :15000.0

159
Genesis Coding School An initiative by IT Professionals
Java

roll no : 1025; Name :pranav; Fees :20000.0

160
Genesis Coding School An initiative by IT Professionals

You might also like