OBJECT ORIENTED
PROGRAMMING USING JAVA
EXAMPLES
Contents
Exception Handling Example................................................ 2
Multi-Thread Example ..................................................... 3
Static member Example .................................................... 4
Method Overloading Example................................................ 5
Method Overriding Example................................................. 6
FileReader-FileWriter Example ............................................. 7
BufferedReader-BufferedWriter Example ..................................... 8
FileInputStream – FileOutputStream Example ................................ 9
Sealed Class Example .................................................... 10
ArrayList Example ....................................................... 12
Comparator Example-1 .................................................... 14
Comparator Example-2 .................................................... 15
Base64 Example .......................................................... 17
Functional Interface Example ............................................. 18
LambdaExpressions Example................................................ 19
Exception Handling Example
Multi-Thread Example
Static member Example
class MyClass {
// Static counter variable
private static int objectCount = 0;
// Constructor increments the counter
public MyClass() {
objectCount++;
}
// Static method to get the count
public static int getObjectCount() {
return objectCount;
}
}
public class StaticEx {
public static void main(String[] args) {
[Link]("Initial count: " + [Link]());
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();
[Link]("Count after creating 3 objects: " +
[Link]());
}
}
Method Overloading Example
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two doubles
public double add(double a, double b) {
return a + b;
}
// Overloaded method to concatenate two strings
public String add(String a, String b) {
return a + b;
}
}
public class Overload {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Sum of two integers: " + [Link](5, 10));
[Link]("Sum of three integers: " + [Link](5, 10,
15));
[Link]("Sum of two doubles: " + [Link](3.5, 2.7));
[Link]("Concatenated strings: " + [Link]("Hello",
" World"));
}
}
Method Overriding Example
class Animal {
public void makeSound() {
[Link]("The animal makes a sound");
}
public void eat() {
[Link]("The animal eats food");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
[Link]("The dog barks: Woof! Woof!");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
[Link]("The cat meows: Meow! Meow!");
}
@Override
public void eat() {
[Link]("The cat eats fish");
}
}
public class Overriding {
public static void main(String[] args) {
Animal genericAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
[Link]();
[Link]();
[Link]();
[Link](); // Calls Animal's eat() (not overridden in Dog)
[Link](); // Calls Cat's overridden eat()
}
}
FileReader-FileWriter Example
import [Link].*;
public class TextFileExample {
public static void main(String[] args) {
String fileName = "[Link]";
// Writing to a file
try (FileWriter writer = new FileWriter(fileName)) {
[Link]("Hello, World!\n");
[Link]("This is a text file example.\n");
[Link]("Java File I/O is simple!\n");
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred while writing.");
[Link]();
}
// Reading from a file
try (FileReader reader = new FileReader(fileName)) {
int character;
[Link]("\nFile content:");
while ((character = [Link]()) != -1) {
[Link]((char) character);
}
} catch (IOException e) {
[Link]("An error occurred while reading.");
[Link]();
}
}
}
BufferedReader-BufferedWriter Example
import [Link].*;
public class BufferedFileExample {
public static void main(String[] args) {
String fileName = "buffered_example.txt";
// Writing with BufferedWriter
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(fileName))) {
[Link]("First line\n");
[Link]("Second line\n");
[Link](); // Adds a blank line
[Link]("Final line");
[Link]("File written successfully");
} catch (IOException e) {
[Link]();
}
// Reading with BufferedReader
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
[Link]("\nFile content:");
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}
FileInputStream – FileOutputStream Example
import [Link].*;
public class BinaryFileExample {
public static void main(String[] args) {
String fileName = "[Link]";
byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in ASCII
// Writing binary data
try (FileOutputStream fos = new FileOutputStream(fileName)) {
[Link](data);
[Link]("Binary file written");
} catch (IOException e) {
[Link]();
}
// Reading binary data
try (FileInputStream fis = new FileInputStream(fileName)) {
byte[] buffer = new byte[1024];
int bytesRead = [Link](buffer);
[Link]("\nRead " + bytesRead + " bytes:");
for (int i = 0; i < bytesRead; i++) {
[Link]("%02X ", buffer[i]);
}
} catch (IOException e) {
[Link]();
}
}
}
Sealed Class Example
// Define a sealed class 'Shape' that permits only Circle, Triangle and
Rectangle
sealed class Shape permits Circle, Rectangle, Triangle {
public double area(){return 0;};
}
// Circle must be either final, sealed, or non-sealed
final class Circle extends Shape {
private final double radius;
public Circle(double radius) {
[Link] = radius;
}
@Override
public double area() {
return [Link] * radius * radius;
}
}
// Rectangle must be either final, sealed, or non-sealed
final class Rectangle extends Shape {
private final double length, width;
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
@Override
public double area() {
return length * width;
}
}
// Triangle is non-sealed, meaning it can be extended freely
non-sealed class Triangle extends Shape {
private final double base, height;
public Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}
// EquilateralTriangle can extend Triangle because Triangle is non-sealed
final class EquilateralTriangle extends Triangle {
public EquilateralTriangle(double side) {
super(side, side * [Link](3)/2);
}
}
public class ShapeCalculator {
public static void describeShape(Shape shape) {
// Pattern matching with switch expressions
String description = switch (shape) {
case Circle c -> "Circle with area " + [Link]();
case Rectangle r -> "Rectangle with area " + [Link]();
case Triangle t -> "Triangle with area " + [Link]();
default -> "No Shape";
};
[Link](description);
}
public static void main(String[] args) {
describeShape(new Circle(5));
describeShape(new Rectangle(4, 6));
describeShape(new Triangle(3, 4));
describeShape(new EquilateralTriangle(5));
}
}
ArrayList Example
import [Link];
import [Link];
import [Link];
import [Link];
public class ArrayListExample {
public static void main(String[] args) {
// 1. Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();
// 2. Add elements (add())
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Initial List: " + fruits); //[Apple, Banana,
Cherry]
// 3. Add at a specific index (add(index, element))
[Link](1, "Mango");
[Link]("After adding Mango at index 1: " + fruits);
// [Apple, Mango, Banana, Cherry]
// 4. Add multiple elements (addAll())
ArrayList<String> moreFruits = new
ArrayList<>([Link]("Grapes", "Orange"));
[Link](moreFruits);
[Link]("After adding more fruits: " + fruits); //
[Apple, Mango, Banana, Cherry, Grapes, Orange]
// 5. Get element by index (get())
String firstFruit = [Link](0);
[Link]("First fruit: " + firstFruit); // Apple
// 6. Check if an element exists (contains())
boolean hasBanana = [Link]("Banana");
[Link]("Contains Banana? " + hasBanana); // true
// 7. Find index of an element (indexOf())
int bananaIndex = [Link]("Banana");
[Link]("Index of Banana: " + bananaIndex); // 2
// 8. Find last index (lastIndexOf())
[Link]("Apple");
[Link]("List with duplicate Apple: " + fruits); //
[Apple, Mango, Banana, Cherry, Grapes, Orange, Apple]
int lastAppleIndex = [Link]("Apple");
[Link]("Last index of Apple: " + lastAppleIndex); //
6
// 9. Update an element (set())
[Link](1, "Pineapple");
[Link]("After replacing Mango with Pineapple: " +
fruits); // [Apple, Pineapple, Banana, Cherry, Grapes, Orange, Apple]
// 10. Remove by index (remove(index))
[Link](0);
[Link]("After removing index 0: " + fruits); //
[Pineapple, Banana, Cherry, Grapes, Orange, Apple]
// 11. Remove by value (remove(Object))
[Link]("Apple");
[Link]("After removing 'Apple': " + fruits); //
[Pineapple, Banana, Cherry, Grapes, Orange]
// 12. Remove all elements matching a collection (removeAll())
ArrayList<String> toRemove = new
ArrayList<>([Link]("Banana", "Grapes"));
[Link](toRemove);
[Link]("After removing Banana & Grapes: " + fruits);
// [Pineapple, Cherry, Orange]
// 13. Clear all elements (clear())
[Link]();
[Link]("After clear(): " + fruits); // []
[Link]("Is list empty? " + [Link]()); // true
// 14. Using for-loop
[Link]("Using for-loop: ");
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
// 15. Using for-each loop
[Link]("\nUsing for-each: ");
for (String item : fruits) {
[Link](item + " ");
}
// 16. Using Iterator
[Link]("\nUsing Iterator: ");
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]() + " ");
}
}
}
Comparator Example-1
import [Link];
import [Link];
import [Link];
public class ComparatorExample {
public static void main(String[] args) {
List<Integer> numbers = [Link](5, 2, 9, 1, 5, 6);
// Sort in natural order (ascending)
[Link]([Link]());
[Link]("Ascending: " + numbers); // [1,2,5,5,6,9]
// Sort in reverse order (descending)
[Link]([Link]());
[Link]("Descending: " + numbers); // [9,6,5,5,2,1]
}
}
Comparator Example-2
import [Link];
import [Link];
import [Link];
class Employee {
private String name;
private int age;
private double salary;
// Constructor, getters, toString
public Employee(String name, int age, double salary) {
[Link] = name;
[Link] = age;
[Link] = salary;
}
public String getName() { return name; }
public int getAge() { return age; }
public double getSalary() { return salary; }
@Override
public String toString() {
return name + " (Age: " + age + ", Salary: $" + salary + ")";
}
}
public class EmployeeSorter {
public static void main(String[] args) {
List<Employee> employees = [Link](
new Employee("John", 30, 50000),
new Employee("Alice", 25, 60000),
new Employee("Bob", 35, 45000)
);
// Sort by name (alphabetical order)
[Link]([Link](Employee::getName));
[Link]("\nSorted by name:");
[Link]([Link]::println);
// Sort by age (ascending)
[Link]([Link](Employee::getAge));
[Link]("\nSorted by age:");
[Link]([Link]::println);
// Sort by salary (descending)
[Link]([Link](Employee::getSalary).reversed()
);
[Link]("\nSorted by salary (descending):");
[Link]([Link]::println);
}
}
Base64 Example
import [Link].Base64;
public class Base64Example {
public static void main(String[] args) {
String original = "Hello, World!";
// Encode
String encoded =
[Link]().encodeToString([Link]());
[Link]("Encoded: " + encoded); //
SGVsbG8sIFdvcmxkIQ==
// Decode
byte[] decodedBytes = [Link]().decode(encoded);
String decoded = new String(decodedBytes);
[Link]("Decoded: " + decoded); // Hello, World!
}
}
Functional Interface Example
@FunctionalInterface
interface Greeter {
void greet(String name); // Single Abstract Method (SAM)
default void defaultMethod() {
[Link]("Default method in functional interface");
}
}
public class FunctionalInterfaceDemo {
public static void main(String[] args) {
// Lambda implementation
Greeter greeter = name -> [Link]("Hello, " + name);
[Link]("Ashish"); // Hello, Ashish
// Method reference implementation
Greeter printer = [Link]::println;
[Link]("Hi Students"); // Hi Students
}
}
LambdaExpressions Example
public class LambdaExpressions {
public static void main(String[] args) {
Runnable greet = () -> [Link]("Hello World!");
[Link](); // Prints "Hello World!"
}
}