Swing

Swing Swing is a part of Java Foundation Classes (JFC) used to create Graphical User Interfaces (GUIs). It builds on AWT (Abstract Window Toolkit) but provides a richer set of components and is more flexible. Key Features Lightweight Components (do not rely on native OS peers) Pluggable Look-and-Feel MVC Architecture Highly customizable and extensible Basic Structure import javax.swing.*; public class HelloSwing { public static void main(String[] args) { JFrame frame = new JFrame("Swing Example"); JButton button = new JButton("Click Me!"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.add(button); frame.setVisible(true); } } Core Components JFrame – Top-level window JButton – Push button JLabel – Display text JTextField – Single-line input JPanel – Generic container Benefits of Swing Cross-platform consistency Rich component library Backed by event-driven programming 🔗 Related Notes Components and Containers Layout Managers Swing Event Handling

May 8, 2025 · 1 min · Rohan

Functional Interfaces

Functional Interfaces A Functional Interface is an interface with exactly one abstract method. It forms the foundation for lambda expressions in Java. Declaration @FunctionalInterface interface MyFunctionalInterface { void execute(); } The @FunctionalInterface annotation is optional but recommended. Having more than one abstract method will result in a compilation error if the annotation is present. Example with Lambda public class Main { public static void main(String[] args) { MyFunctionalInterface f = () -> System.out.println("Executed!"); f.execute(); } } Built-in Functional Interfaces (in java.util.function) Predicate<T> – returns boolean Function<T, R> – returns a value Consumer<T> – performs an action Supplier<T> – provides a value Predicate<String> isLong = s -> s.length() > 5; System.out.println(isLong.test("Hello")); // false Benefits Enables cleaner, more modular code Essential for lambda expressions Supports functional programming 🔗 Related Notes Lambdas Generic Methods

May 8, 2025 · 1 min · Rohan

Lambdas

Lambdas Lambdas in Java are anonymous functions that can be treated as objects and passed around. Introduced in Java 8, they enable functional programming features such as concise function representations and behavior passing. Syntax (parameters) -> expression (parameters) -> { statements } Example interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = () -> System.out.println("Hello, Lambda!"); g.sayHello(); } } With Parameters interface MathOperation { int operation(int a, int b); } public class Main { public static void main(String[] args) { MathOperation add = (a, b) -> a + b; System.out.println(add.operation(5, 3)); // Output: 8 } } Use with Collections List<String> list = Arrays.asList("A", "B", "C"); list.forEach(item -> System.out.println(item)); Benefits Shorter code Improved readability Enables functional-style programming 🔗 Related Notes Functional Interfaces Generic Methods

May 8, 2025 · 1 min · Rohan

Generic Methods

Generic Methods A Generic Method defines a method that operates on objects of various types while providing compile-time type safety. These methods can be used inside generic and non-generic classes. Syntax public <T> void printArray(T[] array) { for (T element : array) { System.out.println(element); } } <T> before the return type indicates the method is generic. T is the type parameter used within the method. Example public class Main { public static <T> void display(T[] items) { for (T item : items) { System.out.print(item + " "); } System.out.println(); } public static void main(String[] args) { Integer[] intArray = {1, 2, 3}; String[] strArray = {"A", "B", "C"}; display(intArray); display(strArray); } } Bounded Type Parameters Generic methods can restrict the types they accept using bounds. ...

May 8, 2025 · 1 min · Rohan

Generic Class

Generic Class A Generic Class allows the definition of classes with a placeholder for a type, enabling reusability and type safety. The type is specified when the object is instantiated. Syntax class Box<T> { T item; void set(T item) { this.item = item; } T get() { return item; } } Usage public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(100); System.out.println("Integer Value: " + intBox.get()); Box<String> strBox = new Box<>(); strBox.set("Hello Generics"); System.out.println("String Value: " + strBox.get()); } } Multiple Type Parameters class Pair<K, V> { K key; V value; Pair(K key, V value) { this.key = key; this.value = value; } K getKey() { return key; } V getValue() { return value; } } Benefits Reduces code duplication Type-safe data structures Easier to debug and maintain 🔗 Related Notes Generics Fundamentals Generic Methods

