Object Oriented Programming in Java Course Level Coding Cheat Sheet
Object Oriented Programming in Java Course Level Coding Cheat Sheet
Select the hamburger menu located at the top left of the window to quickly locate code and explanations based on the video name. You can also use the forward and back
arrows to navigate between pages.
This course-level cheat sheet includes code and related explanations from the following videos.
Description Example
Create a Car class, which serves as a blueprint for creating Car objects.
String color;
String model;
int year;
Define attributes of the Car class. The variables color, model, and year store the car's color,
model, and year, respectively.
void displayInfo() {
Print the car details to the console using the System.out.println() function. System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
System.out.println(>System.out.println("Car Year: " + year);
about:blank 1/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This example creates a class named Car and defines three attributes for the Car class: model, color, and year. The displayInfo() method prints the car
details.
Creating an object
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
myCar.color = "Red";
myCar.model = "Toyota";
myCar.year = 2020;
myCar.displayInfo();
Close curly braces to end the main method and class definition. }
}
about:blank 2/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This example declares a reference variable named myCar of type Car. new Car() creates a new object of the Car class and assigns values to the object's
attributes: color, model and year. The displayInfo() method prints the car details.
Description Example
A Java statement used to define a class named Car, which acts as a blueprint for creating Car objects. The variable model is declared
as public, meaning it can be accessed directly from outside the class.
A Java statement to declare a String variable named model to store the car's model name.
Description Example
A Java statement used to define a class named Car, which acts as a blueprint for creating Car objects.
The variable model is declared as public, meaning that it can be accessed directly from outside the
class.
A Java statement to declare a private String variable named color to store the car's color. The private
modifier ensures the color variable can be accessed and modified only within the Car class.
Call the displayColor() method with the private access modifier. This ensures the method can be private void displayColor() {
called only within the Car class and not from other classes.
about:blank 3/79
4/11/25, 6:50 PM about:blank
Description Example
Print the car's color to the console using the System.out.println() function.
}
}
Description Example
A Java statement used to define a class named Car, which acts as a blueprint for creating Car objects.
The variable model is declared as public, meaning that it can be accessed directly from outside the
class.
A Java statement to declare a protected int variable named year to store the car's year. The protected
modifier ensures the year variable is accessible within the same package (default package access) and
by subclasses, even if they are in different packages.
Call the displayYear() method with the protected access modifier. This ensures the method can be
called within the same package and by subclasses, even if they are in different packages.
Print the car's year to the console using the System.out.println() function.
about:blank 4/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
class Car {
A Java statement used to define a class named Car, which acts as a blueprint for creating Car objects.
String model;
A Java statement to declare a String variable named model without any access modifier. If no access
modifier is used, the variable is considered default. Default variables are accessible only within their
own package.
void displayModel() {
Print the car's model to the console using the System.out.println() function.
}
}
Description Example
A Java statement used to define a class named Car, which acts as a blueprint for creating Car
objects. The variable model is declared as public, meaning that it can be accessed directly
from outside the class.
about:blank 5/79
4/11/25, 6:50 PM about:blank
Description Example
A Java statement to declare a static int variable named numberOfCars to keep track of the
total number of Car objects created. Since it's static, its value is shared among all instances of
Car.
public Car() {
A Java statement to declare a constructor. Every time a new Car object is created, this
constructor runs.
numberOfCars++;
A Java statement to increment the numberOfCars variable that keeps track of how many cars
have been instantiated.
Call the displayCount() method without creating an instance of the Car class. This method
can only access static variables such as numberOfCars, not instance variables.
Print the total number of cars to the console using the System.out.println() function.
}
}
Description Example
A Java statement used to define a final class named Vehicle, which acts as a blueprint for creating public final class Vehicle {
Car objects. The final class cannot be extended (inherited) by any other class. This means no
about:blank 6/79
4/11/25, 6:50 PM about:blank
Description Example
subclasses can be created from Vehicle.
A Java statement to declare a final int variable named maxSpeed with the value 120. The final
variable is a constant, meaning that its value cannot be changed once it is assigned. Trying to
modify maxSpeed later in the code will cause a compilation error.
A Java statement to declare a final method named displayMaxSpeed(). The final method cannot be
overridden by subclasses. This ensures the behavior of displayMaxSpeed remains the same in all
instances.
Print the maximum car speed to the console using the System.out.println() function.
}
}
Description Example
A Java statement used to define an abstract class named Shape. This is an abstract class, meaning that it
cannot be instantiated (you cannot create Shape objects directly). It works as a blueprint from which other
classes can inherit.
A Java statement used to define a final class named Vehicle, which acts as a blueprint for creating Car
objects. The final class cannot be extended (inherited) by any other class. This means no subclasses can be
created from Vehicle.
about:blank 7/79
4/11/25, 6:50 PM about:blank
Description Example
A Java statement to describe Circle that extends the Shape class and provides an implementation of the
draw() method.
@Override
A Java annotation to tell the compiler the draw() method in Circle is an override of the abstract method in
Shape.
void draw()
System.out.println("Drawing Circle");
Print the string Drawing Circle to the console using the System.out.println() function.
}
}
}
Using encapsulation
Creating an encapsulated class
Description Example
class Person {
Create the Person class, which serves as a blueprint for creating Person objects.
about:blank 8/79
4/11/25, 6:50 PM about:blank
Description Example
Create private attributes name and age to store the person's name and age. The name and age
attributes cannot be accesse diretly from outside the class.
Use the Java constructor to initialize the name and age variables when a Person object is
created.
this.name = name;
this.age = age;
The keyword this refers to the current object's instance variables. It differentiates instance
variables from method parameters.
Use the Java public method (Getter) to obtain read access to private variables.
return name;
Use the Java public method (Setter) to obtain write access to private variables. public void setName(String name) {
about:blank 9/79
4/11/25, 6:50 PM about:blank
Description Example
this.name = name;
Use the Java public method (Getter) to obtain read access to private variables.
return age;
Use the Java public method (Setter) to obtain write access to private variables.
if (age >= 0) {
Use the Java if statement to ensure age is not negative before assigning.
this.age = age;
Use the Java else statement to specify what to do when the age is negative. } else {
about:blank 10/79
4/11/25, 6:50 PM about:blank
Description Example
Print the string Age cannot be negative to the console using the System.out.println()
function.
}
}
Explanation: This example creates a Person class in which the name and age attributes are declared as private, meaning they cannot be accessed directly from outside the
Person class. The constructor Person(String name, int age) initializes the attributes when a new object of the class is created. getName() and getAge() are getter methods
that allow other classes to read the values of name and age. setName(String name) and setAge(int age) are setter methods that allow other classes to modify the values of
name and age. The setter for age includes validation to ensure age cannot be set to a negative number.
Description Example
A Java class named Main with a main method. The main method is the entry point of the
program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
Create a new instance of the Person class. Assign the value "Alice" to the name attribute
and the value "30" to the age attribute.
Use the getName() getter to obtain and print the value of the name attribute.
Use the getAge() getter to obtain and print the value of the age attribute. System.out.println("Age: " + person.getAge());
about:blank 11/79
4/11/25, 6:50 PM about:blank
Description Example
person.setName("Bob");
person.setAge(25);
Use the setName() setter to assign the value of name attribute to "Bob" and age attribute to
"25".
Use the getName() getter to obtain and print the updated value of the name attribute.
The setAge(-5) call attempts to set an invalid age. Since setAge() has validation logic, it
will print "Age cannot be negative."
}
}
Explanation: This example creates an instance of the Person class with the name "Alice" and age "30". We call the getName() and getAge() getter methods to print the
values. We then update the name and age attributes usint the setName() and setAge() setter methods. When we attempt to set a negative age with setAge(-5), it prints an
error message because of validation included in the setter method.
Using constructors
Creating a default constructor
Description Example
class Dog {
A Java statement used to define a class named Dog, which acts as a blueprint for creating Dog objects.
A Java statement to declare a String variable named name without any access modifier. If no access String name;
modifier is used, the variable is considered default. Default variables are accessible only within their
own package.
about:blank 12/79
4/11/25, 6:50 PM about:blank
Description Example
Dog() {
name = "Unknown";
The default constructor initializes the name variable with the value "Unknown". This ensures every
new Dog object always hasa name, even if the user doesn't provide one.
void display() {
Print the dog's name to the console using the System.out.println() function. Since name was
initialized in the constructor, it always has a value.
}
}
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is public static void main(String[] args) {
required for execution in Java programs.
about:blank 13/79
4/11/25, 6:50 PM about:blank
Description Example
Create an instance of the Dog class using the default constructor. The name variable is automatically set
to "Unknown".
myDog.display();
}
}
Explanation: This example creates an instance of the Dog class with a default constructor that initializes the name attribute to "Unknown". When we create the instance,
the default constructor is invoked automatically.
Description Example
class Dog {
A Java statement used to define a class named Dog, which acts as a blueprint for creating Dog objects.
String name;
A Java statement to declare a String variable named name without any access modifier. If no access
modifier is used, the variable is considered default. Default variables are accessible only within their
own package.
Dog(String dogName) {
When the Dog object is created, the provided dogName value is assigned to the name variable. name = dogName;
Parameterized constructors let you assign a unique name to each Dog object when it is created.
about:blank 14/79
4/11/25, 6:50 PM about:blank
Description Example
void display() {
Print the dog's name to the console using the System.out.println() function. Since name was
initialized in the constructor, it always has a value.
}
}
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is
required for execution in Java programs.
Create an instance of the Dog class. "Buddy" is passed as an argument to the constructor, setting name
to "Buddy".
about:blank 15/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This example creates an instance of the Dog class with a parameterized constructor that takes a string parameter dogName. When we create a Dog instance
with the name "Buddy", the constructor initializes the name attribute with that value.
Description Example
class Car {
A Java statement used to define a class named Car, which acts as a blueprint for
creating Car objects.
String model;
int year;
A Java statement to declare a String variable named model and an int variable
named year without any access modifier. If no access modifier is used, the
variable is considered default. Default variables are accessible only within their
own package.
Car() {
When the Car object is created, it automatically assigns the value "Default
Model" to model and 2020 to year.
Call the display() method without any access modifier. void display() {
about:blank 16/79
4/11/25, 6:50 PM about:blank
Description Example
Print the car's model and year to the console using the System.out.println()
function.
}
}
A Java class named Main with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args).
This method is required for execution in Java programs.
myCar.display();
Call the display() method to print the model and year of the car.
}
}
about:blank 17/79
4/11/25, 6:50 PM about:blank
Explanation: This example creates an instance of the Car class with two attributes model and year. The Car() constructor initializes the model to "Default Model" and year
to 2020. When we create an instance of the Car class with new Car(), the no-arg constructor is called automatically, and the default values are assigned to the attributes.
The display() method prints the model and year of the car.
Constructor overloading
Description Example
class Dog {
A Java statement used to define a class named Dog, which acts as a blueprint for
creating Dog objects.
String name;
int age;
A Java statement to declare a String variable named name and an int variable
named age without any access modifier. If no access modifier is used, the variable
is considered default. Default variables are accessible only within their own
package.
Dog() {
name = "Unknown";
age = 0;
The default constructor initializes the name variable with the value "Unknown"
and age variable with the value 0. This ensures every new Dog object always has a
name and age, even if the user doesn't provide one.
Dog(String dogName) {
name = dogName;
age = 0;
When the Dog object is created, the provided dogName value is assigned to name
while keeping the age as 0 by default. Parameterized constructors let you assign a
unique name to each Dog object when it is created.
about:blank 18/79
4/11/25, 6:50 PM about:blank
Description Example
This is the parameterized constructor that takes two arguments dogName and
dogAge.
name = dogName;
age = dogAge;
When the Dog object is created, the constructor allows the user to specify both
name and age.
void display() {
Print the dog's name and age to the console using the System.out.println()
function. Since name and age were initialized in the constructor, they always have
a value.
}
}
A Java class named Main with a main method. The main method is the entry point public class Main {
of the program.
about:blank 19/79
4/11/25, 6:50 PM about:blank
Description Example
The main method is declared using public static void main(String[] args).
This method is required for execution in Java programs.
Create the dog1 object using the default constructor Dog(). So, name =
"Unknown" and age = 0.
Create the dog2 object using the one-parameter constructor Dog("Charlie"). So,
name = "Charlie" and age = 0 (default).
Create the dog3 object using the two-parameter constructor Dog("Max", 5). So,
name = "Max" and age = 5.
dog1.display();
dog2.display();
dog3.display();
}
}
Explanation: This example has three constructors of the Dog class. Depending on the number of parameters provided when creating an object, the corresponding
constructor is called.
Inheritance in Java
Polymorphism in Java
Interfaces and abstract classes in Java
Inner classes in Java
Keep this summary reading available as a reference as you progress through your course, and refer to this reading as you begin coding with Java after this course!
Inheritance in Java
about:blank 20/79
4/11/25, 6:50 PM about:blank
Creating a superclass
Description Example
class Animal {
Create a superclass named Animal, which serves as a base class for other classes that might inherit from
it.
String name;
void eat() {
Include a method eat() to print the message that the animal is eating.
Print the message to the console using the System.out.println() function. The animal name is displayed
dynamically.
}
}
Creating a subclass
Description Example
The Dog class inherits from the Animal class, meaning it automatically gets all properties and methods
from Animal.
void bark() {
Include a method bark() to print the message that the dog is barking.
about:blank 21/79
4/11/25, 6:50 PM about:blank
Description Example
Print the message to the console using the System.out.println() function. The animal name is displayed
dynamically.
}
}
Using inheritance
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
Creates an instance of the Dog class. The Dog class inherits from the Animal class.
myDog.name = "Buddy";
myDog.eat();
Calls the eat() method from the Animal class, which prints "Buddy is eating.".
Calls the bark() method from the Dog class, which prints "Buddy says woof!". myDog.bark();
about:blank 22/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Description Example
The Puppy class inherits from the Dog class. Since Dog already inherits from Animal, Puppy indirectly
inherits all properties and methods from Animal as well.
void weep() {
Print the message to the console using the System.out.println() function. The animal name is
displayed dynamically.
}
}
Explanation: This is an example of multilevel inheritance. Animal (Superclass) → Dog (Subclass) → Puppy (Subclass of Dog). The Animal class has attribute name and
method eat(). The Dog class inherits from Animal and adds the bark() method. Puppy inherits from Dog and adds the weep() method.
Description Example
The Cat class inherits from the Animal class. Since Animal contains the name variable and eat() method, class Cat extends Animal {
Cat inherits those properties.
about:blank 23/79
4/11/25, 6:50 PM about:blank
Description Example
void meow() {
Print the message to the console using the System.out.println() function. The animal name is displayed
dynamically.
}
}
Explanation: This is an example of hierarchical inheritance because multiple subclasses (Dog and Cat) inherit from the same superclass (Animal). Animal has attribute name
and method eat(). Dog and Cat inherit from Animal, but each adds unique behaviors. Dog adds the bark() method and Cat adds the meow() method.
Method overriding
Description Example
class Animal {
Create a superclass named Animal, which serves as a base class for other classes that might inherit
from it.
void sound() {
Include a sound() method. This method is meant to be overridden by subclasses that define more
specific behavors.
Print the message "Animal makes a sound" to the console using the System.out.println() function.
about:blank 24/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
@Override
Dog overrides the sound() method to provide a specific implementation: "Dog barks". The @Override annotation
tells the compiler that this method replaces the sound() method from Animal.
void sound() {
System.out.println("Dog barks");
}
}
Explanation: In this example, Dog provides its own implementation of sound(), replacing the one in Animal. Method overriding occurs when a subclass provides a specific
implementation of a method already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the
superclass.
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
about:blank 25/79
4/11/25, 6:50 PM about:blank
Description Example
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
The Dog object is stored in an Animal reference. Since Dog overrides the sound() method, Java uses dynamic
method dispatch to call the overridden method in Dog, not in Animal.
myAnimal.sound();
Since myAnimal is a regular Animal object, calling myAnimal.sound() executes the sound() method from the
Animal class.
myDog.sound();
Since myDog refers to a Dog object (even though it's declared as Animal), it calls the overridden sound()
method in Dog due to polymorphism.
}
}
Explanation: The Dog class inherits from Animal, meaning it gets all non-private properties and methods of Animal. Dog overrides the sound() method from Animal,
providing a more specific implementation. Even though myDog is declared as an Animal, Java determines the method to call at runtime, not compile time. When calling
myDog.sound(), Java looks at the actual object type (Dog) and calls sound() from Dog, not Animal.
Polymorphism in Java
Compile-time polymorphism
Description Example
Create a class MathOperations that contains multiple methods for performing class MathOperations {
addition.
about:blank 26/79
4/11/25, 6:50 PM about:blank
Description Example
Include an add method that accepts two int values (a and b).
return a + b;
Add the values of a and b and return the sum to the calling method as an int.
Include an add method that accepts three int values (a, b, and c).
return a + b + c;
Add the values of a, b, and c and return the sum to the calling method as an
int. This method overloads the first add() method because it has different
number of parameters.
Include an add method that accepts two double values (a and b).
Add the values of a and b and return the sum to the calling method as a double. return a + b;
This method overloads both of the previous add() methods, but it works with
double values instead of int.
about:blank 27/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Close curly braces to end the method and the MathOperations class definition.
A Java class named Main with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args).
This method is required for execution in Java programs.
Create an instance of the MathOperations class and assign it to the math object.
Calls the method add(int a, int b) to add two integers (2 + 3) and print the
result to the console.
Calls the method add(double a, double b) to add two double values (2.5 +
3.5) and print the result to the console.
about:blank 28/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: The add() method is overloaded three times in the MathOperations class. Different number of parameters (int a, int b) versus (int a, int b, int c) and different
types of parameters (int versus double). In Java, overloading is based on the method signature, which includes the number and types of parameters. It does not depend on
the return type. The correct method is selected at compile time based on the arguments passed to the add() method. This is an example of compile-time polymorphism (or
static polymorphism).
Description Example
class MathOperations {
Include an add method that accepts two int values (a and b).
return a + b;
Add the values of a and b and return the sum to the calling method as an int.
Include an add method that accepts two double values (a and b).
return a + b;
Add the values of a and b and return the sum to the calling method as a double.
This method overloads both of the previous add() methods, but it works with
double values instead of int.
about:blank 29/79
4/11/25, 6:50 PM about:blank
Description Example
Include an add method that accepts three int values (a, b, and c).
return a + b + c;
Add the values of a, b, and c and return the sum to the calling method as an
int. This method overloads the first add() method because it has different
number of parameters.
}
}
Close curly braces to end the method and the MathOperations class definition.
A Java class named Main with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args).
This method is required for execution in Java programs.
Create an instance of the MathOperations class and assign it to the math object.
Calls the method add(int a, int b) to add two integers (2 + 3) and print the System.out.println("Sum of 2 and 3: " + math.add(2, 3));
result to the console.
about:blank 30/79
4/11/25, 6:50 PM about:blank
Description Example
Calls the method add(double a, double b) to add two double values (2.5 +
3.5) and print the result to the console.
}
}
Explanation: In this example, the MathOperations class has three overloaded add methods. Depending on the number and type of arguments passed to add, Java
determines which method to invoke at compile time. This makes our code more flexible and easier to read.
Description Example
class Animal {
Create a superclass named Animal, which serves as a base class for other classes that might inherit
from it.
void sound() {
Include a sound() method. This method is meant to be overridden by subclasses that define more
specific behavors.
Print the message "Animal makes a sound" to the console using the System.out.println() function.
about:blank 31/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
@Override
Dog overrides the sound() method to provide a specific implementation: "Dog barks". The @Override annotation
tells the compiler that this method replaces the sound() method from Animal.
void sound() {
System.out.println("Dog barks");
}
}
Description Example
@Override
Cat overrides the sound() method to provide a specific implementation: "Cat meows". The @Override annotation
tells the compiler that this method replaces the sound() method from Animal.
about:blank 32/79
4/11/25, 6:50 PM about:blank
Description Example
void sound() {
System.out.println("Cat meows");
}
}
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
The Dog object is stored in an Animal reference. Since Dog overrides the sound() method, Java uses dynamic
method dispatch to call the overridden method in Dog, not in Animal.
Since myAnimal is a regular Animal object, calling myAnimal.sound() executes the sound() method from the myAnimal.sound();
Animal class.
about:blank 33/79
4/11/25, 6:50 PM about:blank
Description Example
The Cat object is stored in an Animal reference. Since Cat overrides the sound() method, Java uses dynamic
method dispatch to call the overridden method in Cat, not in Animal.
myAnimal.sound();
Since myAnimal is a regular Animal object, calling myAnimal.sound() executes the sound() method from the
Animal class.
}
}
Explanation: In this example, Animal is a superclass with a method called sound(). Both Dog and Cat classes extend Animal, providing their own implementation of the
sound() method. When we create an Animal reference and assign it to different subclasses (Dog and Cat), the appropriate sound() method is called at runtime based on the
object type. This allows for more dynamic and flexible code.
Description Example
class Animal {
Create a superclass named Animal, which serves as a base class for other classes that might inherit
from it.
void sound() {
Include a sound() method. This method is meant to be overridden by subclasses that define more
specific behavors.
Print the message "Animal makes a sound" to the console using the System.out.println() function.
about:blank 34/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
@Override
Dog overrides the sound() method to provide a specific implementation: "Dog barks". The @Override annotation
tells the compiler that this method replaces the sound() method from Animal.
void sound() {
System.out.println("Dog barks");
}
}
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for public static void main(String[] args) {
execution in Java programs.
about:blank 35/79
4/11/25, 6:50 PM about:blank
Description Example
myAnimal.sound();
Since myAnimal is a regular Animal object, calling myAnimal.sound() executes the sound() method from the
Animal class.
}
}
Explanation: In this example, even though myAnimal is an Animal, the sound() method from the Dog class is called, demonstrating virtual method behavior.
Description Example
interface Animal {
void sound();
Include a method sound(). Any class that implements this interface must provide an implementation of sound().
Description Example
Create a Dog class that implements the Animal interface. class Dog implements Animal {
about:blank 36/79
4/11/25, 6:50 PM about:blank
Description Example
System.out.println("Bark");
Calling sound() prints "Bark" to the console using the System.out.println() function.
}
}
Description Example
System.out.println("Meow");
Calling sound() prints "Meow" to the console using the System.out.println() function.
about:blank 37/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
dog.sound();
Call sound() on the dog object. This prints the message "Bark".
cat.sound();
Call sound() on the cat object. This prints the message "Meow".
about:blank 38/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: In this example, we define an interface Animal with a method sound(). The Dog and Cat classes implement the Animal interface and provide their own
versions of the sound() method. In the Main class, we create instances of Dog and Cat, calling the sound() method on each to demonstrate polymorphism.
Description Example
void display() {
System.out.println("This is a shape.");
Calling the display() method prints "This is a shape." to the console using the System.out.println()
function.
}
}
Description Example
about:blank 39/79
4/11/25, 6:50 PM about:blank
Description Example
System.out.println("Drawing Circle");
Calling the draw() method prints "Drawing Circle" to the console using the System.out.println() function.
}
}
Description Example
A Java class named Main with a main method. The main method is the entry point of the program.
The main method is declared using public static void main(String[] args). This method is required for
execution in Java programs.
The shape object is instantiated from the Shape class but it refers to a Circle object.
shape.draw();
about:blank 40/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: In this example, we define an abstract class Shape with an abstract method draw() and a concrete method display(). The Circle class extends the Shape
class and provides an implementation for the draw() method. In the Main class, we create an instance of Circle using the Shape reference type to show how it works. The
draw() method executes the overridden version from Circle. The display() method is inherited from Shape and is called as is.
Description Example
class OuterClass {
class InnerClass {
void display();
Include a method display() that accesses OuterVariable from the outer class.
Inner classes have direct access to the outer class's members (including private
ones).
Calling the display() method prints the outerVariable value to the console
using the System.out.println() function. The outerVariable value is
generated dynamically.
about:blank 41/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: In this example, OuterClass contains a variable outerVariable. InnerClass is defined inside OuterClass and has a method display(). This method can
access outerVariable directly.
Description Example
A Java class named Main with a main method. The main method is the entry point of the
program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
Create an instance of the OuterClass. This is necessary because non-static inner classes
require an instance of the outer class to be created first.
Create a classs InnerClass inside the OuterClass. Since InnerClass is a non-static inner
class, it must be created using an instance of OuterClass.
inner.display();
}
}
about:blank 42/79
4/11/25, 6:50 PM about:blank
Explanation: In this example, InnerClass is nested inside OuterClass and has access to all outer class's members. The display() method will print the value of the
outerVariable. The code demonstrates encapsulation in Java.
Description Example
class OuterClass {
void show();
Include a method show() that accesses OuterVariable from the outer class.
Inner classes have direct access to the outer class's members (including
private ones).
Calling the show() method prints the outerVariable value to the console
using the System.out.println() function. The outerVariable value is
generated dynamically.
}
}
}
Explanation: In this example, OuterClass contains a static variable named staticVariable with a value of 20. Since the variable is static, it belongs to the class itself
rather than an instance. Static nested classes do not require an instance of the outer class. It can access staticVariable without an instance of OuterClass. The nested class
keeps related logic inside OuterClass, improving organization.
about:blank 43/79
4/11/25, 6:50 PM about:blank
Description Example
A Java class named Main with a main method. The main method is
the entry point of the program.
nested.show();
}
}
}
Description Example
class OuterClass {
void myMethod() {
Create an OuterClass with a method myMethod() that will define and use a
method-local inner class.
about:blank 44/79
4/11/25, 6:50 PM about:blank
Description Example
inner.display();
}
}
Description Example
interface Greeting {
void greet();
}
greeting.greet();
This calls the overridden greet() method in the anonymous inner class,
printing "Hello from Anonymous Inner Class!".
about:blank 45/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
class Library {
private String libraryName;
public Library(String name) {
this.libraryName = name;
}
The Library class represents a library and has a private variable libraryName
to store its name. A constructor initializes libraryName.
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public void displayBookInfo() {
System.out.println("Library: " + libraryName);
Nested inside Library, this class represents a book. It has two private System.out.println("Book Title: " + title);
attributes: title and author. The Book class has a constructor to initialize System.out.println("Author: " + author);
these attributes. The displayBookInfo() method prints the book's title and }
author. It also accesses libraryName from Library, demonstrating how inner }
classes can access private members of the outer class.
}
}
about:blank 46/79
4/11/25, 6:50 PM about:blank
Description Example
import java.util.ArrayList;
import java.util.List;
Import ArrayList and List from the java.util package to use dynamic lists.
}
}
Explanation: This Java program demonstrates how to use the List interface with an ArrayList implementation to store and manipulate a list of fruit names. ArrayList is a
dynamic array-based implementation of List, allowing for flexible resizing. Elements are added in order and accessed using a zero-based index. The get(index) method
retrieves elements at specific positions.
Description Example
import java.util.LinkedList;
Import the LinkedList class from the java.util package to use a linked list.
about:blank 47/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java program demonstrates how to use a LinkedList to store and manipulate a list of animal names. LinkedList is a doubly linked list implementation
in Java, meaning that elements are linked using pointers. In LinkedList, insertions and deletions are faster compared to ArrayList (especially for large lists).
Description Example
import java.util.HashSet;
Import the HashSet class from the java.util package to store a collection of unique elements.
}
}
Explanation: This Java program demonstrates the usage of a HashSet, which is a part of the Java Collections Framework and is used to store a collection of unique
elements. HashSet does not maintain any specific order and ignores duplicates. It is useful when you need a collection of distinct elements with fast lookup times.
Description Example
import java.util.HashMap;
Import the HashMap class from the java.util package to store key-value pairs.
Define a class HashMapExample that contains the Java main method. Create a HashMap<String, public class HashMapExample {
Integer> named ageMap. The keys are names (String), and the values are ages (Integer). Add public static void main(String[] args) {
HashMap<String, Integer> ageMap = new HashMap<>();
key-value pair to the HashMap using the put() method. The System.out.println() statement ageMap.put("Alice", 30);
prints the entire HashMap but does not maintain any order because HashMap does not maintain ageMap.put("Bob", 25);
insertion order. The program retrieves Alice's age using ageMap.get("Alice") and stores it in ageMap.put("Charlie", 35);
aliceAge. System.out.println("Age Map: " + ageMap);
int aliceAge = ageMap.get("Alice");
System.out.println("Alice's Age: " + aliceAge);
about:blank 48/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates the usage of a HashMap, which is a part of the Java Collections Framework and is used to store key-value pairs. Keys are
unique (if a duplicate key is added, it replaces the old value). Values can be duplicated. HashMap does not maintain any specific order. It provides fast access to values using
keys.
Description Example
import java.util.ArrayList;
}
}
Explanation: This Java program demonstrates the usage of an ArrayList, which is a part of the Java Collections Framework and is used to store a resizable list of
elements. ArrayList elements are added in order and accessed using a zero-based index. The get(index) method retrieves elements at specific positions. ArrayList allows
duplicates and removing elements shifts subsequent elements left (affecting performance for large lists).
Creating a LinkedList
Description Example
Import the LinkedList class from the java.util package to create a linked list. import java.util.LinkedList;
about:blank 49/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates the usage of a LinkedList, which is a part of the Java Collections Framework. LinkedList stores elements in nodes, where
each node contains a reference to the next node. It allows efficient insertion and removal of elements from both ends: addFirst(), addLast(), removeFirst(), and
removeLast(). Accessing elements by index get(index) is slower than in ArrayList, because it requires traversing the list from the beginning. Duplicates are allowed, and
order is maintained. Unlike ArrayList, elements are not shifted after removal (only the references are updated), which can improve performance for certain operations.
Description Example
import java.util.HashSet;
Import the HashSet class from the java.util package to store a collection of unique
elements.
about:blank 50/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates the usage of a HashSet, which is a part of the Java Collections Framework and is used to store a collection of unique
elements. The contains() method provides fast lookup to check if an element exists. The remove() method efficiently removes elements. HashSet does not maintain any
specific order and ignores duplicates. It is useful when you need a collection of distinct elements with fast lookup times.
Creating a TreeSet
Description Example
import java.util.TreeSet;
Import the TreeSet class from the java.util package to store a collection of unique
elements.
}
}
Explanation: This Java program demonstrates the usage of a TreeSet, which is used to store a collection of unique elements. TreeSet elements are always sorted in
ascending order. The contains() method provides fast lookup (uses a Balanced Tree structure). The remove() methokd efficiently deletes elements while maintaining
order. TreeSet is useful when you need a sorted set with fast operations.
Description Example
Use TreeSet: When you need the elements to be sorted in a specific order. For example: If you want to store a TreeSet<Integer> grades = new TreeSet<>();
list of student grades and display them in ascending order, a TreeSet will automatically sort them. grades.add(85);
grades.add(90);
grades.add(70);
// Output: [70, 85, 90]
System.out.println(grades);
about:blank 51/79
4/11/25, 6:50 PM about:blank
Description Example
Use HashSet: When the order of elements does not matter. For example: If you are storing unique user IDs and
do not care about their order.
Description Example
Use TreeSet: When you can afford slower operations but need the elements
sorted. For Example: If you are maintaining a leaderboard that requires
sorted scores, a TreeSet is suitable even if it's slightly slower.
Description Example
Using TreeSet to avoid duplicates. A TreeSet<String> named sortedFruits is created. TreeSet<String> sortedFruits = new TreeSet<>();
"Apple" and "Banana" are added. A duplicate "Apple" is added but ignored because sortedFruits.add("Apple");
sortedFruits.add("Banana");
TreeSet also does not allow duplicates. Unlike HashSet, TreeSet automatically sorts
sortedFruits.add("Apple"); // Duplicate will not be added
elements in ascending order. The output is always [Apple, Banana], since TreeSet System.out.println(sortedFruits); // Output: [Apple, Banana]
maintains sorted order.
about:blank 52/79
4/11/25, 6:50 PM about:blank
Description Example
Description Example
import java.util.LinkedList;
import java.util.Queue;
Import the java.util.LinkedList and java.util.Queue packages to use the Queue interface
with a LinkedList implementation.
}
}
Explanation: This Java program demonstrates the use of a Queue data structure using the LinkedList class. The method offer() adds an element to the queue (enqueue),
poll() removes and returns the front element (dequeue). LinkedList as a queue implements FIFO (First-In-First-Out) behavior.
Description Example
import java.util.PriorityQueue;
about:blank 53/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates the usage of a PriorityQueue, which is a type of queue where elements are processed based on their priority (natural order
by default for numbers). The method offer() adds an element to the queue (enqueue), poll() removes and returns the element with the highest priority (smallest number
in this case). Heap-based Implementation ensures efficient insertions and deletions.
Description Example
import java.util.LinkedList;
import java.util.Queue;
about:blank 54/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java program simulates a customer service queue using a Queue (FIFO - First In, First Out) implemented with a LinkedList. It models how customers
arrive, wait, and are served in order. The method offer() adds customers to the queue and poll() removes customers in FIFO order. LinkedList as a queue mimics a real
world waiting line. This approach can be extended to simulate bank queues, call centers, or ticket counters.
Description Example
import java.util.HashMap;
}
}
Explanation: This Java program demonstrates the usage of a HashMap, a data structure that stores key-value pairs and allows fast access to values using keys. put(K key,
V value) adds or updates a key-value pair, get(K key) retrieves the value for a key, keySet() returns all keys, containsKey(K key) checks if a key exists, and remove(K
key) deletes a key-value pair.
Using a HashMap
about:blank 55/79
4/11/25, 6:50 PM about:blank
Description Example
Initialize a HashMap<String, Integer> named wordCount, where the keys are words for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
(Strings) and the values are the count of occurrences of each word (Integers). Define the }
input text containing a string with multiple repeated words. The split() method splits the
text string into a words array based on spaces. A for loop iterates over each word in the
words array. The wordCount.getOrDefault(word, 0) method retrieves the current count of
the word if it exists. If the word is not yet in the map, it defaults to 0. The +1 increments
the count for each occurrence and put(word, newCount) updates the count in the HashMap.
Explanation: This Java code snippet demonstrates how to use a HashMap to count the occurrences of words in a given text string. This approach is useful for word
frequency analysis in text processing. The split(" ") function splits text into words. HashMap efficiently tracks word occurrences. getOrDefault(key, defaultValue)
avoids null values.
Creating a TreeMap
Description Example
import java.util.TreeMap;
}
}
Explanation: This Java program demonstrates the use of a TreeMap, a data structure that stores key-value pairs in sorted order based on keys. TreeMap maintains sorted
order (ascending by default).
Using a TreeMap
about:blank 56/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java code snippet demonstrates the use of a TreeMap to store and display a sorted leaderboard of players and their scores. TreeMap stores entries in key-
sorted order (ascending). put(K key, V value) adds key-value pairs, get(K key) retrieves the value for a given key, and keySet() returns keys in sorted order.
Description Example
import java.util.ArrayList;
public class Library {
private ArrayList<String> books;
public Library() {
books = new ArrayList<>();
}
Import the ArrayList class from the java.util package, which is a part of Java's Collection public void displayBooks() {
System.out.println("Books in the Library:");
Framework and is used to store a dynamic list. Create the Library class to represent a collection of
for (String book : books) {
books. The books variable is a private ArrayList<String>, meaning it stores book titles as strings and System.out.println(book);
it cannot be accessed directly from outside the class. The Library() constructor initializes the books }
list when a Library object is created. The addBook() method adds a new book to the books list. The }
displayBooks() method prints all books stored in the books list using a for-each loop. The main
public static void main(String[] args) {
method creates a Library object named myLibrary, adds two books: "The Great Gatsby" and "To Kill
Library myLibrary = new Library();
a Mockingbird", and calls the displayBooks() method to print the book list. myLibrary.addBook("The Great Gatsby");
myLibrary.addBook("To Kill a Mockingbird");
myLibrary.displayBooks();
}
}
Close curly braces to end the main and Library class definition.
Description Example
about:blank 57/79
4/11/25, 6:50 PM about:blank
Description Example
it cannot be accessed directly from outside the orders = new HashMap<>();
class. It is encapsulated to ensure data integrity. }
The Java constructor OrderManagement() public void addOrder(int orderId, String customerName) {
initializes the orders HashMap when an orders.put(orderId, customerName);
OrderManagement object is created. The }
addOrder() method adds a new order using the
.put(orderId, customerName) method. If the public void displayOrders() {
System.out.println("Customer Orders:");
same orderId is added again, it overwrites the for (int orderId : orders.keySet()) {
previous entry. The displayOrders() method System.out.println("Order ID: " + orderId + ", Customer Name: " + orders.get(orderId));
iterates over the HashMap using keySet() to get }
all order IDs, retrieves and prints the }
corresponding customer names. The main
public static void main(String[] args) {
method creates an instance of OrderManagement, OrderManagement orderManagement = new OrderManagement();
adds two orders: Order #101 for Alice and Order orderManagement.addOrder(101, "Alice");
#102 for Bob, and calls the displayOrders() orderManagement.addOrder(102, "Bob");
method to show all orders. orderManagement.displayOrders();
}
}
Explanation: This Java program implements a basic Order Management system using a HashMap to store and manage customer orders. The program uses
HashMap<Integer, String>, which stores Keys (Integer) to represent Order IDs and Values (String) to represent Customer Names.
Description Example
import java.util.HashSet;
public EmployeeManager() {
employees = new HashSet<>();
}
Close curly braces to end the main and EmployeeManager class definition. }
}
about:blank 58/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java program implements a basic Employee Management system using a HashSet to store and manage employee names. It uses LinkedHashSet to
maintain insertion order and TreeSet to store employees in sorted order.
Description Example
import java.util.LinkedList;
public TaskManager() {
tasks = new LinkedList<>();
}
manager.completeTask();
manager.displayTasks();
}
}
Close curly braces to end the main and TaskManager class definition.
Explanation: This Java program implements a simple Task Manager using a LinkedList to store and manage tasks. It supports fast insertions/removals at both ends for
addFirst() and removeFirst().
Description Example
Import the HashSet class from the java.util package, which is a part of Java's Collection import java.util.HashSet;
Framework and is used to store a dynamic list. Create the SocialMedia class with a HashMap
public class SocialMedia {
where Key (String) represents a user and Value (HashSet<String>) stores a set of followers private HashMap<String, HashSet<String>> userFollowers;
(ensuring uniqueness). The constructor SocialMedia() initializes userFollowers as an empty
about:blank 59/79
4/11/25, 6:50 PM about:blank
Description Example
HashMap. The addFoower() method ensures the user exists in the HashMap using the public SocialMedia() {
putIfAbsent(user, new HashSet<>()) method and adds the follower to the user's HashSet userFollowers = new HashMap<>();
}
(no duplicates allowed). The displayFollowers() method checks if the user exists, prints all
followers of the user, and handles missing users by displaying "No followers found". The public void addFollower(String user, String follower) {
Java main method creates an instance of SocialMedia class, adds followers: "Bob" follows userFollowers.putIfAbsent(user, new HashSet<>());
"Alice", "Charlie" follows "Alice", and displays Alice's followers. userFollowers.get(user).add(follower);
}
}
}
Close curly braces to end the main and EmployeeManager class definition.
Explanation: This Java program implements a basic social media follower system using HashMap and HashSet. HashSet ensures no user follows the same person twice. If a
user has no followers, it prints "No followers found". HashMap provides average time complexity for lookups. Followers cannot be accessed directly, only through class
methods.
Java File Handling / Working with File Input and Output Streams
Using the File class
Description Example
import java.io.File;
Import the File class, which provides methods for file and directory operations.
Define a class FileExample that contains the Java main method. Create a File object representing public class FileExample {
a file named example.txt. This does not create the actual file, just a reference to it. Call the public static void main(String[] args) {
File myFile = new File("example.txt");
exists() method on the File object to check whether the file physically exists in the specified
location. If the file exists, prints "File exists.", otherwise print "File does not exist.". // Check if the file exists
if (myFile.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
about:blank 60/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates how to check whether a file exists in the filesystem using the File class from the java.io package.
Writing to Files
Description Example
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
Import the FileWriter class for writing character data to a file, the
BufferedWriter class that wraps FileWriter to provide efficient writing
operations, and the IOException class to handle input/output exceptions.
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine(); // Adds a new line
Define a class WriteToFile that contains the Java main method. Create a bufferedWriter.write("This is a Java file handling example.");
FileWriter class to write to the file "output.txt". A BufferedWriter is
wrapped around FileWriter for more efficient writing. Write text to the file bufferedWriter.close(); // Always close the writer
using the write() method. The newLine() method inserts a newline System.out.println("Data written to file successfully.");
} catch (IOException e) {
character (\n). The close() method closes the writer to ensure all data is System.out.println("An error occurred: " + e.getMessage());
flushed to the file. A confirmation message is printed to the console. The }
catch() call catches IOException if any file operation fails (for example,
permission issues, disk space) and prints an error message.
}
}
Explanation: This Java program demonstrates how to write text to a file using the FileWriter and BufferedWriter package. It writes multiple lines to the file, handles
exceptions properly, and closes the file to prevent resource leaks.
Description Example
Import the FileReader class that reads character-based data from a file, the import java.io.BufferedReader;
BufferedReader class that provides efficient reading capabilities by buffering import java.io.FileReader;
import java.io.IOException;
input, and the IOException class to handle errors that may occur during file
operations.
about:blank 61/79
4/11/25, 6:50 PM about:blank
Description Example
String line;
while ((line = bufferedReader.readLine()) != null) {
Define a class ReadFromFile that contains the Java main method. Create a System.out.println(line);
FileReader class to read the file "output.txt". A BufferedReader is wrapped }
around FileReader for more efficient reading. Call readLine() reads one line at
a time from the file. The loop continues until readLine() returns null bufferedReader.close();
} catch (IOException e) {
(indicating the end of the file). Each line is printed to the console. The System.out.println("An error occurred: " + e.getMessage());
bufferedReader.close() method ensures the file resource is released after }
reading is complete. The catch() call catches IOException if any file operation
fails (for example, permission issues, disk space) and prints an error message.
}
}
Explanation: This Java program reads a file line by line using FileReader and BufferedReader and prints its content to the console. It reads and prints lines the file line by
line, handles exceptions properly, and closes the file to prevent resource leaks.
Description Example
import java.io.FileInputStream;
import java.io.IOException;
Import the FileInputStream class for reading raw byte data from a file and the
IOException class to handle input/output exceptions.
Define a class ReadBytes that contains the Java main method. Declare a public class ReadBytes {
FileInputStream variable, but don't initialize it. Open "example.txt" for reading. Read public static void main(String[] args) {
FileInputStream fileInputStream = null;
one byte at a time until the end of the file is reached. The method byteData() converts try {
the byte into a character and prints it. If an I/O error occurs, an error stack trace is // Create a FileInputStream to read from a file
printed. The finally block ensures the file stream is closed, preventing resource leaks. fileInputStream = new FileInputStream("example.txt");
The method fileInputStream.close() closes the file to free system resources.
// Variable to hold the byte data
int byteData;
// Read bytes until end of file
while ((byteData = fileInputStream.read()) != -1) {
// Print the byte data as characters
System.out.print((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the stream to free resources
if (fileInputStream != null) {
try {
fileInputStream.close();
about:blank 62/79
4/11/25, 6:50 PM about:blank
Description Example
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Explanation: This Java program reads a file byte by byte using FileInputStream and prints its contents to the console.
Writing bytes
Description Example
import java.io.FileOutputStream;
import java.io.IOException;
Import the FileOutputStream class for writing raw byte data to a file and the
IOException class to handle input/output exceptions.
// Data to write
String data = "Hello, World!";
// Convert the string to bytes
byte[] byteData = data.getBytes();
about:blank 63/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java program, writes the string "Hello, World!" to a file named output.txt using a FileOutputStream. It uses exception handling to catch possible file
operation errors and uses a finally block to ensure the file stream is always closed.
Description Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
Import the FileInputStream class for reading faw byte data from a file,
FileOutputStream class for writing raw byte data to a file, and the IOException
class to handle input/output exceptions.
try {
// Create FileInputStream to read from "source.txt"
inputFile = new FileInputStream("source.txt");
// Create FileOutputStream to write to "destination.txt"
outputFile = new FileOutputStream("destination.txt");
int byteData;
// Read bytes from source and write them to destination
while ((byteData = inputFile.read()) != -1) {
Decleare FileInputStream inputFile to reads data from source.txt and outputFile.write(byteData);
FileOutputStream outputFile to write data to destination.txt. The try block }
initializes inputFile to read from source.txt, initializes outputFile to write to
System.out.println("File copied successfully!");
destination.txt, reads bytes from source.txt one byte at a time using
inputFile.read(), writes each byte to destination.txt using } catch (IOException e) {
outputFile.write(byteData), continues until reaching the end of the file (-1), and e.printStackTrace();
prints "File copied successfully!" after completion. The catch block prints the stack } finally {
// Close both streams
trace if an IOException occurs (for example, file not found, read/write error). The
try {
finally bock ensures both inputFile and outputFile are closed to free system if (inputFile != null) inputFile.close();
resources. It uses null checks to prevent NullPointerException. if (outputFile != null) outputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Explanation: This Java program copies the contents of a file named source.txt into another file named destination.txt using FileInputStream and FileOutputStream. It
reads and writes files one byte at a time and uses finally to always close file streams. The program catches IOException to prevent crashes.
Description Example
import java.io.File;
}
}
Explanation: This Java program creates a directory (including nested directories) if it does not already exist. It handles success and failure cases gracefully.
Description Example
import java.io.File;
Define a class ListDirectoryContents that contains the Java main method. public class ListDirectoryContents {
The String directoryPath = "Projects/Java" specifies the directory public static void main(String[] args) {
String directoryPath = "Projects/Java";
whose contents will be listed. Create a File object for the directory by File directory = new File(directoryPath);
calling the File(directoryPath) method. The File object represents the
directory but does not perform any operations yet. The directory.list() // List all files and directories in the specified directory
method returns an array of filenames that exist in the directory. If the String[] contents = directory.list();
directory does not exist or is empty, list() returns null. The if (contents
if (contents != null) {
!= null) method ensures the directory exists and is not empty before
System.out.println("Contents of " + directoryPath + ":");
proceeding. If contents is null, it prints: "The directory is empty or does for (String fileName : contents) {
not exist." If the directory contains files/subdirectories, the program prints System.out.println(fileName);
"Contents of Projects/Java:", iterates through the contents array and }
prints each filename. } else {
System.out.println("The directory is empty or does not exist.");
}
about:blank 65/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program lists all files and subdirectories inside a directory and handles cases where the directory is empty or does not exist
It uses the File.list() method to retrieve directory contents efficiently.
Deleting a directory
Description Example
import java.io.File;
}
}
Explanation: This Java program uses the File.delete() method to delete a specified directory if it exists. The program handles success and failure cases gracefully.
Description Example
about:blank 66/79
4/11/25, 6:50 PM about:blank
Description Example
file and directory paths in a platform-independent import java.io.IOException;
way, java.nio.file.Paths to create Path instances,
and java.io.IOException to handle potentila I/O
errors.
}
}
Explanation: This Java program creates a directory using Java NIO (New Input/Output) instead of the traditional File class. It handles success and failure cases gracefully
and works cross-platform.
Description Example
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Import Java class java.nio.file.Files for import java.io.IOException;
file and directory operations, import java.util.Scanner;
java.nio.file.Path to represent file and
directory paths in a platform-independent
way, java.nio.file.Paths to create Path
instances, java.io.IOException to handle
potentila I/O errors, and java.util.Scanner
for handling user input.
about:blank 67/79
4/11/25, 6:50 PM about:blank
Description Example
a specified directory, and "4" exits the case "2": listDirectory(scanner); break;
program. case "3": deleteDirectory(scanner); break;
case "4": scanner.close(); return;
default: System.out.println("Invalid choice.");
}
}
}
Files.list(path).forEach(System.out::println);
The listDirectory() method lists the } catch (IOException e) {
contents of a directory and reads directory System.err.println("Error: " + e.getMessage());
name from user input. It uses }
}
Files.list(path) to retrieve the directory
and prints each file/subdirectory. If the
directory doesn't exist or an error occurs, it
prints "Error: message".
}
}
Explanation: This Java program provides a simple command-line interface for managing directories inside a "Documents" folder. It allows users to create, list, and delete
directories using Java NIO (New Input/Output).
about:blank 68/79
4/11/25, 6:50 PM about:blank
Description Example
import java.time.LocalDate;
Import the LocalDate class, which is part of the Java Date and Time API.
Define a public class LocalDateExample that contains the Java main method. Use LocalDate.now() to
retrieve the current date and print it in the "YYYY-MM-DD" format, which is the default format of
LocalDate.toString().
}
}
Explanation: This Java program demonstrates the use of the LocalDate class from the java.time package to get and display the current date.
Description Example
import java.time.LocalTime;
Import the LocalTime class, which is part of the Java Date and Time API.
about:blank 69/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates the use of the LocalTime class from the java.time package to get and display the current time.
Description Example
import java.time.LocalDateTime;
Import the LocalDateTime class, which is part of the Java Date and Time API.
}
}
Explanation: This Java program demonstrates the use of the LocalDateTime class from the java.time package to get and display the current date and time. LocalDateTime
is an immutable class that represents both date and time without a time zone.
Description Example
import java.time.ZonedDateTime;
Import the ZonedDateTime class, which is part of the Java Date and Time
API.
Define a public class ZonedDateTimeExample that contains the Java main public class ZonedDateTimeExample {
method. Use ZonedDateTime.now() to retrieve the current system date and public static void main(String[] args) {
ZonedDateTime zonedNow = ZonedDateTime.now();
time, including the time zone. Print the current date, time, and zone in the System.out.println("Current date and time with zone: " + zonedNow);
default ISO-8601 format.
about:blank 70/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates how to use the ZonedDateTime class from the java.time package to retrieve and display the current date and time along with
the time zone. It is useful when working with time zones in applications such as scheduling, logging, and internationalization.
Description Example
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Scanner;
Import the LocalDate, LocalTime,
LocalDateTime, ZoneId, ZonedDateTime, and
Scanner classes that are part of the Java
Date and Time API.
Define a public class with the Java main public static void main(String[] args) {
method and use it to accept user input for Scanner scanner = new Scanner(System.in);
event details. This class captures name, date, // Input event details
time, and timeZone from user input. The System.out.println("Enter event name:");
method Event(name, date, time, String name = scanner.nextLine();
timeZone) creates an event object through
user input. The method getEventDateTime() System.out.println("Enter event date (YYYY-MM-DD):");
String dateInput = scanner.nextLine();
displays the event date an time in the LocalDate date = LocalDate.parse(dateInput);
specified time zone. The method
ZonedDateTime converts eventDateTime to System.out.println("Enter event time (HH:MM):");
the system's local time zone. The method String timeInput = scanner.nextLine();
scanner.close() closes the scanner to free LocalTime time = LocalTime.parse(timeInput);
up resources. System.out.println("Enter time zone (e.g., America/New_York):");
String zoneInput = scanner.nextLine();
ZoneId timeZone = ZoneId.of(zoneInput);
about:blank 71/79
4/11/25, 6:50 PM about:blank
Description Example
// Create the event
Event event = new Event(name, date, time, timeZone);
scanner.close();
}
}
Explanation: This Java program is a simple event management system that allows users to enter an event's details, including its name, date, time, and time zone. It then
converts and displays the event time in both the specified time zone and the system's default time zone.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
about:blank 72/79
4/11/25, 6:50 PM about:blank
Description Example
Explanation: This Java program demonstrates how to format a date using DateTimeFormatter from the java.time package. It formats dates into a human-friendly format.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
}
}
Explanation: This Java program prompts the user to enter their name and birthdate, then formats and displays the birthdate in a more readable format.
Description Example
Import ZoneId which is part of the Java Date and Time API class to represent a time zone, import java.time.ZoneId;
such as "America/New_York", "Asia/Tokyo", and "Europe/London".
about:blank 73/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program demonstrates how to create and display a time zone ID using the java.time package.
Creating a ZoneDateTime
Description Example
import java.time.ZonedDateTime;
import java.time.ZoneId;
}
}
Explanation: This Java program demonstrates how to create and display a time zone ID using the java.time package.
about:blank 74/79
4/11/25, 6:50 PM about:blank
Description Example
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
}
}
Explanation: This Java program simulates scheduling a meeting across different time zones. It converts a fixed UTC meeting time to the local times of participants in
various time zones and displays it in a formatted way.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Create a public class DateParsingExample that contains the Java main public class DateParsingExample {
method and define a string variable dateString to represent date in public static void main(String[] args) {
// Define a date string to parse
the format "yyyy-MM-dd". Create a date formatter using the String dateString = "2025-01-23";
about:blank 75/79
4/11/25, 6:50 PM about:blank
Description Example
DateTimeFormatter.ofPattern("yyyy-MM-dd") method. Use
LocalDate.parse(dateString, formatter) to convert the dateString // Create a DateTimeFormatter to define the expected format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
into a LocalDate object and print the parsed date.
// Parse the string into a LocalDate object
LocalDate date = LocalDate.parse(dateString, formatter);
}
}
Explanation: This Java program demonstrates how to parse a date string into a LocalDate object using the DateTimeFormatter class.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
}
}
Explanation: This Java program demonstrates how to parse a date string with a custom format into a LocalDate object using the DateTimeFormatter class.
Parsing LocalDateTime
about:blank 76/79
4/11/25, 6:50 PM about:blank
Description Example
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
}
}
Explanation: This Java program demonstrates how to parse a date string with a custom format into a LocalDateTime object using the DateTimeFormatter class.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
Import the LocalDate, DateTimeFormatter, and
DateTimeParseException classes, which are part
of the Java Date and Time API class and used to
represent dates without a time zone, define a
pattern for parsing and formatting dates, and
handle errors if the date format is incorrect.
about:blank 77/79
4/11/25, 6:50 PM about:blank
Description Example
}
}
Explanation: This Java program extracts a date from a given sentence, parses it into a LocalDate object, and displays it in a structured format. It also gracefully handles
potential parsing errors.
Description Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
Import the LocalDate, DateTimeFormatter, and
DateTimeParseException classes, which are part of the Java Date and
Time API class and used to represent dates without a time zone,
define a pattern for parsing and formatting dates, and handle errors
if the date format is incorrect.
}
}
Explanation: This Java program extracts multiple dates from a given text, parses them into LocalDate objects, and prints them in a structured format. It also handles
potential errors if any part of the text is not in the expected date format.
Description Example
about:blank 78/79
4/11/25, 6:50 PM about:blank
Description Example
the Java Date and Time API class and used to import java.time.format.DateTimeParseException;
represent dates without a time zone, define a
pattern for parsing and formatting dates, and
handle errors if the date format is incorrect.
}
}
Explanation: This Java program extracts dates from a string containing mixed content (text and dates), parses them into LocalDate objects, and prints the valid dates. If
any date format is invalid, the program gracefully handles the error.
Author(s)
Ramanujam Srinivasan
Lavanya Thiruvali Sunderarajan
about:blank 79/79