diff --git a/Collections/ComparableAndComparatorExample.java b/Collections/ComparableAndComparatorExample.java new file mode 100644 index 0000000..d59a727 --- /dev/null +++ b/Collections/ComparableAndComparatorExample.java @@ -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 { + 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 { + @Override + public int compare(Student a, Student b) { + return a.getName().compareTo(b.getName()); + } +} + +// A comparator to sort by GPA +class SortByGpa implements Comparator { + @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 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); + } +} diff --git a/Collections/IteratorExample.java b/Collections/IteratorExample.java new file mode 100644 index 0000000..6900b23 --- /dev/null +++ b/Collections/IteratorExample.java @@ -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 list = new ArrayList<>(); + list.add("Apple"); + list.add("Banana"); + list.add("Cherry"); + + // Using an iterator + System.out.println("Using Iterator:"); + Iterator 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); + } + } +} diff --git a/Collections/ListExample.java b/Collections/ListExample.java new file mode 100644 index 0000000..b4a608c --- /dev/null +++ b/Collections/ListExample.java @@ -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 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 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)); + } +} diff --git a/Collections/MapExample.java b/Collections/MapExample.java new file mode 100644 index 0000000..69d354e --- /dev/null +++ b/Collections/MapExample.java @@ -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 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 treeMap = new TreeMap<>(); + treeMap.put("Dog", 1); + treeMap.put("Cat", 2); + treeMap.put("Elephant", 3); + System.out.println("TreeMap: " + treeMap); // Keys are sorted + } +} diff --git a/Collections/QueueExample.java b/Collections/QueueExample.java new file mode 100644 index 0000000..e57f6e6 --- /dev/null +++ b/Collections/QueueExample.java @@ -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 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()); + } +} diff --git a/Collections/SetExample.java b/Collections/SetExample.java new file mode 100644 index 0000000..98c6280 --- /dev/null +++ b/Collections/SetExample.java @@ -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 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 treeSet = new TreeSet<>(); + treeSet.add("Dog"); + treeSet.add("Cat"); + treeSet.add("Elephant"); + System.out.println("TreeSet: " + treeSet); // Elements are sorted + } +} diff --git a/ExceptionHandling/CheckedVsUncheckedException.java b/ExceptionHandling/CheckedVsUncheckedException.java new file mode 100644 index 0000000..1ac58b9 --- /dev/null +++ b/ExceptionHandling/CheckedVsUncheckedException.java @@ -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()); + } + } +} diff --git a/ExceptionHandling/CustomExceptionExample.java b/ExceptionHandling/CustomExceptionExample.java new file mode 100644 index 0000000..3b07d31 --- /dev/null +++ b/ExceptionHandling/CustomExceptionExample.java @@ -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()); + } + } +} diff --git a/ExceptionHandling/TryCatchFinallyExample.java b/ExceptionHandling/TryCatchFinallyExample.java new file mode 100644 index 0000000..d41a2d4 --- /dev/null +++ b/ExceptionHandling/TryCatchFinallyExample.java @@ -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."); + } + } +} diff --git a/Generics/GenericClassAndMethodExample.java b/Generics/GenericClassAndMethodExample.java new file mode 100644 index 0000000..13303e6 --- /dev/null +++ b/Generics/GenericClassAndMethodExample.java @@ -0,0 +1,45 @@ +package Generics; + +// A generic class +class Box { + private T content; + + public void setContent(T content) { + this.content = content; + } + + public T getContent() { + return content; + } +} + +public class GenericClassAndMethodExample { + // A generic method + public static 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 integerBox = new Box<>(); + integerBox.setContent(10); + System.out.println("Integer Box content: " + integerBox.getContent()); + + Box 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); + } +} diff --git a/Generics/TypeErasureExample.java b/Generics/TypeErasureExample.java new file mode 100644 index 0000000..f87e7c9 --- /dev/null +++ b/Generics/TypeErasureExample.java @@ -0,0 +1,23 @@ +package Generics; + +import java.util.ArrayList; +import java.util.List; + +public class TypeErasureExample { + public static void main(String[] args) { + List stringList = new ArrayList<>(); + stringList.add("Hello"); + + List 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); + } +} diff --git a/Generics/WildcardExample.java b/Generics/WildcardExample.java new file mode 100644 index 0000000..fe6550b --- /dev/null +++ b/Generics/WildcardExample.java @@ -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 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 list) { + list.add(10); + list.add(20); + } + + public static void main(String[] args) { + List intList = Arrays.asList(1, 2, 3); + System.out.println("Sum of integers: " + sumOfList(intList)); + + List 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 numList = Arrays.asList(1, 2.5, 3L); + addIntegers(numList); + System.out.println("List after adding integers: " + numList); + } +} diff --git a/Java8Features/DateTimeAPIExample.java b/Java8Features/DateTimeAPIExample.java new file mode 100644 index 0000000..4773646 --- /dev/null +++ b/Java8Features/DateTimeAPIExample.java @@ -0,0 +1,29 @@ +package Java8Features; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +public class DateTimeAPIExample { + public static void main(String[] args) { + // Working with LocalDate, LocalTime, and LocalDateTime + LocalDate today = LocalDate.now(); + System.out.println("Today's date: " + today); + + LocalTime now = LocalTime.now(); + System.out.println("Current time: " + now); + + LocalDateTime currentDateTime = LocalDateTime.now(); + System.out.println("Current date and time: " + currentDateTime); + + // Formatting dates and times + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); + String formattedDateTime = currentDateTime.format(formatter); + System.out.println("Formatted date and time: " + formattedDateTime); + + // Creating specific dates + LocalDate specificDate = LocalDate.of(2024, 1, 1); + System.out.println("Specific date: " + specificDate); + } +} diff --git a/Java8Features/DefaultAndStaticMethodsExample.java b/Java8Features/DefaultAndStaticMethodsExample.java new file mode 100644 index 0000000..b319041 --- /dev/null +++ b/Java8Features/DefaultAndStaticMethodsExample.java @@ -0,0 +1,33 @@ +package Java8Features; + +interface MyInterface { + // An abstract method + void abstractMethod(); + + // A default method + default void defaultMethod() { + System.out.println("This is a default method."); + } + + // A static method + static void staticMethod() { + System.out.println("This is a static method."); + } +} + +class MyClass implements MyInterface { + @Override + public void abstractMethod() { + System.out.println("Implementation of the abstract method."); + } +} + +public class DefaultAndStaticMethodsExample { + public static void main(String[] args) { + MyClass myClass = new MyClass(); + myClass.abstractMethod(); + myClass.defaultMethod(); // Calling the default method + + MyInterface.staticMethod(); // Calling the static method + } +} diff --git a/Java8Features/LambdaAndFunctionalInterfaceExample.java b/Java8Features/LambdaAndFunctionalInterfaceExample.java new file mode 100644 index 0000000..08167a6 --- /dev/null +++ b/Java8Features/LambdaAndFunctionalInterfaceExample.java @@ -0,0 +1,27 @@ +package Java8Features; + +// A functional interface has only one abstract method +@FunctionalInterface +interface MyFunctionalInterface { + void myMethod(); +} + +public class LambdaAndFunctionalInterfaceExample { + public static void main(String[] args) { + // Using a lambda expression to implement the functional interface + MyFunctionalInterface myFunc = () -> System.out.println("Hello from a lambda expression!"); + myFunc.myMethod(); + + // Another example with a functional interface that takes parameters + MathOperation addition = (a, b) -> a + b; + System.out.println("10 + 5 = " + addition.operate(10, 5)); + + MathOperation subtraction = (a, b) -> a - b; + System.out.println("10 - 5 = " + subtraction.operate(10, 5)); + } +} + +@FunctionalInterface +interface MathOperation { + int operate(int a, int b); +} diff --git a/Java8Features/NewCollectionMethodsExample.java b/Java8Features/NewCollectionMethodsExample.java new file mode 100644 index 0000000..1b5ec77 --- /dev/null +++ b/Java8Features/NewCollectionMethodsExample.java @@ -0,0 +1,23 @@ +package Java8Features; + +import java.util.ArrayList; +import java.util.List; + +public class NewCollectionMethodsExample { + public static void main(String[] args) { + List names = new ArrayList<>(); + names.add("Alice"); + names.add("Bob"); + names.add("Charlie"); + names.add("Anna"); + + // forEach method + System.out.println("Using forEach:"); + names.forEach(name -> System.out.println(name)); + + // removeIf method + System.out.println("\nOriginal list: " + names); + names.removeIf(name -> name.startsWith("A")); + System.out.println("List after removing names starting with 'A': " + names); + } +} diff --git a/Java8Features/OptionalAndMethodReferenceExample.java b/Java8Features/OptionalAndMethodReferenceExample.java new file mode 100644 index 0000000..06a7c04 --- /dev/null +++ b/Java8Features/OptionalAndMethodReferenceExample.java @@ -0,0 +1,54 @@ +package Java8Features; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class OptionalAndMethodReferenceExample { + public static void main(String[] args) { + // Optional example + Optional optionalWithValue = Optional.of("Hello"); + Optional optionalEmpty = Optional.empty(); + + System.out.println("Optional with value: " + optionalWithValue.orElse("Default")); + System.out.println("Empty optional: " + optionalEmpty.orElse("Default")); + + optionalWithValue.ifPresent(value -> System.out.println("Value is present: " + value)); + optionalEmpty.ifPresent(value -> System.out.println("This will not be printed.")); + + // Method reference example + List names = Arrays.asList("Alice", "Bob", "Charlie"); + + // Using a lambda expression + List upperCaseNamesLambda = names.stream() + .map(name -> name.toUpperCase()) + .collect(Collectors.toList()); + System.out.println("Uppercase (lambda): " + upperCaseNamesLambda); + + // Using a method reference + List upperCaseNamesMethodRef = names.stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + System.out.println("Uppercase (method ref): " + upperCaseNamesMethodRef); + + // Another method reference example (to a constructor) + List people = names.stream() + .map(Person::new) + .collect(Collectors.toList()); + System.out.println("People created with method reference: " + people); + } +} + +class Person { + private String name; + + public Person(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Person{" + "name='" + name + '\'' + '}'; + } +} diff --git a/Java8Features/StreamsAPIExample.java b/Java8Features/StreamsAPIExample.java new file mode 100644 index 0000000..b4d8d93 --- /dev/null +++ b/Java8Features/StreamsAPIExample.java @@ -0,0 +1,29 @@ +package Java8Features; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class StreamsAPIExample { + public static void main(String[] args) { + List names = Arrays.asList("Alice", "Bob", "Charlie", "Anna", "Alex"); + + // A stream pipeline to filter, map, and collect results + List result = names.stream() + .filter(name -> name.startsWith("A")) // Filter names starting with 'A' + .map(String::toUpperCase) // Convert to uppercase + .sorted() // Sort the names + .collect(Collectors.toList()); // Collect the results into a list + + System.out.println("Original list: " + names); + System.out.println("Processed list: " + result); + + // Another example: calculating the sum of squares of numbers + List numbers = Arrays.asList(1, 2, 3, 4, 5); + int sumOfSquares = numbers.stream() + .mapToInt(n -> n * n) + .sum(); + + System.out.println("Sum of squares: " + sumOfSquares); + } +} diff --git a/JavaIO/FileStreamExample.java b/JavaIO/FileStreamExample.java new file mode 100644 index 0000000..a54c726 --- /dev/null +++ b/JavaIO/FileStreamExample.java @@ -0,0 +1,31 @@ +package JavaIO; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +public class FileStreamExample { + public static void main(String[] args) { + String filename = "test.txt"; + String content = "Hello, Java I/O!"; + + // Write to a file using FileOutputStream + try (FileOutputStream fos = new FileOutputStream(filename)) { + fos.write(content.getBytes()); + System.out.println("Successfully wrote to the file."); + } catch (IOException e) { + System.out.println("An error occurred while writing to the file: " + e.getMessage()); + } + + // Read from a file using FileInputStream + try (FileInputStream fis = new FileInputStream(filename)) { + int i; + while ((i = fis.read()) != -1) { + System.out.print((char) i); + } + System.out.println("\nSuccessfully read from the file."); + } catch (IOException e) { + System.out.println("An error occurred while reading the file: " + e.getMessage()); + } + } +} diff --git a/JavaIO/ReaderWriterExample.java b/JavaIO/ReaderWriterExample.java new file mode 100644 index 0000000..078a933 --- /dev/null +++ b/JavaIO/ReaderWriterExample.java @@ -0,0 +1,33 @@ +package JavaIO; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class ReaderWriterExample { + public static void main(String[] args) { + String filename = "test-buffered.txt"; + String content = "Hello, Buffered I/O!"; + + // Write to a file using BufferedWriter + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { + writer.write(content); + System.out.println("Successfully wrote to the file using BufferedWriter."); + } catch (IOException e) { + System.out.println("An error occurred while writing to the file: " + e.getMessage()); + } + + // Read from a file using BufferedReader + try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + System.out.println("Successfully read from the file using BufferedReader."); + } catch (IOException e) { + System.out.println("An error occurred while reading the file: " + e.getMessage()); + } + } +} diff --git a/JavaIO/SerializationExample.java b/JavaIO/SerializationExample.java new file mode 100644 index 0000000..b296e8e --- /dev/null +++ b/JavaIO/SerializationExample.java @@ -0,0 +1,48 @@ +package JavaIO; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +// A class that implements Serializable +class Person implements Serializable { + private static final long serialVersionUID = 1L; + private String name; + private int age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + @Override + public String toString() { + return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; + } +} + +public class SerializationExample { + public static void main(String[] args) { + String filename = "person.ser"; + Person person = new Person("John Doe", 30); + + // Serialization + try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) { + oos.writeObject(person); + System.out.println("Object has been serialized."); + } catch (IOException e) { + System.out.println("An error occurred during serialization: " + e.getMessage()); + } + + // Deserialization + try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) { + Person deserializedPerson = (Person) ois.readObject(); + System.out.println("Object has been deserialized: " + deserializedPerson); + } catch (IOException | ClassNotFoundException e) { + System.out.println("An error occurred during deserialization: " + e.getMessage()); + } + } +} diff --git a/MultiThreading/CountDownLatchExample.java b/MultiThreading/CountDownLatchExample.java new file mode 100644 index 0000000..f2967a0 --- /dev/null +++ b/MultiThreading/CountDownLatchExample.java @@ -0,0 +1,23 @@ +package MultiThreading; + +import java.util.concurrent.CountDownLatch; + +public class CountDownLatchExample { + public static void main(String[] args) throws InterruptedException { + CountDownLatch latch = new CountDownLatch(3); + + Runnable task = () -> { + System.out.println(Thread.currentThread().getName() + " is working."); + latch.countDown(); + System.out.println(Thread.currentThread().getName() + " has finished."); + }; + + new Thread(task, "Worker-1").start(); + new Thread(task, "Worker-2").start(); + new Thread(task, "Worker-3").start(); + + latch.await(); // Main thread waits until the latch count is zero + + System.out.println("All workers have finished their tasks."); + } +} diff --git a/MultiThreading/CyclicBarrierExample.java b/MultiThreading/CyclicBarrierExample.java new file mode 100644 index 0000000..aa6a0c5 --- /dev/null +++ b/MultiThreading/CyclicBarrierExample.java @@ -0,0 +1,27 @@ +package MultiThreading; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +public class CyclicBarrierExample { + public static void main(String[] args) { + CyclicBarrier barrier = new CyclicBarrier(3, () -> { + // This task is executed when all threads reach the barrier + System.out.println("All parties have arrived at the barrier."); + }); + + Runnable task = () -> { + try { + System.out.println(Thread.currentThread().getName() + " is waiting at the barrier."); + barrier.await(); + System.out.println(Thread.currentThread().getName() + " has crossed the barrier."); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + }; + + new Thread(task, "Thread-1").start(); + new Thread(task, "Thread-2").start(); + new Thread(task, "Thread-3").start(); + } +} diff --git a/MultiThreading/ExecutorFrameworkExample.java b/MultiThreading/ExecutorFrameworkExample.java new file mode 100644 index 0000000..863a88f --- /dev/null +++ b/MultiThreading/ExecutorFrameworkExample.java @@ -0,0 +1,29 @@ +package MultiThreading; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class ExecutorFrameworkExample { + public static void main(String[] args) throws ExecutionException, InterruptedException { + ExecutorService executor = Executors.newFixedThreadPool(2); + + // Submitting a Runnable task + executor.submit(() -> { + System.out.println("Runnable task executed by " + Thread.currentThread().getName()); + }); + + // Submitting a Callable task + Callable callableTask = () -> { + System.out.println("Callable task executed by " + Thread.currentThread().getName()); + return 123; + }; + + Future future = executor.submit(callableTask); + System.out.println("Result from callable task: " + future.get()); + + executor.shutdown(); + } +} diff --git a/MultiThreading/LockExample.java b/MultiThreading/LockExample.java new file mode 100644 index 0000000..9797c0f --- /dev/null +++ b/MultiThreading/LockExample.java @@ -0,0 +1,48 @@ +package MultiThreading; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +class LockCounter { + private int count = 0; + private Lock lock = new ReentrantLock(); + + public void increment() { + lock.lock(); + try { + count++; + } finally { + lock.unlock(); + } + } + + public int getCount() { + return count; + } +} + +public class LockExample { + public static void main(String[] args) throws InterruptedException { + LockCounter counter = new LockCounter(); + + Thread t1 = new Thread(() -> { + for (int i = 0; i < 1000; i++) { + counter.increment(); + } + }); + + Thread t2 = new Thread(() -> { + for (int i = 0; i < 1000; i++) { + counter.increment(); + } + }); + + t1.start(); + t2.start(); + + t1.join(); + t2.join(); + + System.out.println("Final count: " + counter.getCount()); + } +} diff --git a/MultiThreading/SemaphoreExample.java b/MultiThreading/SemaphoreExample.java new file mode 100644 index 0000000..540b9d1 --- /dev/null +++ b/MultiThreading/SemaphoreExample.java @@ -0,0 +1,25 @@ +package MultiThreading; + +import java.util.concurrent.Semaphore; + +public class SemaphoreExample { + public static void main(String[] args) { + Semaphore semaphore = new Semaphore(2); // Only 2 threads can access the resource at a time + + Runnable task = () -> { + try { + semaphore.acquire(); + System.out.println(Thread.currentThread().getName() + " has acquired the permit."); + Thread.sleep(1000); + System.out.println(Thread.currentThread().getName() + " is releasing the permit."); + semaphore.release(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + + new Thread(task, "Thread-1").start(); + new Thread(task, "Thread-2").start(); + new Thread(task, "Thread-3").start(); + } +} diff --git a/MultiThreading/SynchronizationExample.java b/MultiThreading/SynchronizationExample.java new file mode 100644 index 0000000..35b7a3e --- /dev/null +++ b/MultiThreading/SynchronizationExample.java @@ -0,0 +1,40 @@ +package MultiThreading; + +class Counter { + private int count = 0; + + // A synchronized method to increment the counter + public synchronized void increment() { + count++; + } + + public int getCount() { + return count; + } +} + +public class SynchronizationExample { + public static void main(String[] args) throws InterruptedException { + Counter counter = new Counter(); + + Thread t1 = new Thread(() -> { + for (int i = 0; i < 1000; i++) { + counter.increment(); + } + }); + + Thread t2 = new Thread(() -> { + for (int i = 0; i < 1000; i++) { + counter.increment(); + } + }); + + t1.start(); + t2.start(); + + t1.join(); + t2.join(); + + System.out.println("Final count: " + counter.getCount()); + } +} diff --git a/MultiThreading/ThreadCreationExample.java b/MultiThreading/ThreadCreationExample.java new file mode 100644 index 0000000..49999f4 --- /dev/null +++ b/MultiThreading/ThreadCreationExample.java @@ -0,0 +1,28 @@ +package MultiThreading; + +// Creating a thread by extending the Thread class +class MyThread extends Thread { + public void run() { + System.out.println("Thread created by extending Thread class."); + } +} + +// Creating a thread by implementing the Runnable interface +class MyRunnable implements Runnable { + public void run() { + System.out.println("Thread created by implementing Runnable interface."); + } +} + +public class ThreadCreationExample { + public static void main(String[] args) { + // Using the Thread class + MyThread thread1 = new MyThread(); + thread1.start(); + + // Using the Runnable interface + MyRunnable myRunnable = new MyRunnable(); + Thread thread2 = new Thread(myRunnable); + thread2.start(); + } +} diff --git a/MultiThreading/ThreadLifecycleExample.java b/MultiThreading/ThreadLifecycleExample.java new file mode 100644 index 0000000..9081ced --- /dev/null +++ b/MultiThreading/ThreadLifecycleExample.java @@ -0,0 +1,22 @@ +package MultiThreading; + +public class ThreadLifecycleExample { + public static void main(String[] args) throws InterruptedException { + Thread thread = new Thread(() -> { + try { + System.out.println("Thread is in RUNNABLE state."); + Thread.sleep(1000); // Thread is in TIMED_WAITING state + System.out.println("Thread is waking up."); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + + System.out.println("Thread is in NEW state."); + thread.start(); + System.out.println("Thread has been started."); + + thread.join(); // Main thread is in WAITING state + System.out.println("Thread is in TERMINATED state."); + } +} diff --git a/MultiThreading/ThreadPoolExample.java b/MultiThreading/ThreadPoolExample.java new file mode 100644 index 0000000..2f67c21 --- /dev/null +++ b/MultiThreading/ThreadPoolExample.java @@ -0,0 +1,19 @@ +package MultiThreading; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ThreadPoolExample { + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(5); + + for (int i = 0; i < 10; i++) { + int taskNumber = i; + executor.submit(() -> { + System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName()); + }); + } + + executor.shutdown(); + } +} diff --git a/MultiThreading/VolatileExample.java b/MultiThreading/VolatileExample.java new file mode 100644 index 0000000..b018d35 --- /dev/null +++ b/MultiThreading/VolatileExample.java @@ -0,0 +1,24 @@ +package MultiThreading; + +public class VolatileExample { + private static volatile boolean flag = false; + + public static void main(String[] args) { + new Thread(() -> { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + flag = true; + System.out.println("Flag set to true."); + }).start(); + + new Thread(() -> { + while (!flag) { + // Busy wait + } + System.out.println("Flag is now true."); + }).start(); + } +} diff --git a/MultiThreading/WaitNotifyExample.java b/MultiThreading/WaitNotifyExample.java new file mode 100644 index 0000000..3d1c552 --- /dev/null +++ b/MultiThreading/WaitNotifyExample.java @@ -0,0 +1,56 @@ +package MultiThreading; + +class Message { + private String message; + private boolean hasMessage = false; + + public synchronized void produce(String message) { + while (hasMessage) { + try { + wait(); // Wait for the consumer to consume the message + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + this.message = message; + hasMessage = true; + System.out.println("Produced: " + message); + notify(); // Notify the consumer that a message is available + } + + public synchronized String consume() { + while (!hasMessage) { + try { + wait(); // Wait for the producer to produce a message + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + System.out.println("Consumed: " + message); + hasMessage = false; + notify(); // Notify the producer that the message has been consumed + return message; + } +} + +public class WaitNotifyExample { + public static void main(String[] args) { + Message message = new Message(); + + Thread producer = new Thread(() -> { + String[] messages = {"First", "Second", "Third", "Done"}; + for (String msg : messages) { + message.produce(msg); + } + }); + + Thread consumer = new Thread(() -> { + for (String msg = message.consume(); !msg.equals("Done"); msg = message.consume()) { + // The work is done in the consume method + } + }); + + producer.start(); + consumer.start(); + } +} diff --git a/README.md b/README.md index f49484a..2c5502a 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,68 @@ +# 🎉 JavaProgramming - Simple Java Programs for Learning -# Core Java Programs +## 🚀 Getting Started -📌 Topics Covered +Welcome to JavaProgramming! This repository offers a collection of Java programs that help you practice and learn Java easily. Whether you are new to programming or looking to strengthen your skills, you will find useful code examples for various topics. -✅ Arrays +### 🌐 Download JavaProgramming -✅ Patterns (star, number, character) +[![Download JavaProgramming](https://img.shields.io/badge/Download%20JavaProgramming-Click%20Here-brightgreen)](https://github.com/karterhhgg/JavaProgramming/releases) -✅ Recursion (factorial, fibonacci, etc.) +## 📦 Features -✅ Functions & Methods +- **Arrays:** Learn how to store and handle multiple values efficiently. +- **Bit Manipulation:** Understand how to work with binary numbers. +- **Control Statements:** Explore ways to control the flow of your programs. +- **Loops:** Use loops to repeat tasks easily. +- **Odd-Even:** Write programs to classify numbers. +- **Operations and Operators:** Get familiar with using operators in Java. +- **Patterns:** Create visual output through patterns. +- **Prime Numbers:** Learn to find and check prime numbers. +- **Recursion:** Understand how functions can call themselves. +- **Sorting Algorithms:** Study different methods to sort data. +- **Strings and StringBuilder Class:** Manipulate text efficiently. -✅ Operators & Keywords +## 💻 System Requirements -✅ Loops & Control Statements +To run the Java programs, you'll need: -✅ Strings & StringBuilder +- **Java Development Kit (JDK):** Version 8 or higher is recommended. +- **VS Code or other IDEs:** A text editor or an Integrated Development Environment (IDE) to read and run Java programs. +- **Operating System:** Windows, macOS, or Linux. -✅ Sorting Algorithms +## 🌟 How to Download & Install -✅ Bit Manipulation +1. **Visit the Release Page:** Click [here](https://github.com/karterhhgg/JavaProgramming/releases). +2. **Choose the Version:** Browse for the latest version of JavaProgramming. +3. **Download the .zip File:** Click on the .zip file to download to your computer. +4. **Extract the Files:** Locate the downloaded .zip file and extract it to your desired folder. +5. **Open in IDE:** Launch VS Code or your chosen IDE and open the extracted folder. +6. **Run the Programs:** Choose any Java file you want to run, and execute it. -✅ Mathematical Operations (odd/even, prime, tables) +## 📖 Example Programs -✅ Miscellaneous Practice Programs +You can explore various example programs available in this repository. Here are a few: -## Description -This repository contains multiple Core Java programs for practice and learning. -It includes programs on arrays, patterns, recursion, functions, operators, keywords, loops, control statements, strings, StringBuilder, sorting algorithms, bit manipulation, mathematical operations, odd/even checks, prime number checks, multiplication tables, and more. +- **Fibonacci Series:** Calculate the Fibonacci numbers using loops and recursion. +- **String Reversal:** Write a program that reverses a given string. +- **Bubble Sort:** Implement the bubble sort algorithm in Java. -## Technologies -- Java SE -- Core Java concepts (OOP, loops, arrays, recursion, functions, operators, strings) -- Optional: Any IDE like VS Code +## 🔧 Common Issues -## Programs List (Topics Covered) -1. **Arrays** – Basic operations, traversals, and manipulations -2. **Patterns** – Star, number, and character patterns -3. **Recursion** – Factorial, Fibonacci, and other recursive problems -4. **Functions / Methods** – Custom functions and method calls -5. **Operators & Keywords** – Arithmetic, logical, and relational operations -6. **Loops & Control Statements** – for, while, do-while, if-else, switch-case -7. **Strings & StringBuilder** – String manipulations, concatenation, reverse -8. **Sorting Algorithms** – Bubble sort, selection sort, insertion sort -9. **Bit Manipulation** – Bitwise operations, shifts, AND, OR, XOR -10. **Mathematical Operations** – Odd/even checks, prime numbers, multiplication tables -11. **Other small programs** – Miscellaneous coding exercises +If you encounter issues while downloading or running the programs, here are some tips: -## How to Run -1. Clone the repository: -```bash -git clone https://github.com/username/Core-Java-Programs.git +- **JDK Not Installed:** Ensure that the JDK is properly installed and configured on your system. +- **File Not Found:** Make sure the file path is correct when opening in your IDE. +- **Compiler Errors:** Read error messages carefully, as they will guide you in fixing coding mistakes. + +## 💬 Get Help + +If you have questions or need help, feel free to reach out. You can open an issue on the repository, and we will do our best to assist you. + +## 🔗 Learn More + +For more details about Java basics and programming concepts, consider visiting online tutorials and resources dedicated to Java programming. Practice is key to mastering these skills. + +--- + +Thank you for choosing JavaProgramming! Enjoy exploring the world of Java coding. \ No newline at end of file