May 8, 2025 · 1 min · Rohan

Generics Fundamentals

Generics Fundamentals Generics in Java provide a way to define classes, interfaces, and methods with a placeholder for types. They allow for type safety and code reusability without the need for casting. Why Generics? Type Safety: Compile-time checking prevents runtime ClassCastException. Code Reusability: One class or method works with different types. Eliminates Casting: Reduces boilerplate casting code. Example Without Generics ArrayList list = new ArrayList(); list.add("Hello"); String s = (String) list.get(0); // requires casting Example With Generics ArrayList<String> list = new ArrayList<>(); list.add("Hello"); String s = list.get(0); // no casting required Generic Syntax class Box<T> { T item; void set(T item) { this.item = item; } T get() { return item; } } Benefits Prevents runtime errors More readable and maintainable code Encourages clean APIs 🔗 Related Notes Generic Class Generic Methods Functional Interfaces

May 8, 2025 · 1 min · Rohan

Filereader

FileReader The FileReader class in Java is used to read character-based data from files. It is part of the java.io package and is ideal for reading text files. Basic Example import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileReader reader = new FileReader("example.txt"); int character; while ((character = reader.read()) != -1) { System.out.print((char) character); } reader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Best Practices Always close the FileReader to avoid memory leaks. Wrap with BufferedReader for efficient reading of large files. Use try-with-resources for automatic closing. import java.io.*; public class Main { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } 🔗 Related Notes FileWriter Exception Handlers Concurrent Programming

May 8, 2025 · 1 min · Rohan

Filewriter

FileWriter The FileWriter class in Java is used to write character-based data to files. It is part of the java.io package and is generally used for writing text files. Basic Example import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try { FileWriter writer = new FileWriter("example.txt"); writer.write("Hello, FileWriter!"); writer.close(); System.out.println("Successfully written to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Appending to a File Use the overloaded constructor with true to append data. ...

May 8, 2025 · 1 min · Rohan

Runnable Interface

Runnable Interface The Runnable interface in Java is another way to create and execute threads. It is preferred over extending the Thread class, especially when a class needs to extend another class as Java does not support multiple inheritance. Declaring a Thread with Runnable To use Runnable, implement the interface and pass the object to a Thread. class MyRunnable implements Runnable { public void run() { System.out.println("Runnable thread running..."); } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread t = new Thread(myRunnable); t.start(); } } Advantages of Using Runnable Decouples task from thread mechanics. Allows class to extend another class. More flexible in multithreaded applications. Anonymous Runnable Example public class Main { public static void main(String[] args) { Thread t = new Thread(new Runnable() { public void run() { System.out.println("Anonymous Runnable running..."); } }); t.start(); } } Functional Interface & Lambda Expression (Java 8+) public class Main { public static void main(String[] args) { Runnable r = () -> System.out.println("Lambda Runnable running..."); Thread t = new Thread(r); t.start(); } } 🔗 Related Notes Thread Class Concurrent Programming Exception Handlers

May 8, 2025 · 1 min · Rohan

Thread Class

The Thread Class The Thread class in Java provides a direct way to create and manage threads. It belongs to the java.lang package and provides various methods to control thread behavior. Creating a Thread Using Thread Class To create a thread using the Thread class, extend it and override its run() method. class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // starts the thread } } Important Methods in Thread Class Method Description start() Starts the thread. run() Contains the code executed by the thread. sleep(ms) Puts thread to sleep for specified time. join() Waits for a thread to die. isAlive() Checks if the thread is still running. setName() Sets the thread’s name. getName() Returns the thread’s name. Example with Sleep and Join class MyThread extends Thread { public void run() { try { Thread.sleep(500); System.out.println("Thread " + Thread.currentThread().getName() + " running."); } catch (InterruptedException e) { System.out.println("Interrupted"); } } } public class Main { public static void main(String[] args) throws InterruptedException { MyThread t1 = new MyThread(); t1.setName("Worker1"); t1.start(); t1.join(); // Waits for t1 to finish System.out.println("Main thread finished."); } } Thread Priorities Java threads have priorities that help the thread scheduler decide when each thread should run. ...

May 8, 2025 · 2 min · Rohan