Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions Collections/ComparableAndComparatorExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package Collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

// A class that implements Comparable
class Student implements Comparable<Student> {
private int id;
private String name;
private double gpa;

public Student(int id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public double getGpa() {
return gpa;
}

@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", gpa=" + gpa + '}';
}

// Default sorting by ID
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
}

// A comparator to sort by name
class SortByName implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return a.getName().compareTo(b.getName());
}
}

// A comparator to sort by GPA
class SortByGpa implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return Double.compare(b.getGpa(), a.getGpa()); // Descending order
}
}

public class ComparableAndComparatorExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(3, "Charlie", 3.8));
students.add(new Student(1, "Alice", 3.5));
students.add(new Student(2, "Bob", 3.9));

// Sorting using Comparable (default sorting by ID)
Collections.sort(students);
System.out.println("Sorted by ID (Comparable): " + students);

// Sorting using Comparator (by name)
Collections.sort(students, new SortByName());
System.out.println("Sorted by Name (Comparator): " + students);

// Sorting using Comparator (by GPA)
Collections.sort(students, new SortByGpa());
System.out.println("Sorted by GPA (Comparator): " + students);
}
}
28 changes: 28 additions & 0 deletions Collections/IteratorExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package Collections;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Using an iterator
System.out.println("Using Iterator:");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}

// Using an enhanced for loop
System.out.println("\nUsing Enhanced For Loop:");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
25 changes: 25 additions & 0 deletions Collections/ListExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package Collections;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListExample {
public static void main(String[] args) {
// ArrayList example
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
System.out.println("ArrayList: " + arrayList);
System.out.println("Element at index 1: " + arrayList.get(1));

// LinkedList example
List<String> linkedList = new LinkedList<>();
linkedList.add("Dog");
linkedList.add("Cat");
linkedList.add("Elephant");
System.out.println("LinkedList: " + linkedList);
System.out.println("Element at index 1: " + linkedList.get(1));
}
}
24 changes: 24 additions & 0 deletions Collections/MapExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package Collections;

import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// HashMap example
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 1);
hashMap.put("Banana", 2);
hashMap.put("Cherry", 3);
System.out.println("HashMap: " + hashMap);
System.out.println("Value for key 'Banana': " + hashMap.get("Banana"));

// TreeMap example
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Dog", 1);
treeMap.put("Cat", 2);
treeMap.put("Elephant", 3);
System.out.println("TreeMap: " + treeMap); // Keys are sorted
}
}
18 changes: 18 additions & 0 deletions Collections/QueueExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package Collections;

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
public static void main(String[] args) {
// Queue example with LinkedList
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
System.out.println("Queue: " + queue);
System.out.println("Removed element: " + queue.remove());
System.out.println("Queue after removal: " + queue);
System.out.println("Head of the queue: " + queue.peek());
}
}
24 changes: 24 additions & 0 deletions Collections/SetExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package Collections;

import java.util.HashSet;
import java.util.TreeSet;
import java.util.Set;

public class SetExample {
public static void main(String[] args) {
// HashSet example
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
hashSet.add("Apple"); // Duplicates are not allowed
System.out.println("HashSet: " + hashSet);

// TreeSet example
Set<String> treeSet = new TreeSet<>();
treeSet.add("Dog");
treeSet.add("Cat");
treeSet.add("Elephant");
System.out.println("TreeSet: " + treeSet); // Elements are sorted
}
}
26 changes: 26 additions & 0 deletions ExceptionHandling/CheckedVsUncheckedException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ExceptionHandling;

import java.io.FileNotFoundException;
import java.io.FileReader;

public class CheckedVsUncheckedException {
public static void main(String[] args) {
// Unchecked exception (RuntimeException)
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Unchecked exception caught: " + e.getMessage());
}

// Checked exception (must be handled or declared)
try (FileReader fr = new FileReader("nonexistent.txt")) {
// This line will not be reached as the file does not exist.
System.out.println("File opened.");
} catch (FileNotFoundException e) {
System.out.println("Checked exception caught: " + e.getMessage());
} catch (java.io.IOException e) {
System.out.println("I/O Exception: " + e.getMessage());
}
}
}
27 changes: 27 additions & 0 deletions ExceptionHandling/CustomExceptionExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ExceptionHandling;

// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomExceptionExample {
// A method that throws a custom exception
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote.");
} else {
System.out.println("Welcome to vote.");
}
}

public static void main(String[] args) {
try {
validateAge(13);
} catch (InvalidAgeException e) {
System.out.println("Custom exception caught: " + e.getMessage());
}
}
}
17 changes: 17 additions & 0 deletions ExceptionHandling/TryCatchFinallyExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ExceptionHandling;

public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Exception handling
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
// This block is always executed
System.out.println("Finally block executed.");
}
}
}
45 changes: 45 additions & 0 deletions Generics/GenericClassAndMethodExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package Generics;

// A generic class
class Box<T> {
private T content;

public void setContent(T content) {
this.content = content;
}

public T getContent() {
return content;
}
}

public class GenericClassAndMethodExample {
// A generic method
public static <E> void printArray(E[] inputArray) {
for (E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String[] args) {
// Using the generic class
Box<Integer> integerBox = new Box<>();
integerBox.setContent(10);
System.out.println("Integer Box content: " + integerBox.getContent());

Box<String> stringBox = new Box<>();
stringBox.setContent("Hello Generics");
System.out.println("String Box content: " + stringBox.getContent());

// Using the generic method
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"A", "B", "C"};

System.out.print("Integer Array: ");
printArray(intArray);

System.out.print("String Array: ");
printArray(stringArray);
}
}
23 changes: 23 additions & 0 deletions Generics/TypeErasureExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package Generics;

import java.util.ArrayList;
import java.util.List;

public class TypeErasureExample {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Hello");

List<Integer> intList = new ArrayList<>();
intList.add(123);

// At runtime, both lists have the same class due to type erasure
System.out.println("stringList class: " + stringList.getClass());
System.out.println("intList class: " + intList.getClass());
System.out.println("Are they the same class? " + (stringList.getClass() == intList.getClass()));

// The compiler enforces type safety, but the JVM doesn't know about the generic types.
// The following line would cause a compile-time error:
// stringList.add(123);
}
}
47 changes: 47 additions & 0 deletions Generics/WildcardExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package Generics;

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

public class WildcardExample {
// Upper-bounded wildcard: accepts a list of Number or its subclasses
public static double sumOfList(List<? extends Number> list) {
double sum = 0.0;
for (Number n : list) {
sum += n.doubleValue();
}
return sum;
}

// Unbounded wildcard: accepts a list of any type
public static void printList(List<?> list) {
for (Object elem : list) {
System.out.print(elem + " ");
}
System.out.println();
}

// Lower-bounded wildcard: accepts a list of Integer or its superclasses
public static void addIntegers(List<? super Integer> list) {
list.add(10);
list.add(20);
}

public static void main(String[] args) {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println("Sum of integers: " + sumOfList(intList));

List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3);
System.out.println("Sum of doubles: " + sumOfList(doubleList));

System.out.print("Integer list: ");
printList(intList);

System.out.print("Double list: ");
printList(doubleList);

List<Number> numList = Arrays.asList(1, 2.5, 3L);
addIntegers(numList);
System.out.println("List after adding integers: " + numList);
}
}
Loading