0% found this document useful (0 votes)
0 views20 pages

Java Examples

The document provides examples of various concepts in Object-Oriented Programming using Java, including exception handling, multi-threading, method overloading, and overriding. It also covers file I/O operations, sealed classes, ArrayLists, comparators, Base64 encoding, functional interfaces, and lambda expressions. Each example is accompanied by code snippets demonstrating the implementation of these concepts.

Uploaded by

v3756155
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)
0 views20 pages

Java Examples

The document provides examples of various concepts in Object-Oriented Programming using Java, including exception handling, multi-threading, method overloading, and overriding. It also covers file I/O operations, sealed classes, ArrayLists, comparators, Base64 encoding, functional interfaces, and lambda expressions. Each example is accompanied by code snippets demonstrating the implementation of these concepts.

Uploaded by

v3756155
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/ 20

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) {
System.out.println("Initial count: " + MyClass.getObjectCount());

MyClass obj1 = new MyClass();


MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();

System.out.println("Count after creating 3 objects: " +


MyClass.getObjectCount());
}
}
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();

System.out.println("Sum of two integers: " + calc.add(5, 10));


System.out.println("Sum of three integers: " + calc.add(5, 10,
15));
System.out.println("Sum of two doubles: " + calc.add(3.5, 2.7));
System.out.println("Concatenated strings: " + calc.add("Hello",
" World"));
}
}
Method Overriding Example

class Animal {

public void makeSound() {


System.out.println("The animal makes a sound");
}

public void eat() {


System.out.println("The animal eats food");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("The dog barks: Woof! Woof!");
}
}

class Cat extends Animal {

@Override
public void makeSound() {
System.out.println("The cat meows: Meow! Meow!");
}

@Override
public void eat() {
System.out.println("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();

genericAnimal.makeSound();
myDog.makeSound();
myCat.makeSound();

myDog.eat(); // Calls Animal's eat() (not overridden in Dog)


myCat.eat(); // Calls Cat's overridden eat()
}
}
FileReader-FileWriter Example

import java.io.*;

public class TextFileExample {


public static void main(String[] args) {
String fileName = "example.txt";

// Writing to a file
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Hello, World!\n");
writer.write("This is a text file example.\n");
writer.write("Java File I/O is simple!\n");
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing.");
e.printStackTrace();
}

// Reading from a file


try (FileReader reader = new FileReader(fileName)) {
int character;
System.out.println("\nFile content:");
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("An error occurred while reading.");
e.printStackTrace();
}
}
}
BufferedReader-BufferedWriter Example

import java.io.*;

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))) {
writer.write("First line\n");
writer.write("Second line\n");
writer.newLine(); // Adds a blank line
writer.write("Final line");
System.out.println("File written successfully");
} catch (IOException e) {
e.printStackTrace();
}

// Reading with BufferedReader


