Java Set2
Java Set2
Table of Contents
........................................................................................................................................................................ 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
4
Genesis Coding School An initiative by IT Professionals
Java
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
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??
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
7
Genesis Coding School An initiative by IT Professionals
Java
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
13
Genesis Coding School An initiative by IT Professionals
Java
Using Terminal
Open the ubuntu Terminal and Run the update command given below.
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.
15
Genesis Coding School An initiative by IT Professionals
Java
Now final step, run this command to install eclipse through terminal using snap.
16
Genesis Coding School An initiative by IT Professionals
Java
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
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.
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
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
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
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.
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!");
}
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
class genesis {
public static void main(String[] args) {
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) {
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.
33
Genesis Coding School An initiative by IT Professionals
Java
Output :
odd number
Exercise
34
Genesis Coding School An initiative by IT Professionals
Java
a) True
b) False
c) Error
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.
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;
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:
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) {
38
Genesis Coding School An initiative by IT Professionals
Java
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
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) {
Output :
-5.5 is not positive
Exercise
40
Genesis Coding School An initiative by IT Professionals
Java
Switch statement
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
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.
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 :
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 :
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
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.
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.
for(initialization;condition;incr/decr){
//statement or code to be executed
}
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 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.
for(Type var:array){
//code to be executed
}
50
Genesis Coding School An initiative by IT Professionals
Java
Output :
12
23
44
56
78
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 :
51
Genesis Coding School An initiative by IT Professionals
Java
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?
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 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
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 .
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
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
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 .
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
61
Genesis Coding School An initiative by IT Professionals
Java
break;
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
63
Genesis Coding School An initiative by IT Professionals
Java
}
}
Output :
10
20
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
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.
66
Genesis Coding School An initiative by IT Professionals
Java
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
// 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
enum Enums
{
ONE, TWO, THREE, ONE, FOUR;
}
71
Genesis Coding School An initiative by IT Professionals
Java
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 :
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
To display the current date, import the java.time.LocalDate class, and use its now() method:
Example
73
Genesis Coding School An initiative by IT Professionals
Java
-------------------------------------------------------------
To display the current time (hour, minute, second, and milliseconds), import the
java.time.LocalTime class, and use its now() method:
Example
74
Genesis Coding School An initiative by IT Professionals
Java
----------------------------------------------------------
To display the current date and time, import the java.time.LocalDateTime class, and use its now()
method:
Example
75
Genesis Coding School An initiative by IT Professionals
Java
-------------------------------------------------------------------
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
76
Genesis Coding School An initiative by IT Professionals
Java
-----------------------------------------------------------------------------------
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"
77
Genesis Coding School An initiative by IT Professionals
Java
Output :
Before Formatting: 2020-05-25T03:34:38.720524
After Formatting: 25-May-2020 03:34:38
78
Genesis Coding School An initiative by IT Professionals
Java
Output :
Before Formatting: 2020-05-25T03:32:17.271922
After Formatting: 25/05/2020 03:32:17
Output :
79
Genesis Coding School An initiative by IT Professionals
Java
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.
Depending on whether a method is defined by the user, or available in the standard library, there
are two types of methods in Java:
81
Genesis Coding School An initiative by IT Professionals
Java
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 : 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.
83
Genesis Coding School An initiative by IT Professionals
Java
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();
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
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
88
Genesis Coding School An initiative by IT Professionals
Java
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
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
Exception Handling
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.
91
Genesis Coding School An initiative by IT Professionals
Java
Exercise
92
Genesis Coding School An initiative by IT Professionals
Java
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.
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
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))?
{
//error handling code
}
Example :
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:
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
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
Example :
COPY
finally{
96
Genesis Coding School An initiative by IT Professionals
Java
Output :
Number should not be divided by zero
This is finally block
Out of try-catch-finally
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
for example:
Example :
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)
Example :
99
Genesis Coding School An initiative by IT Professionals
Java
Output :
Access granted - You are old enough!
Exercise
100
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.
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.
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.
104
Genesis Coding School An initiative by IT Professionals
Java
Example
105
Genesis Coding School An initiative by IT Professionals
Java
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,
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.
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
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
109
Genesis Coding School An initiative by IT Professionals
Java
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.
111
Genesis Coding School An initiative by IT Professionals
Java
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.
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
Output :
Principal's salary is:30000
Bonus of Teacher is:18000
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Through Interfaces)
5. Hybrid Inheritance(Through Interfaces)
Single Inheritance
113
Genesis Coding School An initiative by IT Professionals
Java
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.
}
}
Output :
Principal's salary is:30000
Bonus of Teacher is:18000
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.
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 :
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
Interface
Multiple Inheritance
Hybrid Inheritance
118
Genesis Coding School An initiative by IT Professionals
Java
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
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
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
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
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.
Output :
GenesisAcademy
127
Genesis Coding School An initiative by IT Professionals
Java
Types of Polymorphism
Compile-time Polymorphism
Run-time Polymorphism
Types of Polymorphism
Compile-time Polymorphism
Run-time Polymorphism
Compile-time Polymorphism
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
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);
}
}
}
Output :
30
40
class GenesisAcademyExample {
130
Genesis Coding School An initiative by IT Professionals
Java
}
}
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
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
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
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.
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
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 :
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.
138
Genesis Coding School An initiative by IT Professionals
Java
Here, start() is an abstract method. The body of start() is replaced by ; . An abstract class can
contain both abstract and non-abstract methods.
In the above example, we have created an abstract class Vehicle. It contains an abstract method
stop() and a non-abstract method start().
An abstract class cannot create objects of an abstract class. So, to access the members of an
abstract class, we must inherit it.
139
Genesis Coding School An initiative by IT Professionals
Java
}
class GenesisAcademyExample {
public static void main(String[] args) {
DieselVehicle car = new DieselVehicle();
car.start();
}
}
Output :
Vehicle is about to start
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
Output :
141
Genesis Coding School An initiative by IT Professionals
Java
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.
142
Genesis Coding School An initiative by IT Professionals
Java
class GenesisAcademyExample {
public static void main(String[] args) {
PetrolVehicle car1= new PetrolVehicle ();
car1.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.
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
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.
1. Default
2. Private
3. Protected
147
Genesis Coding School An initiative by IT Professionals
Java
4. Public
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.
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
package packageforbclass;
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
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
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 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{
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).
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{
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.
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
class Account {
private int account_number;
private int account_balance;
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.
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.
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.
Keyword THIS is a reference variable in Java that refers to the current object.
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 :
159
Genesis Coding School An initiative by IT Professionals
Java
160
Genesis Coding School An initiative by IT Professionals