0% found this document useful (0 votes)
7 views91 pages

Java Upto OOps

Uploaded by

Akhila Akhila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views91 pages

Java Upto OOps

Uploaded by

Akhila Akhila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Access Modifiers

Concepts
 Access Modifiers
 Access Modifiers with Attributes
 Access Modifiers with Methods and Constructors
 Access Modifiers with Classes
 More Method Overriding Rules

Introduction
In the previous units, we learned classes and class members like attributes, methods,
etc. In Java, it is possible to specify whether a class or any member of a class can be
accessed in another class/subclass of the same package, or another class/subclass of a
different package.

In this unit, we'll learn different types of Access Modifiers that are used to control
the accessibility.

1. Access Modifiers
Access modifiers are the keywords that set access levels when used with the classes,
methods, constructors, attributes, etc.

In Java, we have four access modifiers to set the accessibility. They are,

1. Private: The access level of a private modifier is only within the declared class.
It is not accessible outside of the class.
2. Default : The access level of a default modifier is up to the class/subclass of the
same package. It cannot be accessed from outside the package.
3. Protected : The access level of a protected modifier is up to the class/subclass
of the same package and also to a different package through the subclass. A
subclass is required to access it from a different package.
4. Public : The access level of a public modifier is everywhere in the program. It
means that it is accessible from the class/subclass of the same/different package.

Package (Recap)

Let's learn the behaviour of different modifiers with classes, methods, etc.

2. Access Modifiers with Attributes


Let's learn the behaviour of each of the access modifiers with attributes

2.1 Private
The keyword

private
is used to specify the private access modifier. The private access modifier has the most
restricted scope among all other access modifiers.

Syntax

1
private static dataType attributeName;
JAVA

The keywords like

final
, and
static
are called Non-Access Modifiers. We can use access modifiers along with non-access
modifiers. When a declaration consists of both access and non-access modifiers, the
access modifiers must be placed prior to the non-access modifiers as shown above.
The

private
attributes are accessible only within the declared class.
Example 1: Accessing private attributes within the declared class

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");
System.out.println(mobile.model);

JAVA
Expand

Output

iPhone 13 Pro
In the above code, we are able to an create object and access the attribute as we have
created it inside the

Mobile
class.
Example 2: Accessing private attributes inside another class

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");

JAVA
Expand

Output

file.java:13: error: model has private access in Mobile


System.out.println(mobile.model);
^

In the above code, attribute is declared as private and tried to access it inside the

Base
class. As we have learned they are only accessed within the declared class. Hence, we
are unable to access them from any other class and the error is thrown.

2.2 Default (no keyword required)


If we do not specify any access modifier, it is considered as default.

The default attributes are accessible only to the classes or subclasses of the same
package. We cannot access them in other packages.