try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
System.out.println("\nFile content:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream – FileOutputStream Example

import java.io.*;

public class BinaryFileExample {


public static void main(String[] args) {
String fileName = "data.bin";
byte[] data = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello" in ASCII

// Writing binary data


try (FileOutputStream fos = new FileOutputStream(fileName)) {
fos.write(data);
System.out.println("Binary file written");
} catch (IOException e) {
e.printStackTrace();
}

// Reading binary data


try (FileInputStream fis = new FileInputStream(fileName)) {
byte[] buffer = new byte[1024];
int bytesRead = fis.read(buffer);
System.out.println("\nRead " + bytesRead + " bytes:");
for (int i = 0; i < bytesRead; i++) {
System.out.printf("%02X ", buffer[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * 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) {


this.length = length;
this.width = 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) {


this.base = base;
this.height = 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 * Math.sqrt(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 " + c.area();
case Rectangle r -> "Rectangle with area " + r.area();
case Triangle t -> "Triangle with area " + t.area();
default -> "No Shape";
};
System.out.println(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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;

public class ArrayListExample {


public static void main(String[] args) {
// 1. Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();

// 2. Add elements (add())


fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Initial List: " + fruits); //[Apple, Banana,
Cherry]

// 3. Add at a specific index (add(index, element))


fruits.add(1, "Mango");
System.out.println("After adding Mango at index 1: " + fruits);
// [Apple, Mango, Banana, Cherry]

// 4. Add multiple elements (addAll())


ArrayList<String> moreFruits = new
ArrayList<>(Arrays.asList("Grapes", "Orange"));
fruits.addAll(moreFruits);
System.out.println("After adding more fruits: " + fruits); //
[Apple, Mango, Banana, Cherry, Grapes, Orange]

// 5. Get element by index (get())


String firstFruit = fruits.get(0);
System.out.println("First fruit: " + firstFruit); // Apple

// 6. Check if an element exists (contains())


boolean hasBanana = fruits.contains("Banana");
System.out.println("Contains Banana? " + hasBanana); // true

// 7. Find index of an element (indexOf())


int bananaIndex = fruits.indexOf("Banana");
System.out.println("Index of Banana: " + bananaIndex); // 2

// 8. Find last index (lastIndexOf())


fruits.add("Apple");
System.out.println("List with duplicate Apple: " + fruits); //
[Apple, Mango, Banana, Cherry, Grapes, Orange, Apple]
int lastAppleIndex = fruits.lastIndexOf("Apple");
System.out.println("Last index of Apple: " + lastAppleIndex); //
6
// 9. Update an element (set())
fruits.set(1, "Pineapple");
System.out.println("After replacing Mango with Pineapple: " +
fruits); // [Apple, Pineapple, Banana, Cherry, Grapes, Orange, Apple]

// 10. Remove by index (remove(index))


fruits.remove(0);
System.out.println("After removing index 0: " + fruits); //
[Pineapple, Banana, Cherry, Grapes, Orange, Apple]

// 11. Remove by value (remove(Object))


fruits.remove("Apple");
System.out.println("After removing 'Apple': " + fruits); //
[Pineapple, Banana, Cherry, Grapes, Orange]

// 12. Remove all elements matching a collection (removeAll())


ArrayList<String> toRemove = new
ArrayList<>(Arrays.asList("Banana", "Grapes"));
fruits.removeAll(toRemove);
System.out.println("After removing Banana & Grapes: " + fruits);
// [Pineapple, Cherry, Orange]

// 13. Clear all elements (clear())


fruits.clear();
System.out.println("After clear(): " + fruits); // []
System.out.println("Is list empty? " + fruits.isEmpty()); // true

// 14. Using for-loop


System.out.print("Using for-loop: ");
for (int i = 0; i < fruits.size(); i++) {
System.out.print(fruits.get(i) + " ");
}

// 15. Using for-each loop


System.out.print("\nUsing for-each: ");
for (String item : fruits) {
System.out.print(item + " ");
}

// 16. Using Iterator


System.out.print("\nUsing Iterator: ");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
Comparator Example-1

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ComparatorExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 5, 6);

// Sort in natural order (ascending)


numbers.sort(Comparator.naturalOrder());
System.out.println("Ascending: " + numbers); // [1,2,5,5,6,9]

// Sort in reverse order (descending)


numbers.sort(Comparator.reverseOrder());
System.out.println("Descending: " + numbers); // [9,6,5,5,2,1]
}
}
Comparator Example-2

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Employee {
private String name;
private int age;
private double salary;

// Constructor, getters, toString


public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = 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 = Arrays.asList(
new Employee("John", 30, 50000),
new Employee("Alice", 25, 60000),
new Employee("Bob", 35, 45000)
);

// Sort by name (alphabetical order)


employees.sort(Comparator.comparing(Employee::getName));
System.out.println("\nSorted by name:");
employees.forEach(System.out::println);

// Sort by age (ascending)


employees.sort(Comparator.comparingInt(Employee::getAge));
System.out.println("\nSorted by age:");
employees.forEach(System.out::println);

// Sort by salary (descending)


employees.sort(Comparator.comparingDouble(Employee::getSalary).reversed()
);
System.out.println("\nSorted by salary (descending):");
employees.forEach(System.out::println);
}
}
Base64 Example

import java.util.Base64;

public class Base64Example {


public static void main(String[] args) {
String original = "Hello, World!";

// Encode
String encoded =
Base64.getEncoder().encodeToString(original.getBytes());
System.out.println("Encoded: " + encoded); //
SGVsbG8sIFdvcmxkIQ==

// Decode
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
System.out.println("Decoded: " + decoded); // Hello, World!
}
}
Functional Interface Example

@FunctionalInterface
interface Greeter {
void greet(String name); // Single Abstract Method (SAM)

default void defaultMethod() {


System.out.println("Default method in functional interface");
}
}

public class FunctionalInterfaceDemo {


public static void main(String[] args) {
// Lambda implementation
Greeter greeter = name -> System.out.println("Hello, " + name);
greeter.greet("Ashish"); // Hello, Ashish

// Method reference implementation


Greeter printer = System.out::println;
printer.greet("Hi Students"); // Hi Students
}
}
LambdaExpressions Example

public class LambdaExpressions {


public static void main(String[] args) {
Runnable greet = () -> System.out.println("Hello World!");
greet.run(); // Prints "Hello World!"
}
}

You might also like