Let's understand it with an example by defining two classes in the same file.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Mobile {
String model;
String camera;
Mobile(String modelSpecification, String cameraSpecification) {
model = modelSpecification;
camera = cameraSpecification;
}
}
class Base {

JAVA
Expand

Output

iPhone 13 Pro
12 MP
In the above code, no access modifiers are mentioned for attributes. Hence, they are
considered to be the default and we are able to access the attributes of the

Mobile
class inside the
Base
class.

2.3 Protected
The keyword

protected
is used to specify the protected access modifier.

Syntax

1
protected dataType attributeName;
JAVA

When an attribute is declared as

protected
, it means that it is accessible to the class/subclass of the same package and subclass of
other packages.
For example, we have a public

classA
of
packageA
having a protected attribute
name
and a
classB
of
packageB
(another package). Now, the
name
is accessible inside the
classB
only when the
classB
extends
classA
.
We will learn public classes later in this unit
The access modifier

protected
is less restrictive when compared to the default and private.

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
protected String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");

JAVA
Expand

Output
iPhone 13 Pro
In the above code, the protected attributes are accessible to other classes of the same
package. So, we are able to create objects and access the attributes and methods of it.

2.4 Public
The keyword

public
is used to specify the public access modifier.

Syntax

1
public dataType attributeName;
JAVA

When attributes are declared as

public
, it means that those are accessible from the class/subclass of the same/different
package.

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
public String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
}
class Base {
public static void main(String[] args) {
Mobile mobile = new Mobile("iPhone 13 Pro");

JAVA
Expand

Output

iPhone 13 Pro
In the above code, the public attributes are accessible from the class/subclass of the
same/different package. So, we are able to access them in another class (

Base
class) of the same package.

2.5 Accessibility of Access Modifiers


Same Different Different
Access Same Same package
package package package other
Modifier Class other classes
subclass subclass classes

private Yes No No No No

default Yes Yes Yes No No

protected Yes Yes Yes Yes No

public Yes Yes Yes Yes Yes

 The private access modifier is most restrictive compared to other modifiers


 The default and protected access modifiers are almost similar with protected
having little more scope that it can be accessed in other packages with its
subclass.
 The public access modifier is having the widest scope among all the access
modifiers.

3. Access Modifiers with Methods and


Constructors
All the access modifiers we learned till now are applicable and work the same with the
methods and constructors.

Let's understand them with examples,

3.1 Private
The methods declared with the
private
access modifier can be called private methods.
Similarly, the constructors declared with the

private
access modifiers can be called private constructors.

Syntax for Methods

1
2
3
private returnType methodName() {
// method body
}
JAVA

Syntax for Constructors

1
2
3
private ClassName() {
// constructor body
}
JAVA

The private methods and constructors are accessible only within the declared class.

Example 1: Accessing private methods within the declared class

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
private Mobile(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}

JAVA
Expand

Output

iPhone 13 Pro
calling...9876543210
In the above code, we are able to create objects and access the attributes and methods
of the

Mobile
class as we access them inside the
Mobile
class.
Example 2: Accessing private methods inside another class

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
private String model;
private Mobile(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}

JAVA
Expand
Output

file.java:15: error: Mobile(String) has private access in Mobile


Mobile mobile = new Mobile("iPhone 13 Pro");
^
/usercode/file.java:16: error: makeCall(long) has private access in Mobile
mobile.makeCall(9876543210L);
^

In the above code, the constructor and method are declared as private and tried to
access it inside the

Base
class. As we have learned they are only accessed within the declared class. Hence, we
are unable to access them from any other class and the error is thrown.

3.2 Default (no keyword required)


When no access modifier is specified to the methods and constructors, then they can be
called default methods and default constructors respectively.

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
String model;
Mobile(String modelSpecification) {
model = modelSpecification;
}
void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}

JAVA
Expand
Output

iPhone 13 Pro
calling...9876543210
In the above code, no access modifiers are mentioned for the attribute, method, and
constructor. Hence, they are considered to be the default and we are able to access the
attributes of the

Mobile
class inside the
Base
class.

3.3 Protected
The methods and constructors declared with

protected
access modifiers can be called protected methods and protected constructors
respectively.

Syntax for Methods

1
2
3
protected returnType methodName() {
// method body
}
JAVA

Syntax for Constructors

1
2
3
protected ClassName() {
// constructor body
}
JAVA

Similar to the protected attributes, the protected methods and constructors are
accessible to the class/subclass of the same package and subclass of other packages.

Code
1
2
3
4
5
6
7
8
9
10
11
class Mobile {
protected String model;
protected Mobile(String modelSpecification) {
model = modelSpecification;
}
protected void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}

JAVA
Expand

Output

iPhone 13 Pro
calling...9876543210
In the above code, the protected attributes, methods and constructors are accessible to
other classes of the same package. So, we are able to create objects and access the
attributes and methods of it.

3.4 Public
The methods and constructors declared with

public
access modifier can be called public methods and public constructors respectively.

Syntax for Methods

1
2
3
public returnType methodName() {
// method body
}
JAVA

Syntax for Constructors

1
2
3
public ClassName() {
// constructor body
}
JAVA

Similar to the public attributes, the public methods and constructors are accessible from
can be accessed from the class/subclass of the same/different package.

Code

1
2
3
4
5
6
7
8
9
10
11
class Mobile {
public String model;
public Mobile(String modelSpecification) {
model = modelSpecification;
}
public void makeCall(long phnNum) {
System.out.printf("calling...%d", phnNum);
}
}

JAVA
Expand

Output

iPhone 13 Pro
calling...9876543210
In the above code, the public methods, etc are accessible from the class/subclass of the
same/different package. So, we are able to create objects and access the attributes and
methods in the

Base
class.

4. Access Modifiers with Classes


Classes in Java can only have Public or Default as access modifiers.

4.1 Public
The classes declared with

public
access modifier can be called public classes.

Syntax

1
2
3
public class ClassName {
// body of the class
}
JAVA

When a class is declared

public
, it means that it is accessible from the class/subclass of the same/different package.
Previously we have learned what are packages. We have used different classes like

Scanner
,
Math
, etc of different packages by importing them to our Java program. This is because all
those are
public
classes. Hence, we are able to import and utilise them in our program.
A Java file can consist of only one public class.

Note: Currently we cannot define public classes in the provided code playground. We
will provide support to write public classes soon.
4.2 Default (no keyword required)
When no access modifier is specified to the classes, then they can be called default
classes.

Syntax

1
2
3
class ClassName {
// body of the class
}
JAVA

A default class is accessible only to the classes or subclasses of the same package. We
cannot access the default classes in other packages.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Mobile {
String model;
String camera;
Mobile(String modelSpecification, String cameraSpecification) {
model = modelSpecification;
camera = cameraSpecification;
}
}
class Base {

JAVA
Expand

In the above code, no access modifiers are mentioned for both classes. Hence both the
classes are considered as the default classes.
As we have learned, we can see that the

Mobile
class is accessible inside the
Base
class and able to create objects.
Similar to classes, only the access modifiers public and default we learned till now
are applicable to Interfaces also and work in the same way.

We will learn about Interfaces later in the course.

5. More Method Overriding Rules


In the previous unit, we learned few rules of the method overriding.

1. Constructors cannot be overridden


2. The overriding method should have the same return type and parameters
3. A final method cannot be overridden

Now, let's learn few more rules of the method overriding,

4. The private methods cannot be overridden.


5. The access level cannot be more restrictive than the overridden method's access
level.

Let's understand each of the above rules with examples

4. The private methods cannot be overridden


We have learned that private methods are accessible only within the declared class. It
means that private methods cannot be inherited to the subclasses, so they cannot be
overridden too.

Example 1:

Code

1
2
3
4
5
6
7
8
9
10
11
class Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
class Smartphone extends Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Smartphone");
}

JAVA
Expand

Output

file.java:24: error: makeCall(long) has private access in Telephone


smartphone.makeCall(9876543210L);
^

In the above code, we have declared the

smartphone
object using the superclass
Telephone
. So, the
smartphone
object can access all the methods of the
Telephone
class and overriding methods of the
Smartphone
class.
Also we tried to invoke the

makeCall()
method of the
Smartphone
class. As the private method
makeCall()
cannot be overridden, the compiler tries to invoke the
makeCall()
method of the
Telephone
class. But the private methods are only accessible in the declared class. Hence, the error
has been thrown.
Let's declare the

smartphone
object using the
Smartphone
class.
Example 2:

Code

1
2
3
4
5
6
7
8
9
10
11
class Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}
class Smartphone extends Telephone {
private void makeCall(long phnNum) {
System.out.println("Calling from Smartphone");
}

JAVA
Expand

Output

Calling from Smartphone


The above code works. This is because private methods cannot be inherited to the
subclasses. So, the Java compiler directly invokes the

makeCall()
method of the
Smartphone
class.
5. The access level cannot be more restrictive than the overridden
method's access level
We have learned that the

private
is more restrictive (i.e., narrow scope) and the
public
is less restrictive (i.e., widely scoped) access modifier.
Below is the hierarchy of the access modifiers based on the access levels, more
restrictive to less restrictive from left to right.

private -> default -> protected -> public


Example 1:

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Telephone {
String model;
Telephone(String modelSpecification) {
model = modelSpecification;
}
protected void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}

JAVA
Expand

Output

file.java:18: error: makeCall(long) in Smartphone cannot override


makeCall(long) in Telephone
private void makeCall(long phnNum) {
^
attempting to assign weaker access privileges; was protected

In the above code,

 we have defined the


makeCall()
method in the superclass
Telephone
as
protected
 we have defined the
makeCall()
method in the subclass
Smartphone
as
private
The

private
modifier is more restrictive than the
protected
. So, the
makeCall()
method of the
Telephone
class cannot be overridden with the
makeCall()
method of the
Smartphone
class and the error has been thrown.
Example 2:

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Telephone {
String model;
Telephone(String modelSpecification) {
model = modelSpecification;
}
private void makeCall(long phnNum) {
System.out.println("Calling from Telephone");
}
}

JAVA
Expand

Output

Calling from Smartphone


In the above code,

 we have defined the


makeCall()
method in the superclass
Telephone
as
private
 we have defined the
makeCall()
method in the subclass
Smartphone
as
protected
The

protected
modifier is less restrictive than the
private
. So, the
makeCall()
method of the
Telephone
class has overridden by the
makeCall()
method of the
Smartphone
class.

Summary
 Accessibility of Access Modifiers

Same Same Different Different


Access Same
package package package package other
Modifier Class
subclass other classes subclass classes

private Yes No No No No

default Yes Yes Yes No No

protected Yes Yes Yes Yes No

public Yes Yes Yes Yes Yes

 The private access modifier is most restrictive compared to other modifiers


 The default and protected access modifiers are almost similar with protected
having little more scope that it can be accessed in other packages with its
subclass.

 The public access modifier is having the widest scope among all the access
modifiers.

 Classes in Java can only have Public or Default as access modifiers.

 Rules of Method Overriding

i. Constructors cannot be overridden


ii. The overriding method should have the same return type and parameters
iii. A final method cannot be overridden
iv. The private methods cannot be overridden
v. The access level cannot be more restrictive than the overridden method's
access level

Polymorphism
Concepts
 Execution of a Java Code
 Polymorphism

Introduction
In the previous units, we have seen the four core principles of object-oriented
programming:

1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction

and also learned one of fundamental principles called Inheritance.

In this unit, we'll look into the execution of Java code and learn another important
principle of OOP called Polymorphism .

1. Execution of a Java Code


The execution of Java code will be done in two stages.

1. Compilation
2. Execution

Compilation: In this stage, the file containing our Java code (with

.java
extension) is passed through the compiler, which then converts the source code (our
Java code) into a machine-independent encoding, known as Bytecode . For each class
inside the source file, a separate class file (with
.class
as file extension) is created and the corresponding code is stored in it. The class files
generated are independent of the machine or OS (Operating System).
Note: The creation of bytecode,
.class
files, etc will happen internally in the code playground provided to you.

Execution: In this stage, the main class file i.e., the class that contains the

main()
method is passed to the Java Virtual Machine (JVM) and the code will be run after a few
checks like variables are initialized before they are used, rules for accessing private data
and methods are not violated, etc.

2. Polymorphism
Polymorphism is derived from two Greek words poly and morphs. The word poly means
"many" and morphs means "forms". So polymorphism means many forms.

Polymorphism in Java refers to an object’s capacity to take several forms.


Polymorphism allows us to perform the same action in multiple ways in Java.

Polymorphism is of two types:

1. Compile-time polymorphism
2. Runtime polymorphism

2.1 Compile-time Polymorphism


A polymorphism that occurs during the compilation stage is known as a Compile-time
polymorphism. Method overloading is an example of compile-time polymorphism.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Shapes {
public void area(int radius) {
System.out.println("Area of Circle = " + 3.14 * radius * radius);
}
public void area(double base, double height) {
System.out.println("Area of Triangle = " + 0.5 * base * height);
}
public void area(int length, int breadth) {
System.out.println("Area of Rectangle = " + length * breadth);

JAVA
Expand

Output

Area of Circle = 314.0


Area of Triangle = 43.4775
Area of Rectangle = 15
In the above code, we have defined multiple overloading methods with the name

area
which differ in their parameters. We have also invoked the same method with different
numbers or types of arguments.
Here, compile-time polymorphism occurs and the decision of which method to be
invoked for which call is done in the compilation stage.

2.2 Runtime Polymorphism


A polymorphism that occurs during the execution stage is called Runtime polymorphism.
Method overriding is an example of Runtime polymorphism.

Code

1
2
3
4
5
6
7
8
9
10
11
class Mammal {
void eat() {
System.out.println("Mammal is eating");
}
}
class Dog extends Mammal {
void eat() {
System.out.println("Dog is eating");
}
}

JAVA
Expand

Output

Dog is eating
In the above code, we have used the superclass reference variable

mammal
to refer to its subclass object. We also invoked
eat()
method using the reference variable
mammal
. The method invocations with objects are resolved (i.e., deciding which method should
be called by the statement
mammal.eat()
) during the runtime.
During the runtime, the

mammal
refers to the
Dog
object and the method invocation is resolved and the
eat()
method of the
Dog
class has been invoked as it overrides the
eat()
method of the
Mammal
class.

Summary
 The execution of a Java code will be commenced in two stages:- Compilation and
Execution.

 Polymorphism is of two types:


o Compile-time polymorphism : A polymorphism that occurs during
the compilation stage is called Compile-time polymorphism. Method
overloading is an example of compile-time polymorphism.

o Runtime polymorphism : A polymorphism that occurs during the


execution stage is called Runtime polymorphism. Method overriding is an
example of Runtime polymorphism.

Encapsulation
Concepts
 Encapsulation
 Getters and Setters

Introduction
In the previous units, we have seen the four core principles of object-oriented
programming:

1. Inheritance
2. Encapsulation
3. Polymorphism
4. Abstraction

and also learned one of the fundamental principles of OOP called Inheritance.

In this unit, we'll learn another important principle of OOP called Encapsulation .

1. Encapsulation
Encapsulation in Java is a process of wrapping related code and data together into a
single unit, for example, a capsule which contains several medicines.
In Java, the idea behind encapsulation is to ensure that implementation details are not
visible to users by hiding data within a class to prevent unauthorized access and avoid
unnecessary modifications from outside the class.

Let's understand it better with an example

Code

1
2
3
4
5
6
7
8
9
10
11
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

JAVA
Expand

Output

20
In the above code, we declared the attribute

age
, and
getAge()
,
setAge()
methods in the
Student
class. Here, we have bundled similar codes together in a single class.
To hide the implementation details, we have declared the

age
attribute as
private
and defined public methods
setAge()
and
getAge()
in the class.
This will restrict access to the attributes from outside the class. This is called Data
Hiding .

1.1 Getters and Setters


Getters and setters are the methods which are mostly used to access and update the
non-static attributes respectively.

For each non-static attribute,

Getters: The Getters are used to access/get the value of the non-static attribute of a
class. These are also called accessors.

Generally, getters start with get, followed by the variable name in camel case notation.
Example: getBalance, getName, getLength, etc.
Setters: The Setters are used to set a new value to the non-static attribute of a class.
These are also called mutators.

Generally, setters start with set, followed by the variable name in camel case notation.
Example: setBalance, setName, setLength, etc.

Getters and setters provide us with control over the data in our program. For example,
we can write conditions inside the

setAge()
method so that no one can provide an invalid age.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int studentAge) {
if (studentAge >= 3) {
age = studentAge;
}

JAVA
Expand

Output

15
15
In the above code, we have written a condition in the setter method

setAge()
that a student's age must be greater than or equal to 3. So, when
15
is provided as an argument, the
age
attribute has been updated to
15
and when
1
is provided as an argument the
age
attribute has not been updated.

Summary
 Encapsulation refers to the bundling of attributes and methods inside a single
class.
 Getter method returns the value of a particular non-static attribute of the class.
 Setter method sets a new value to a particular non-static attribute of the class.
 Getters and setters provide us with control over the data in our program.

Abstraction
Concepts
 Abstraction
 Abstract Classes and Methods
 Implementing Abstract Classes and Methods
 Abstraction vs Encapsulation

Introduction
In the previous units, we have seen the four fundamental principles of object-oriented
programming:

1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
Till now we learned three fundamental principles Inheritance, Encapsulation , and
Polymorphism .

In this unit, we'll learn another fundamental principle of OOP called Abstraction .

1. Abstraction
Abstraction is the process of hiding certain details and showing only essential
information to the user.

Let's look at a real-life example of a man driving a car. As far as he knows, pressing the
accelerator increases the speed of the car or applying the brakes stops it. However, he
doesn't know how the speed actually increases when pressing the accelerator. He
doesn't know anything about the car's inner mechanisms or how the accelerator,
brakes, etc., work.

Abstraction can be achieved with,

1. Abstract classes
2. Interfaces

In the unit, we'll learn abstract classes and later in the course, we'll learn interfaces.

2. Abstract Classes and Methods


2.1 Abstract Classes
The

abstract
keyword is a non-access modifier, applied to classes and methods in Java. A class which
is declared with the
abstract
keyword is known as an abstract class.

Syntax

1
2
3
abstract class ClassName {
// attributes and methods
}
JAVA
Similar to regular classes, abstract classes can have constructors, attributes, static and
final methods, etc.

However,

 Abstract classes cannot be instantiated i.e., we cannot create objects using the
abstract classes.
 Abstract classes can have abstract methods.
 Abstract classes cannot be declared as final.
Let's try to create an object of an abstract class.

Code

1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
void start() {
System.out.println("Vehicle started");
}
void stop() {
System.out.println("Vehicle stopped");
}
}
class Base {

JAVA
Expand

Output

file.java:13: error: Vehicle is abstract; cannot be instantiated


Vehicle vehicle = new Vehicle();
^

In the above code, the error has been thrown because we cannot create objects using
the abstract classes.
2.2 Abstract Methods
A method which is declared with the

abstract
keyword is known as an abstract method .
The abstract methods don't contain any implementation i.e., abstract methods do not
have a body. The abstract methods can only be declared inside abstract classes.

Syntax

1
abstract returnType methodName();
JAVA

Here, the body of the method is replaced by

Code

1
2
3
4
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
JAVA

The implementation of the abstract methods should be provided by its subclasses.

3. Implementing Abstract Classes and Methods


3.1 Inheriting Abstract Classes
As we cannot create objects using an abstract class, to access the members of an
abstract class we have to inherit the class from another class.

The abstract classes can have abstract methods and non-abstract methods (i.e., methods
without

abstract
keyword).
Example 1:
let's inherit the

Vehicle
from a
Car
class and implement the abstract methods inside the
Car
class.

Code

1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Car extends Vehicle {
void start() { // overriding abstract method
System.out.println("Car started");
};
void stop() { // overriding abstract method

JAVA
Expand

Output

Car started
Car stopped
In the above code, we have inherited the abstract class

Vehicle
. we provided the implementation for abstract methods
start()
and
stop()
inside the class
Car
and accessed them using the
car
object.
Example 2:

We can declare a reference variable of an abstract class and assign it an object of its
subclass.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Motorbike extends Vehicle {
void start() {
System.out.println("Motorbike started");
}
void stop() {

JAVA
Expand

Output

Motorbike started
Motorbike stopped
Truck started
Truck stopped
In the above code, the
Vehicle
is an abstract class and the
Motorbike
and
Truck
classes extend the
Vehicle
. We declared a superclass reference variable
vehicle
.
The

start()
and
stop()
methods of
Motorbike
and
Truck
are different in their implementations. Still, we can invoke those methods using the
variable
vehicle
without knowing how they are implemented.
Here, the

start
and
stop
mechanisms may differ for different vehicles, but every vehicle consists of
start
and
stop
features regardless of the inner mechanisms.
The abstract classes focus on what should be done and not on how it should be done.

3.2 Multilevel Inheritance with Abstraction


If the subclass of an abstract class is also an abstract class, then the subclass may or may
not implement the abstract methods of its superclass.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
abstract class Car extends Vehicle { // abstract class
boolean areHeadlightsOn;
Car() {
areHeadlightsOn = false;
}

JAVA
Expand

Output

Ferrari started
Ferrari stopped
Are headlights turned on: true
Ferrari handbrake applied
In the above code,

 we inherited an abstract class


Vehicle
from another abstract class
Car
. As the
Car
is also an abstract class, we may or may not implement the
start()
and
stop()
methods.
 we declared an abstract method
applyHandbrake()
in the
Car
class.
 we inherited the
Car
class from the
Ferrari
class. Here, due to the multilevel inheritance, the methods
start()
,
stop()
,
applyHandbrake()
are inherited to the
Ferrari
class. As
Ferrari
is a regular class, we have implemented all the abstract methods
start()
,
stop()
, and
applyHandbrake()
.
The class which consists of implementation for all its methods is called a concrete
class. In the above code,

Ferrari
is a concrete class.
The
Car
class in the above code has two non-abstract methods. Hence, only partial abstraction is
achieved here.
Key Points:

 Abstract Class:
o An abstract class must be declared with an

abstract

keyword.

o It can have constructors, attributes, static and final methods, etc.

o It can have abstract and non-abstract methods.

o It cannot be instantiated i.e., we cannot create objects using the abstract


classes.

o An abstract class cannot be declared as final.

 Abstract Method :
o An abstract method must be declared with an

abstract

keyword.

o The abstract methods can only be declared inside abstract classes.

o An abstract method must be overridden by its subclass method unless the


subclass is an abstract class.

o Abstract methods cannot be private, final, etc which cannot be overridden

4. Possible Mistakes
Let's look at the most common mistakes while working with abstract classes.

1. Not implementing the abstract methods in its subclass

Code

1
2
3
4
5
6
7
8
9
10
11
abstract class Vehicle { // abstract class
abstract void start(); // abstract method
abstract void stop(); // abstract method
}
class Car extends Vehicle {
void start() {
System.out.println("Car started");
};
}

JAVA
Expand

Output

file.java:6: error: Car is not abstract and does not override abstract
method stop() in Vehicle
class Car extends Vehicle {
^

In the above code, the

Car
is not an abstract class and doesn't implement the abstract method
stop()
. Hence, the error has been thrown.
2. Declaring a method as

abstract
which cannot be overridden
We cannot declare private methods, final methods, etc as abstract as they cannot be
overridden.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Vehicle { // abstract class
abstract final void start(); // declaring a final method as abstract
private abstract void stop(); // declaring a private method as abstract
}
class Car extends Vehicle {
void start() {
System.out.println("Car started");
}
void stop() {

JAVA
Expand

Output

file.java:2: error: illegal combination of modifiers: abstract and final


abstract final void start();
^
file.java:3: error: illegal combination of modifiers: abstract and private
private abstract void stop();
^
...

In the above code, the

start()
method is declared as
final
and the
stop()
method is declared as
private
. As the final and private methods cannot be overridden, the error has been thrown.

5. Abstraction vs Encapsulation
Following are the differences between abstraction and encapsulation:

Abstraction Encapsulation

The abstraction process hides unwanted In addition to hiding data, encapsulation


information. protects information.

Encapsulation can be implemented using by


We can implement abstraction using abstract
access modifier i.e. private, protected and
classes and interfaces.
public.

In abstraction, implementation complexities are In encapsulation, the data is hidden using


hidden using abstract classes and interfaces. access modifiers.

Abstraction focus on what should be done. Encapsulation focus on How it should be done.

Summary
 Abstraction is the process of hiding certain details and showing only essential
information to the user.
 Abstract Class
o An abstract class must be declared with an

abstract

keyword.

o It can have constructors, attributes, static and final methods, etc.

o It can have abstract and non-abstract methods.

o It cannot be instantiated i.e., we cannot create objects using the abstract


classes.

o An abstract class cannot be declared as final.

 Abstract Method
o An abstract method must be declared with an

abstract

keyword.

o The abstract methods can only be declared inside abstract classes.


o An abstract method must be overridden by its subclass method unless the
subclass is an abstract class.

o Abstract methods cannot be private, final, etc which cannot be


overridden.

Interfaces
Concepts
 Interface
 Default Methods in Interfaces
 Inheritance among Interfaces
 Multiple Inheritance
 Abstract Classes vs Interfaces

Introduction
In the previous unit, we learned abstraction and it can be achieved by,

1. Abstract classes
2. Interfaces

We learned to use abstract classes to achieve abstraction.

In this unit, we'll learn Interfaces.

1. Interface
An Interface is similar to an abstract class. It cannot be instantiated and consists of
abstract methods.

The interfaces act as a blueprint for a class. The

interface
keyword is used to create an interface.

Syntax

1
2
3
interface InterfaceName {
// body of the interface
}
JAVA

Similar to classes, the Pascal case notation is followed for naming the interfaces.

Unlike abstract classes, interfaces cannot have constructors.

Let's create an interface

CricketPlayer
with an attribute
hasKit
and abstract methods as
run()
, and
field()
.

Code

1
2
3
4
5
interface CricketPlayer {
boolean hasKit = true;
void run();
void field();
}
JAVA

In the above code, we have created an interface

CricketPlayer
and declared two abstract methods.
Here, we can notice that we did not declare the abstract methods

run()
and
field()
using the
abstract
keyword.
The methods inside the interfaces are
public
and
abstract
by default. And the attributes inside the interfaces are
public
,
static
and
final
by default.
So, the above code is equivalent to,

1
2
3
4
5
interface CricketPlayer {
public static final boolean hasKit = true;
public abstract void run();
public abstract void field();
}
JAVA

1.1 Inheriting Interfaces


The

implements
keyword is used to inherit interfaces from a class.

Code

1
2
3
4
5
6
7
8
9
10
11
interface CricketPlayer {
void run();
void field();
}
class Person implements CricketPlayer {
public void run() { // overriding abstract method
System.out.println("Running");
};
public void field() { // overriding abstract method

JAVA
Expand

Output

Running
Fielding
In the above code, the

Person
class implements the
CricketPlayer
interface and has overridden the
run()
and
field()
methods. We declared the overriding methods as
public
because according to the rules of overriding, the overriding method should not be more
restrictive than the overridden method.
The

public
has the widest scope among all the access modifiers. As, the methods of interfaces are
public
and
abstract
by default, specifying any other access modifier other than
public
makes the overriding methods more restrictive. Hence,
public
methods should be used to override the methods of the interfaces.

2. Default Methods in Interfaces


In Java 8, there is a new feature according which we can write the implementation of a
method inside the interface. These methods are called default methods.

The

default
keyword is used to declare a method in the interface as default method .

Syntax

1
2
3
accessModifier default returnType methodName() {
// block of code
}
JAVA

Why default methods are introduced?


Imagine a scenario where we need to add a new method to an interface in Java. We can
easily add the method to the interface without providing an implementation, but all the
classes that implement this interface must provide their own implementation for the
new method.

If there are many classes that implement this interface, we would have to track down all
of these classes and make changes to them, which can be both tedious and error-prone.

To avoid this issue, Java introduced default methods, which are inherited like regular
methods and provide an implementation for the new method within the interface.

Let's understand it better with an example,

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
interface OnlineShoppingSite {
void processOrder(String item);
default void sendEmailsToCustomers() { // default method
System.out.println("Sending emails to customers who made a purchase in the
last week.");
}
}
class Flipkart implements OnlineShoppingSite {
public void processOrder(String item) {
System.out.println("Processing order for " + item + " on Flipkart.");

JAVA
Expand

Output

Processing order for Book on Flipkart.


Sending personalized emails to Flipkart customers.
Processing order for Laptop on Walmart.
Sending emails to customers who made a purchase in the last week.

In the above code, we have defined an interface

OnlineShoppingSite
with an abstract method
processOrder(String item)
and a default method
sendEmailsToCustomers()
. The
Flipkart
class implements the
OnlineShoppingSite
interface and provides an implementation for the
processOrder(String item)
method and overrides the
sendEmailsToCustomers()
method. The Walmart class also implements the
OnlineShoppingSite
interface and provides an implementation for the
processOrder(String item)
method.
In the

main()
method, we created objects of the
Flipkart
and
Walmart
classes and called their respective methods. The
processOrder(String item)
method processes the order and the
sendEmailsToCustomers()
method sends emails to customers who made a purchase in the last week.
In the case of the

Flipkart
object, the overridden method is called, whereas in the case of the
Walmart
object, the default method is called.

3. Inheritance among Interfaces


An interface can inherit another interface. We use the

extends
keyword to inherit an interface from another interface.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
interface CricketPlayer {
void run();
void field();
}
interface Wicketkeeper extends CricketPlayer { // interface extending another
interface
void wicketkeeping();
}
class Person implements Wicketkeeper {
public void field() {

JAVA
Expand

Output

Fielding
Wicketkeeping
Running
In the above code, we have extended the interface

CricketPlayer
from another interface
Wicketkeeper
and implemented all the methods in the
Person
class.
In Java,

 a class can extend another class


 a class can implement an interface
 an interface can extend another interface

4. Multiple Inheritance
In multiple inheritance, a single class/interface can inherit multiple interfaces.

We can specify multiple interfaces separated by a comma while


extending/implementing the interfaces.
Similar to superclass and subclass, we have superinterface and subinterface in interfaces.

Previously, we came across interfaces at ArrayLists, HashMaps, etc

 the
ArrayList
class implements
List
,
Cloneable
, etc interfaces
o the

List

interface extends the

Collection

interface.

 the
HashMaps
class implements
Map
,
Cloneable
, etc interfaces.
Multiple inheritance is not possible among classes i.e., a single class cannot extend
multiple classes.
Example 1: A class implementing multiple interfaces

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
interface InswingBowler {
void inswing();
}
interface OutswingBowler {
void outswing();
}
class BowlerA implements InswingBowler, OutswingBowler { // a class implementing
multiple interfaces
public void inswing() {
System.out.println("Inswing bowling");

JAVA
Expand

Output

Inswing bowling
Outswing bowling
In the above code, we have declared two interfaces

InswingBowler
and
OutswingBowler
and implemented them inside the
BowlerA
class.
The interfaces represent the IS-A relationship. Here, the

BowlerA
is a
InswingBowler
and the
BowlerA
is a
OutswingBowler
.
Example 2: An interface extending multiple interfaces

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
interface Camera {
void captureImage();
}
interface Calculator {
void calculate();
}
interface Smartphone extends Camera, Calculator { // interface extending multiple
interfaces
void videoCall();
}

JAVA
Expand

Output

Image captured
Calculate mathematical expressions
Video calling
In the above code, the
Smartphone
interface extends two superinterfaces
Camera
and
Calculator
. We declared another class
IPhone
and have provided implementation for all the methods inside it.
Similar to using a superclass reference variable, we have used an interface reference
variable

smartphone
to store the object of its subclass
IPhone
.
While using the superclass or superinterface reference variable make sure that it has all
the methods that are implemented in the subclass object that it will be storing in the
runtime.

For example, in the above code, we cannot use the reference variable of a

Camera
because it doesn't have the
calculate()
and
videoCall()
methods. The
Smartphone
interface has all the methods the
IPhone
class implemented as it extended the
Camera
and
Calculator
interfaces.

4.1 Extending and Implementing from a Single SubClass


In Java, we can extend a superclass and implement multiple interfaces from a single
subclass.

Syntax

1
2
3
class Subclass extends Superclass implements InterfaceOne, InterfaceTwo, ... {
// body of the subclass
}

JAVA

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
interface MachineGun {
void fireBullets();
}
interface MissileSystem {
void fireMissiles();
}
abstract class Boat {
abstract void move();
}

JAVA
Expand

Output

Moving
Firing bullets
Firing missiles
In the above code, we have extended the abstract class

Boat
and implemented the
MachineGun
and
MissileSystem
interfaces from a single class
Warship
. We have provided all the implementations for the methods declared in the interfaces
and an abstract class.

5. Abstract Classes vs Interfaces


Differences between abstract classes and interfaces are,

Abstract Class Interface

The abstract keyword is used to declare an abstract The interface keyword is used to declare
class. an interface.

An abstract class can have abstract and non-abstract


Every method is abstract by default.
methods.

An abstract class can have final, non-final, static and Every attribute is public, static and final by
non-static attributes. default.

An abstract class can have constructors. Interface cannot have constructors.

An abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

An abstract class can provide the implementation of Interface can't provide the implementation
interface. of abstract class.

An abstract class can extend another Java class and An interface can extend another Java
implement multiple Java interfaces. interface only.

An abstract class can be extended using the keyword An interface can be implemented using the
"extends". keyword "implements".

An abstract class can have class members like private, Members of a Java interface are public by
protected, etc. default.

When to use Abstract classes and Interfaces?

Use Abstract classes:

 When we want to share among several closely related classes. For example:
Vehicle, Car, etc.
 When the subclass that extending our abstract class has many common methods
or attributes or requires access modifiers other than
public
 When we want to declare non-static and non-final attributes.
Use Interfaces:

 When we expect that an unrelated class may implement our code. For example, a
smartphone implementing a calculator interface.
 When we want to use the multiple inheritance.

Summary
 Interfaces
o Interfaces are similar to abstract classes. It cannot be instantiated and
consists of abstract methods.

o Attributes inside the interfaces are

public

static

and

final

by default.

o Methods inside the interfaces are

public

and

abstract

by default

 Default Methods in Interfaces


o Through default methods, we can provide the implementation of a
method inside the interface.

o The

default
keyword is used to declare a method in the interface as default method.

 Inheritance with Interfaces

o an interface extends another interface.

o a class implements an interface.

o a class extends another class.

 Multiple Inheritance
o a single class/interface can inherit multiple interfaces.

o a single class can extend another class and implement multiple interfaces.

 Multiple inheritance is not possible among classes i.e., a single class cannot
extend multiple classes.

Errors & Exceptions


Concepts
 Errors & Exceptions
 Handling Exceptions
 Raising Exceptions

Introduction
When executing Java code, different errors and exceptions might occur. There can
be many reasons for these errors and exceptions like coding mistakes committed by the
programmer, environmental issues like insufficient memory, network issues, etc.

To build a reliable, robust application and provide a good experience to the user we
need to handle them properly.

1. Errors & Exceptions


Errors
Errors in Java occur due to syntactical errors, infinite recursion, and many other
reasons. The most common are syntactical errors that occur when a programmer
violates the rules of Java programming language.

Code

1
2
3
4
5
class Main (
public static void main(String[] args) {
System.out.println("Hello world!");
}
)
JAVA

Output

Main.java:1: error: '{' expected


class Main (
^
...
In the above code, we are using parenthesis

()
instead of curly braces
{}
which results in an error.

Exceptions
Even when our code is syntactically correct, it may cause an error when an attempt is
made to execute it.

Errors detected during execution are called Exceptions.

Example 1: Dividing a number by zero.

Code

1
2
3
4
5
6
7
8
class Main {
public static void main(String[] args) {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
}
}
JAVA

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Main.main(Main.java:5)
The above code is syntactically correct, but we are trying to divide a number with zero
which results in an exception during execution.

1.1 Error and Exception Hierarchy


The

Throwable
class is the root class in the hierarchy and from there the hierarchy splits into two
branches Error and Exception.
1.2 Types of Exceptions
In Java, exceptions are of two types,

1. Unchecked Exceptions
2. Checked Exceptions

Unchecked Exceptions
The Unchecked exceptions mostly occur due to the errors committed by the
programmer. These exceptions are not checked at the compile-time but are checked at
the run-time. These exceptions are also known as runtime exceptions.

Example 1: Out-of-bounds array access

Code

1
2
3
4
5
6
7
class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(arr[6]);
}
}
JAVA

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index


6 out of bounds for length 4
at Main.main(Main.java:5)
The above code is syntactically correct, but we are trying to access the array index
which is out of range which results in an unchecked exception

ArrayIndexOutOfBoundsException
during execution.
Comparison with Python

Code

1
2
list_a = [1, 2, 3, 4]
print(list_a[6])
PYTHON

Output

IndexError: list index out of range

Checked Exceptions
These are the exceptions that are checked by the compiler during the compile-time.
These exceptions are also called as IOExceptions.

Some examples of checked exceptions are:

 Trying to open a file that doesn't exist results in


FileNotFoundException
which is a checked exception.
 Trying to read beyond the end of the file.

2. Handling Exceptions
Similar to python's

try...except
block, in Java, we have
try...catch
block to handle the exceptions.

Syntax

1
2
3
4
5
6
7
8
9
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
}
JAVA

The

try
block includes the code that might generate an exception.
The

catch
block includes the code that is executed when there occurs an exception inside the try
block.

Code

1
2
3
4
5
6
7
8
9
10
11
12
class Main {
public static void main(String[] args) {
try {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Denominator can't be 0");
}
}

JAVA
Expand

Output

Denominator can't be 0

Comparison with Python

Code

1
2
3
4
5
6
7
try:
num_1 = 5
num_2 = 0
result = num_1 / num_2
print(result)
except ZeroDivisionError:
print("Denominator can't be 0")
PYTHON

Output

Denominator can't be 0
2.1 Handling Multiple Exceptions
Similar to Python, in Java we can specify multiple

catch
blocks to handle different types of exceptions.

Syntax

1
2
3
4
5
6
7
8
9
10
11
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
} catch (ExceptionType variableName) {
// body of catch block

JAVA
Expand

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4};
System.out.println(arr[6]);
} catch (ArithmeticException e) {
System.out.println("Invalid value");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of range");
}

JAVA
Expand

Output

Array index out of range

Comparison with Python

Code

1
2
3
4
5
6
7
8
try:
list_a = [1, 2, 3, 4]
print(list_a[6])
except ZeroDivisionError:
print("Denominator can't be 0")
except IndexError:
print("List index out of range")
PYTHON

Output

List index out of range


2.2 Finally Block
Besides the

try...catch
blocks, we also have a
finally
block which is always executed whether an exception occurs inside the
try
block or not.

Syntax

1
2
3
4
5
6
7
8
9
10
11
try {
// body of try block
} catch (ExceptionType variableName) {
// body of catch block
} finally {
// body of finally block
}

JAVA
Expand

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
public static void main(String[] args) {
try {
int num1 = 5;
int num2 = 0;
int result = num1 / num2;
System.out.println(result);
} catch(ArithmeticException e) {
System.out.println("Denominator can't be 0");
} finally {
System.out.println("Execution completed");

JAVA
Expand

Output

Denominator can`t be 0
Execution completed
In the above code, we are dividing a number by zero inside the

try
block, which generates
ArithmeticException
. The exception is caught by the
catch
block and then the
finally
block is executed

3. Raising Exceptions
In Java, we can throw an exception explicitly using

throw
keyword.

Code

1
2
3
4
5
6
7
8
9
class Main {
public static void main(String[] args) {
try {
throw new ArithmeticException("Denominator can't be 0");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}

JAVA

Output

Denominator can`t be 0

Comparison with Python

In Python, we can throw an exception explicitly using

raise
keyword.

Code

1
2
3
4
try:
raise ZeroDivisionError("Denominator can't be 0")
except ZeroDivisionError as e:
print(str(e))
PYTHON

Output

Denominator can't be 0
`
In the above code, we are explicitly raising an

ArithmeticException
using the
throw
keyword.
The instance of the exception

e
consists of a
getMessage()
method which returns the exception message as a
string

3.1 The
throws

Keyword
In Java,

throws
keyword is used to specify the type of exception that might be thrown by a method.

Syntax

1
2
3
returnType methodName() throws ExceptionType1, ExceptionType2, ... {
// body of the method
}

JAVA

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
static void divideByZero() throws ArithmeticException {
throw new ArithmeticException("Division with zero");
}
public static void main(String[] args) {
try {
divideByZero();
} catch (ArithmeticException e) {
System.out.println(e);
}

JAVA
Expand

Output

java.lang.ArithmeticException: Division with zero


In the above code, we have specified that the

divideByZero()
method might throw an
ArithmeticException
using the
throws
keyword.

Summary
 Errors detected during execution are called exceptions
 The
Throwable
class is a root class from which the Error and Exception classes are derived.
 The exceptions that are not checked at the compile-time but are checked at the
run-time are called Unchecked exceptions.
 The exceptions that are checked at the compile-time are called as checked
exceptions.
 In Java, we can use
try...catch
block for handling exceptions.
 The
finally
block will execute whether an exception occurs inside the
try
block or not.
 In Java, we can throw an exception explicitly using
throw
keyword
 In Java,
throws
keyword is used to specify the type of exception that might be thrown by a
method.

Working with Dates & Times


Concepts
 Representing Date
 Representing Time
 Representing Date & Time
 Formatting Date & Time
 Difference between Dates & Times

Introduction
Java has a built-in

java.time
package which provides various classes to work with date and time.
Commonly used classes in the
java.time
package are:
 LocalDate
class
 LocalTime
class
 LocalDateTime
class
 DateTimeFormatter
class
 Period
class
 Duration
class

1. Working with
LocalDate

class
1.1 Representing Date
Java

LocalDate
class allows us to create a date object and represent a valid date (year, month and
day).
The

of()
method of
LocalDate
class is used to create an instance of
LocalDate
from the given year, month and day.
Code

1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj);
}
}
JAVA

Output

2019-04-13

Comparison with Python

Code

1
2
3
4
from datetime import date
date_obj = date(2019, 4, 13)
print(date_obj)
PYTHON

Output

2019-04-13

Providing invalid inputs to the

of()
method leads to an error.

Code
1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2022, 2, 31);
System.out.println(dateObj);
}
}
JAVA

Output

Exception in thread "main" java.time.DateTimeException: Invalid date


'FEBRUARY 31'

In the above code, we have provided 31 days for the month of February. As the
February month doesn't have 31 days, the

DateTimeException
has been thrown.

1.2 Today's Date


The

LocalDate
class provides
now()
method which returns the date object with today's date.

Code

1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.now();
System.out.println(dateObj);
}
}
JAVA

Output

2022-12-20

1.3 Commonly used methods of LocalDate Object


Method Description

getYear() Returns the year value (2000, 2022...)

getMonth() Returns the month (AUGUST, SEPTEMBER...)

getMonthValue() Returns the month value (1 to 12)

getDayOfMonth() Returns the day of the month (1, 2, 3, ...31)

getDayOfWeek() Returns the day of the week (MONDAY, TUESDAY...)

getValue() Returns the int value of the day of the week (1, 2...7)

plusDays(days) Returns the date object with days added

plusMonths(months) Returns the date object with months added

plusYears(years) Returns the date object with years added

Returns the negative integer if the given date is less, positive integer if the
compareTo(date)
given date is greater

Example 1:

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj.getYear());
System.out.println(dateObj.getMonth());
System.out.println(dateObj.getDayOfWeek());
System.out.println(dateObj.getDayOfWeek().getValue());
}
}

JAVA
Expand

Output

2019
APRIL
SATURDAY
6
Example 2:

Code

1
2
3
4
5
6
7
8
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj = LocalDate.of(2019, 4, 13);
System.out.println(dateObj.plusYears(5));
}
}
JAVA

Output

2024-04-13
Example 3:

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
LocalDate dateObj1 = LocalDate.of(2019, 4, 13);
LocalDate dateObj2 = LocalDate.of(2020, 4, 13);
if (dateObj1.compareTo(dateObj2) < 0) {
System.out.println("dateObj1 < dateObj2");
} else if (dateObj1.compareTo(dateObj2) > 0) {
System.out.println("dateObj1 > dateObj2");
} else {

JAVA
Expand

Output

dateObj1 < dateObj2


In the above example, the

dateObj1
is less than the
dateObj2
. So, the expression
dateObj1.compareTo(dateObj2) < 0
evaluates to
true
and the dateObj1 < dateObj2 is displayed on the console.

2. Working with
LocalTime

class
2.1 Representing Time
Java

LocalTime
class allows us to create a time object and represent a valid time (hours, minutes and
seconds).

Code

1
2
3
4
5
6
7
8
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
LocalTime timeObj = LocalTime.of(11, 34, 56);
System.out.println(timeObj);
}
}
JAVA

Output

11:34:56

2.2 Commonly used methods of LocalTime Object


Method Description

now() Returns the current time

getHour() Returns the hour value

getMinute() Returns the minute value

getSecond() Returns the Seconds value

plusHours(hours) Returns the time object with specified hours added

plusMinutes(minutes) Returns the time object with specified minutes added

plusSeconds(seconds) Returns the time object with specified seconds added

Returns the negative integer if the given time is less, positive integer if the
compareTo(time)
given time is greater

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
LocalTime timeObj = LocalTime.of(11, 34, 56);
System.out.println(timeObj);
System.out.println(timeObj.getHour());
System.out.println(timeObj.getMinute());
System.out.println(timeObj.getSecond());
}
}

JAVA
Expand
Output

11:34:56
11
34
56

Comparison with Python

Code

1
2
3
4
5
6
7
from datetime import time
time_object = time(11, 34, 56)
print(time_object)
print(time_object.hour)
print(time_object.minute)
print(time_object.second)
PYTHON

Output

11:34:56
11
34
56

3. Working with
LocalDateTime

class
3.1 Representing Date and Time
Java
LocalDateTime
class allows us to create a date-time object and represent a valid date and time
together.

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) {
LocalDateTime dateTimeObj = LocalDateTime.of(2018, 11, 28, 10, 15, 26);
System.out.println(dateTimeObj.getYear());
System.out.println(dateTimeObj.getMonthValue());
System.out.println(dateTimeObj.getHour());
System.out.println(dateTimeObj.getMinute());
}
}

JAVA
Expand

Output

2018
11
10
15

Comparison with Python

Code

1
2
3
4
5
6
7
from datetime import datetime
date_time_obj = datetime(2018, 11, 28, 10, 15, 26)
print(date_time_obj.year)
print(date_time_obj.month)
print(date_time_obj.hour)
print(date_time_obj.minute)
PYTHON

Output

2018
11
10
15

4. Working with
DateTimeFormatter

class
4.1 Formatting Date and Time
The

DateTimeFormatter
class have a
ofPattern()
method that creates an instance of the
DateTimeFormatter
for the given pattern of the date, time and date-time like,
 mm/dd/yyyy
 hh/mm/ss

FormatSpecifier Meaning Example

yyyy year with century 2014, 2015


FormatSpecifier Meaning Example

yy year without century 14, 15

MMMM month as full name January, February

MMM month as abbreviated name Jan, Feb

MM month zero-padded decimal number 01, 02, …, 12

M month without zero-padded decimal number 1, 2, …, 12

dd date zero-padded decimal number 01, 02, …, 30

d date without zero-padded decimal number 1, 2, …, 30

a am, pm of the day AM, PM

HH hour with zero-padded decimal number (1 - 24) 01, 02 …, 24

H hour without zero-padded decimal number (1 - 24) 1, 2 …, 24

hh hour with zero-padded decimal number (1 - 12) 01, 02 …, 12

h hour without zero-padded decimal number (1 - 12) 1, 2 …, 12

mm minute with zero-padded decimal number (1 - 60) 01, 02 …, 60

m minute without zero-padded decimal number (1 - 60) 1, 2 …, 60

ss second with zero-padded decimal number (1 - 60) 01, 02 …, 60

s second without zero-padded decimal number (1 - 60) 1, 2 …, 60

The classes

LocalDateTime
,
LocalDate
, etc have the
format()
method which accepts the
DateTimeFormatter
object of the required pattern as an argument and returns a string after formatting the
given localDate, localTime, or the localDatetime object to the specified pattern.
Example 1:

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMM yyyy hh:mm:ss
a");
String formattedDateTime = now.format(format1);
System.out.println(formattedDateTime);
}
}

JAVA
Expand

Output

13 Sep 2022 01:23:46 PM


Example 2:

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMMM yyyy");
String formattedDate = now.format(format1);
System.out.println(formattedDate);
}
}

JAVA
Expand

Output

13 September 2022

4.2 Parsing Date and Time


The

DateTimeFormatter
class have a
parse()
method which creates the respective object (date, time, or date-time) from the give
string.
Example 1:

Code

1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String dateStr = "28 November 2018";
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd MMMM yyyy");
LocalDate date = LocalDate.parse(dateStr, format1);
System.out.println(date);
}
}

JAVA
Expand

Output

2018-11-28

5. Difference Between Dates & Times


5.1 Difference Between Dates
In Java, we have a

Period
class to find the difference between two dates in terms of years, months and days.
We can get the period object as the difference between two dates using

between()
method.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.time.Period;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2020, 2, 20);
LocalDate endDate = LocalDate.of(2021, 10, 21);
Period period = Period.between(startDate, endDate);
System.out.println("Years: " + period.getYears());
System.out.println("Months: " + period.getMonths());

JAVA
Expand

Output

Years: 1
Months: 8
Days: 1

5.2 Difference Between Times


In Java, we have a

Duration
class to find the difference between two times in seconds.

Code

1
2
3
4
5
6
7
8
9
10
11
12
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
LocalTime startTime = LocalTime.of(10, 30, 30);
LocalTime endTime = LocalTime.of(10, 31, 30);
Duration duration = Duration.between(startTime, endTime);
System.out.println(duration.getSeconds());
}

JAVA
Expand

Output

60

You might also like