( Program Bank »)

Java Program Bank

Ready-to-run programs with full code, a plain-English explanation, and sample output for each.

210 Programs15 TopicsCode + Explanation + Output

Topics

210 programs total

All 210 Programs at a Glance

Every program below comes with complete source code, a plain-English explanation and the exact output it prints. Click a program name to see the code.

Java Basics & Syntax

  • : This is the simplest Java program. It prints "Hello, World!" to the console using System.out.println().
  • : Each call to System.out.println() prints a line of text followed by a newline character, so each message appears on its own line.
  • : This program declares an int and a float variable and prints their values. The 'f' suffix is required for float literals in Java.
  • : The Scanner class reads user input from the console. nextLine() reads a full line of text entered by the user.
  • : Variables are declared with a type and a name. Java is statically typed, so every variable must have a declared type like int, String, or double.
  • : Java has four integer types with different ranges: byte (8-bit), short (16-bit), int (32-bit), and long (64-bit). The 'L' suffix marks a long literal.
  • : float uses 32 bits of precision while double uses 64 bits. Double is the default floating-point type in Java and offers greater precision.
  • : The boolean data type can only hold two values: true or false. It is commonly used for conditional testing and flags.
  • : The char data type stores a single 16-bit Unicode character. Character literals are enclosed in single quotes.
  • : String is a reference type in Java that represents a sequence of characters. The + operator concatenates strings, and length() returns the number of characters.
  • : Widening casting (int to double) is done automatically or explicitly. Since double has a larger range, no data is lost in this conversion.
  • : Narrowing casting (double to int) must be done explicitly because it may lose data. The decimal part is truncated, not rounded.
  • : Integer.parseInt() converts a numeric string into an int value. This is useful when processing user input or reading data from files.
  • : Integer.toString() converts an int to its String representation. You can also use String.valueOf() or simply concatenate with an empty string.
  • : Each wrapper class has a SIZE constant that tells the number of bits used by the corresponding primitive type.
  • : The final keyword makes a variable constant; its value cannot be changed after initialization. Constants are conventionally named in UPPER_SNAKE_CASE.
  • : Java allows declaring multiple variables of the same type in a single statement by separating them with commas.
  • : printf() allows formatted output using format specifiers: %s for strings, %d for integers, %f for floats, and %n for newlines.
  • : Escape sequences represent special characters in strings: \t for tab, \n for newline, \\ for backslash, and \" for a double quote.
  • : Java supports single-line comments (//) and multi-line comments (/* ... */). Comments are ignored by the compiler and help document code.

Operators & Expressions

  • : The five arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Integer division truncates the decimal part.
  • : Relational operators compare two values and return a boolean result. They include ==, !=, >, <, >=, and <=.
  • : Logical operators work with boolean values: && (AND) returns true only if both are true, || (OR) returns true if either is true, and ! (NOT) inverts the value.
  • : Assignment operators combine an arithmetic operation with assignment. For example, a += 5 is equivalent to a = a + 5.
  • : Bitwise operators work on individual bits: & (AND), | (OR), ^ (XOR), and ~ (NOT). Here 5 is 101 and 3 is 011 in binary.
  • : Prefix (++a) increments before use, while postfix (a++) increments after use. The same applies to the decrement operator (--).
  • : The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand for simple if-else expressions that return a value.
  • : Java follows standard operator precedence: multiplication and division are evaluated before addition and subtraction. Parentheses can override this order.
  • : This simple calculator reads two numbers and an operator from the user, then performs the corresponding arithmetic operation using a switch statement.
  • : Integer division in Java truncates the decimal. The modulus operator (%) gives the remainder. Math.floor() rounds a double down to the nearest whole number.
  • : Math.pow(base, exponent) calculates base raised to the power of exponent and returns a double. Math.sqrt() computes the square root.
  • : Complex expressions are evaluated following operator precedence rules. Multiplication and division happen before addition and subtraction.
  • : Compound assignment operators combine an operation with assignment. They include +=, -=, *=, /=, %=, and bitwise variants like &=.
  • : Left shift (<<) multiplies by powers of 2, right shift (>>) divides by powers of 2 preserving sign. Unsigned right shift (>>>) fills with zeros.
  • : Short-circuit evaluation means Java stops evaluating as soon as the result is determined. && stops if the first operand is false; || stops if the first is true.
  • : Swapping two variables uses a temporary variable to hold one value while the other is reassigned. This is a fundamental programming technique.
  • : The modulus operator (%) returns the remainder of integer division. The sign of the result follows the sign of the dividend in Java.
  • : A number is even if it is divisible by 2 (remainder is 0), otherwise it is odd. The modulus operator makes this check simple.
  • : Combining multiple arithmetic operators in a single expression follows precedence rules. Mixing int and double causes automatic promotion to double.
  • : Combining relational and logical operators allows building complex boolean expressions. Parentheses clarify the evaluation order.

Control Flow Statements

  • : The if statement executes a block of code only when the specified condition is true. If the condition is false, the block is skipped.
  • : The if-else statement provides an alternative block of code that runs when the condition is false.
  • : The if-else-if ladder checks multiple conditions in sequence. The first condition that evaluates to true has its block executed, and the rest are skipped.
  • : A nested if places an if statement inside another if block. This allows checking additional conditions only when the outer condition is true.
  • : The switch statement selects one of many code blocks to execute based on the value of a variable. Each case must end with break to prevent fall-through.
  • : Since Java 7, switch statements support String values. The comparison is case-sensitive using the equals() method internally.
  • : Enhanced switch expressions (Java 14+) use arrow syntax (->) and can return values directly. No break statements are needed as there is no fall-through.
  • : The for loop has three parts: initialization, condition, and update. It repeats the block as long as the condition remains true.
  • : The while loop checks the condition before each iteration. It continues executing as long as the condition is true.
  • : The do-while loop executes the body at least once before checking the condition, because the check happens at the end of each iteration.
  • : A nested for loop places one loop inside another. The inner loop completes all its iterations for each single iteration of the outer loop.
  • : This program uses a for loop to print the multiplication table of a given number from 1 to 10.
  • : This program prints a right-angled triangle pattern using nested loops. The inner loop prints stars equal to the current row number.
  • : The break statement immediately exits the loop when encountered. Code after the loop continues to execute normally.
  • : The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.
  • : A labeled break exits the loop identified by the label, not just the innermost loop. This is useful when working with nested loops.
  • : The for-each (enhanced for) loop iterates over each element in an array or collection without needing an index variable.
  • : An infinite loop runs forever until explicitly terminated with break. This pattern is useful when the exit condition is complex or checked mid-loop.
  • : This program uses a loop with multiple conditions combined using the logical AND operator to find numbers divisible by both 2 and 3.
  • : This simulates a number guessing game using a loop that checks each guess against the secret number and gives feedback until the correct number is found.

Arrays & Strings

  • : Arrays are declared with a type and square brackets. The length property gives the number of elements, and elements are accessed by index starting at 0.
  • : This program iterates through each element of the array using a for-each loop and accumulates the total sum.
  • : To find the largest element, we assume the first element is the largest and then compare each subsequent element, updating when a larger value is found.
  • : Similar to finding the largest, we start with the first element and update whenever we find a smaller value during iteration.
  • : Reversing an array swaps elements from both ends moving toward the center. Only half the array needs to be traversed.
  • : Arrays.sort() sorts an array in ascending order using a dual-pivot quicksort algorithm. Arrays.toString() converts the array to a readable string.
  • : Linear search checks each element sequentially until the target is found or the array ends. It works on both sorted and unsorted arrays.
  • : Binary search works on sorted arrays by repeatedly dividing the search interval in half. It is much faster than linear search for large arrays.
  • : A 2D array is an array of arrays. It is accessed using two indices: the first for the row and the second for the column.
  • : Matrix addition adds corresponding elements of two matrices. Both matrices must have the same dimensions.
  • : Matrix multiplication multiplies rows of the first matrix by columns of the second. The number of columns in the first must equal the number of rows in the second.
  • : Strings have useful methods: length() returns the size, charAt() accesses individual characters, and substring() extracts a portion of the string.
  • : Strings can be concatenated using the + operator or the concat() method. Both produce a new String since strings are immutable in Java.
  • : The == operator compares references while equals() compares actual content. Always use equals() to compare string values in Java.
  • : StringBuilder provides a reverse() method that reverses the character sequence. This is the simplest way to reverse a string in Java.
  • : This program counts vowels by checking each character against a string of all vowels. The indexOf() method returns -1 if the character is not found.
  • : A palindrome reads the same forwards and backwards. We reverse the string and compare it with the original using equals().
  • : toUpperCase() converts all characters to uppercase and toLowerCase() converts all to lowercase. Both return a new string since strings are immutable.
  • : The split() method divides a string into an array of substrings based on a delimiter. It accepts a regular expression pattern as the delimiter.
  • : String concatenation in loops creates many temporary objects. StringBuilder is mutable and much faster for repeated appends because it modifies the buffer in place.

Methods & Recursion

  • : A void method performs an action but does not return a value. It can be called multiple times from main or other methods.
  • : Methods can accept parameters that act as local variables inside the method. Arguments are passed when the method is called.
  • : A method with a return type sends a value back to the caller using the return statement. The returned value can be stored in a variable or used directly.
  • : Method overloading lets you define multiple methods with the same name but different parameter types or counts. Java selects the correct version based on the arguments.
  • : A recursive method calls itself with a simpler input until it reaches a base case. Factorial of n is n * factorial(n-1) with base case factorial(0) = 1.
  • : The Fibonacci sequence is defined recursively: F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2). Each number is the sum of the two preceding ones.
  • : This recursive method adds n to the sum of all natural numbers up to n-1. The base case returns 0 when n reaches 0.
  • : Recursive power calculation multiplies the base by itself (exp-1) more times. The base case is any number raised to the power 0 equals 1.
  • : Recursive string reversal takes the first character, places it at the end, and recursively reverses the remaining substring.
  • : The Euclidean algorithm finds the GCD recursively: GCD(a, b) = GCD(b, a%b), with the base case GCD(a, 0) = a.
  • : Static methods belong to the class rather than an instance. They can be called directly without creating an object of the class.
  • : Methods can accept arrays as parameters. The array reference is passed, so the method operates on the same data as the caller.
  • : Methods can create and return arrays. The returned array can be assigned to a variable and used by the caller.
  • : Varargs (int... numbers) allows a method to accept any number of arguments of the specified type. Internally, they are treated as an array.
  • : Recursive binary search divides the sorted array in half at each step. It returns the index if found, or -1 if the element is not present.
  • : Recursive palindrome check compares characters from both ends moving inward. If all pairs match, the string is a palindrome.
  • : Tower of Hanoi is a classic recursion problem. To move n disks, move n-1 disks to auxiliary, move the largest disk to target, then move n-1 from auxiliary to target.
  • : Methods can call other methods to build more complex behavior. Here process() calls doubleValue() first, then passes the result to addTen().
  • : Java is pass-by-value: primitives are copied so changes don't affect the caller. Arrays pass a copy of the reference, so modifications to array contents are visible to the caller.
  • : This recursive countdown prints numbers from n down to 1, then prints "Go!" when the base case is reached. Each recursive call decreases n by 1.

Object-Oriented Programming

  • : A class is a blueprint and an object is an instance of that blueprint. Fields store data, and the dot operator accesses them on a specific object.
  • : A constructor is a special method with the same name as the class. It initialises an object's fields when the object is created with the new keyword.
  • : A default constructor takes no parameters and assigns initial values to fields. Java provides one automatically only if no constructor is defined at all.
  • : A parameterized constructor accepts arguments so each object can be initialised with unique values at the moment of creation.
  • : Constructor overloading means defining multiple constructors with different parameter lists. Java picks the right one based on the arguments provided.
  • : The this keyword refers to the current object. It disambiguates instance fields from constructor or method parameters that share the same name.
  • : Getter and setter methods provide controlled access to private fields. Setters can include validation logic before assigning a value.
  • : A static variable is shared across all instances of a class. A static method can be called on the class itself and can only access static members directly.
  • : A final variable in a class acts as a constant — once set it cannot be reassigned. It is useful for values like PI that should never change.
  • : Instance variables belong to individual objects, so each object keeps its own value. Static variables belong to the class and are shared by every object.
  • : Multiple objects can be created from the same class. Each object maintains its own set of instance variable values independently of the others.
  • : Objects can be passed as method parameters just like primitives. The receiving method accesses the passed object's fields and methods through the parameter reference.
  • : A method can create and return a new object. This pattern is common for operations that produce a result without modifying the original objects.
  • : Overriding toString() lets you define how an object is represented as a string. Java automatically calls toString() when an object is used in string concatenation or println.
  • : Overriding equals() allows comparing two objects by their content rather than memory address. The == operator still checks reference equality.
  • : An anonymous object is created with new but not stored in a variable. It is useful for one-time operations where keeping a reference is unnecessary.
  • : A nested class is defined inside another class. A non-static nested (inner) class requires an instance of the outer class to be instantiated.
  • : An inner class is a non-static nested class. It has full access to the enclosing outer class's private fields and methods.
  • : A static nested class does not need an instance of the outer class. It behaves like a top-level class but is scoped inside the outer class for organisation.
  • : An object array stores multiple references to objects of the same class. Each element must be individually instantiated before it can be used.

Inheritance & Polymorphism

  • : Single inheritance means a child class inherits from exactly one parent class. The child gains all the non-private fields and methods of the parent, allowing code reuse without duplication.
  • : Multilevel inheritance forms a chain: Grandparent → Parent → Child. Each level inherits all the accessible members from the levels above it, building a natural hierarchy of behaviours.
  • : The super keyword gives access to the parent class's fields and methods when the child class defines members with the same name. It helps avoid ambiguity and lets you reuse parent logic.
  • : super() calls the parent class constructor and must be the very first statement in the child constructor. It ensures the parent part of the object is fully initialised before the child adds its own setup.
  • : Method overriding lets a child class replace a parent method with its own implementation. The @Override annotation is optional but recommended — it tells the compiler to verify the override is valid.
  • : Runtime polymorphism (dynamic method dispatch) means the JVM decides which overridden method to call at runtime based on the actual object type, not the reference type. This is the foundation of polymorphic behaviour in Java.
  • : The instanceof operator returns true if an object is an instance of a given class or any subclass. It is commonly used before casting to avoid ClassCastException at runtime.
  • : Upcasting stores a child object in a parent reference (implicit, always safe). Downcasting converts it back to the child type (explicit, must verify with instanceof first to avoid ClassCastException).
  • : Declaring a class as final prevents any other class from extending it. This is used for security and immutability — for example, Java's String class is final to protect its behaviour from being altered.
  • : A final method in a parent class cannot be overridden by any subclass. This guarantees that critical logic (like a payment process) remains unchanged regardless of how the class is extended.

Exception Handling

  • : A try-catch block lets you handle runtime errors without crashing the program. Code that might fail goes inside try. If an exception occurs, the matching catch block runs instead, and the program continues normally afterward.
  • : ArithmeticException is thrown when an illegal arithmetic operation occurs, most commonly dividing an integer by zero. Catching it specifically lets you display a meaningful message instead of crashing.
  • : ArrayIndexOutOfBoundsException is thrown when you try to access an index that is outside the valid range of an array. Always ensure the index is between 0 and array.length - 1 to avoid this error.
  • : NullPointerException occurs when you try to use an object reference that has not been assigned (it is null). This is one of the most common Java exceptions. Always check if an object is null before calling methods on it.
  • : NumberFormatException is thrown when you try to convert a String to a number (e.g., using Integer.parseInt) but the string does not contain a valid numeric value. It is commonly triggered when processing user input.
  • : You can chain multiple catch blocks after a single try block to handle different exception types in different ways. Java checks each catch block in order and executes the first one that matches. A general Exception catch at the end acts as a safety net.
  • : The finally block always runs after try-catch, regardless of whether an exception occurred. It is ideal for cleanup tasks such as closing files, releasing database connections, or freeing resources.
  • : The throw keyword lets you deliberately trigger an exception in your code when a condition is violated. You create an exception object and throw it, which immediately stops the current method and passes the exception to the nearest matching catch block.
  • : The throws keyword is used in a method signature to declare that the method might throw a checked exception. It warns callers that they must either handle the exception with try-catch or propagate it further using throws in their own signature.
  • : A custom exception class lets you create meaningful, domain-specific error types by extending Exception (checked) or RuntimeException (unchecked). You can add extra fields and methods to carry more information about what went wrong, making error handling clearer and more expressive.

Collections Framework

  • : ArrayList is a part of Java's Collections Framework. It works like a dynamic array — you can add elements without specifying a fixed size. Elements are stored in insertion order and can be accessed by index using get(). The size() method returns the number of elements currently in the list.
  • : ArrayList provides flexible methods to add and remove elements. add(value) appends to the end; add(index, value) inserts at a specific position. remove(value) removes the first matching element by value, while remove(index) removes by position. contains() checks whether an element is in the list.
  • : There are three common ways to iterate over an ArrayList: the enhanced for-each loop (clean and readable), the traditional index-based for loop (when you need the index), and the forEach() method with a lambda expression (modern Java 8+ style). All three produce the same result but differ in style and use case.
  • : Collections.sort() sorts an ArrayList in natural (ascending) order — alphabetically for strings, numerically for integers. To sort in descending order, pass Collections.reverseOrder() as a second argument. The Collections utility class provides many helpful methods for working with lists and other collections.
  • : LinkedList stores elements in a doubly-linked structure — each element has a reference to both the next and previous element. This makes adding or removing from the front or back very efficient. addFirst() and addLast() insert at the two ends, while removeFirst() and removeLast() remove from each end. It's ideal when frequent insertions or deletions are needed.
  • : A Deque (Double-Ended Queue) allows adding and removing elements from both ends. LinkedList implements the Deque interface, so it supports offerFirst()/offerLast() to add elements and pollFirst()/pollLast() to remove them. peekFirst()/peekLast() let you inspect the front or back element without removing it. Deques are useful for implementing stacks, queues, or sliding-window algorithms.
  • : Stack is a LIFO (Last-In, First-Out) data structure — the last element added is the first one removed, like a stack of plates. push() adds an element to the top, pop() removes and returns the top element, and peek() lets you see the top element without removing it. isEmpty() checks if the stack has no remaining elements. Stacks are commonly used for undo operations, expression parsing, and backtracking.
  • : Queue follows FIFO (First-In, First-Out) order — the first element added is the first one removed, like a customer service line. offer() adds an element to the back, poll() removes and returns the front element, and peek() lets you see the front without removing it. If the queue is empty, poll() and peek() return null instead of throwing an exception. LinkedList is commonly used to implement a Queue in Java.
  • : HashSet stores only unique elements — adding a duplicate is silently ignored and add() returns false in that case. It uses a hash table internally, making add(), remove(), and contains() operations very fast (O(1) on average). Note that HashSet does not guarantee any specific order when printing elements. It is ideal when you need a collection with no duplicates and fast lookups.
  • : A quick and clean way to remove duplicates from an ArrayList is to pass it into a HashSet constructor — since HashSet only stores unique values, all duplicates are automatically discarded. You can then convert the HashSet back into an ArrayList if you need index-based access or sorting. This pattern is commonly used in real-world Java applications to clean up data or deduplicate results.

Generics & Lambda

  • : A generic class uses a type parameter (e.g. T) as a placeholder that is replaced with a real type when the class is instantiated. This allows the same Box class to safely hold an Integer, a String, or any other type without duplicating code. The compiler enforces type safety — you cannot accidentally put a String into a Box<Integer>. The angle-bracket syntax <T> declares the type parameter, and <Integer> or <String> supplies the actual type at usage.
  • : A generic method declares its own type parameter <T> just before the return type, making it independent of the class. This lets printArray() work on Integer[], String[], or any other object array. The second method adds a bound <T extends Comparable<T>>, which means T must support comparison — enabling the use of compareTo(). Generic methods eliminate the need to write the same logic for every type.
  • : A bounded type parameter restricts which types can be used for T. <T extends Number> means T must be Number or one of its subclasses (Integer, Double, Long, etc.), which allows calling Number methods like doubleValue(). Multiple bounds are written with & — <T extends Animal & Runnable> requires T to extend Animal AND implement Runnable. Bounded parameters give you both flexibility and type-safe access to specific methods.
  • : The wildcard ? in generics represents an unknown type. List<?> means a list of some type — you don't know or care which. This is useful when writing methods that only need to read from a collection without caring about the exact element type. You can iterate and access elements as Object, or use instanceof to check at runtime. The wildcard is more flexible than a concrete type parameter when you don't need to add elements to the collection.
  • : Upper bounded wildcards (? extends Type) restrict to Type and its subclasses — great for reading. List<? extends Number> accepts Integer, Double, Long lists, and lets you safely call Number methods. Lower bounded wildcards (? super Type) restrict to Type and its superclasses — great for writing. List<? super Integer> accepts Integer, Number, or Object lists and allows adding Integers. The PECS rule helps: Producer Extends, Consumer Super.
  • : A lambda expression is a concise way to represent an anonymous function — it has no name and can be passed around like a value. The syntax is (parameters) -> body. If the body is a single expression, no braces are needed; for multiple statements, use a block with {}. Lambdas work with functional interfaces (interfaces with exactly one abstract method) like Runnable, Comparator, and others. They make code shorter and more readable, especially when working with collections and callbacks.
  • : A functional interface is an interface with exactly one abstract method, marked with the optional @FunctionalInterface annotation. This annotation causes a compile error if you accidentally add a second abstract method, helping avoid mistakes. Any functional interface can be implemented using a lambda expression — the lambda provides the body of the single abstract method. This pattern is at the heart of Java's lambda system and enables clean, expressive code without anonymous class boilerplate.
  • : Comparator is a functional interface with one abstract method compare(T o1, T o2). Before lambdas, you had to write a verbose anonymous class; now you can pass a compact lambda directly to sort(). A positive return means o1 > o2, negative means o1 < o2, and zero means equal. This example shows ascending grade sort (s1.grade - s2.grade), descending (reversed), alphabetical (compareTo), and a compound sort that uses grade as the primary key and name as a tiebreaker inside a block lambda.
  • : A method reference is a shorthand for a lambda that simply calls an existing method. The four forms are: ClassName::staticMethod (static method reference), instance::method (bound instance method reference), ClassName::instanceMethod (unbound instance method — the instance comes from the stream element), and ClassName::new (constructor reference). Method references make code cleaner when the lambda body is just a single method call. System.out::println is one of the most commonly seen examples.
  • : Streams (introduced in Java 8) let you process collections with a pipeline of operations. stream() creates a stream from a collection. filter() keeps only elements that satisfy a lambda predicate. map() transforms each element into something else. collect(Collectors.toList()) gathers the results back into a List. Operations can be chained — the stream processes elements lazily, only doing work when a terminal operation (collect, count, forEach) is called. Streams make data processing concise, readable, and expressive.

File I/O & Streams

  • : FileWriter is the simplest way to write text to a file in Java. You pass a filename to its constructor — if the file doesn't exist it is created; if it does exist it is overwritten. The write() method accepts a String. Always call close() when you are done so the data is flushed from the internal buffer to disk and the file handle is released. The entire operation is wrapped in a try-catch because file operations can fail with IOException (e.g., permission denied, disk full).
  • : FileReader reads a file character by character. The read() method returns an int — the Unicode value of the next character, or -1 when the end of the file is reached. We cast the int to char before printing. This approach works well for small files; for large files or line-by-line reading, BufferedReader is preferred because it reduces the number of disk reads. The sample also writes the file first so the program is self-contained and runnable without a pre-existing file.
  • : BufferedWriter wraps a FileWriter (or any Writer) and adds an internal buffer. Instead of writing each character directly to disk, characters accumulate in the buffer and are flushed in larger chunks — which is much faster. The key extra method is newLine(), which writes the correct line separator for the current operating system (\r\n on Windows, \n on Unix). Always close the BufferedWriter (not just the inner FileWriter); closing it also flushes the buffer and closes the wrapped stream.
  • : BufferedReader wraps a FileReader to add buffering and the very useful readLine() method. readLine() returns the next line of text as a String, stripping the line terminator, or null when the end of the file is reached — which makes it perfect for a while-loop condition. Buffering means the JVM reads a large chunk of data at once and serves individual lines from memory, avoiding a disk access for every single character. This is the standard pattern for reading text files line by line in Java.
  • : By default FileWriter overwrites the file every time. Passing true as the second constructor argument switches it to append mode — new data is added after whatever is already in the file. This is essential for log files, audit trails, or any situation where you need to accumulate data across multiple program runs. The example first writes an initial entry (overwrite), then appends two more entries, and finally reads the whole file to verify all three entries are present.
  • : Reading a file line by line is one of the most common file I/O tasks. The pattern is: open a BufferedReader, call readLine() in a while-loop condition, process the returned String inside the loop, and stop when readLine() returns null (end of file). Here we also track a line counter to prefix each line with its number. This approach is memory-efficient because only one line is held in memory at a time, making it safe even for very large files.
  • : Counting lines is a simple but common task — for example, to validate that a CSV has the expected number of rows, or to show progress while processing a large file. The technique is the same as reading line by line, except we discard the line content and only increment a counter. The while (br.readLine() != null) idiom is idiomatic Java: readLine() advances the stream and returns null at the end of the file, so the loop exits naturally. The total line count is printed after the reader is closed.
  • : Copying a file means reading every line from the source and writing it to the destination. This example also introduces the try-with-resources statement (try ( ... ) { }), which automatically closes any AutoCloseable resources — like BufferedReader and BufferedWriter — when the block exits, even if an exception is thrown. This eliminates the need for finally blocks and prevents resource leaks. The resource declarations go inside the parentheses, separated by semicolons, and they are closed in reverse order at the end of the block.
  • : The File class represents a file or directory path — it does not read or write content itself, but provides metadata operations. createNewFile() atomically creates the file if it does not exist and returns true; it returns false (without error) if the file already exists. delete() removes the file from the filesystem and returns true on success. exists() checks whether the file or directory is present on disk. Together, these three methods cover the most common file lifecycle operations: create, verify, and clean up.
  • : exists() is the go-to guard before any file operation — always check before reading so you avoid a FileNotFoundException, and before conditional creation so you don't overwrite existing data. Beyond exists(), the File class exposes useful metadata: getAbsolutePath() shows the full filesystem path, isFile() / isDirectory() distinguish files from folders, and canRead() / canWrite() report permission flags. These methods are all local operations that query the filesystem without opening the file, so they are fast and require no exception handling.

Multithreading & Concurrency

  • : The simplest way to create a thread in Java is to extend the Thread class and override its run() method with the work you want to perform. You then create an instance of your subclass and call start() on it. Calling start() tells the JVM to create a brand-new thread of execution and invoke run() inside it — calling run() directly would just execute the method on the current thread, defeating the purpose. Thread.currentThread().getName() returns the name of whichever thread is executing that line, so the output shows each thread identifying itself.
  • : Implementing Runnable is generally preferred over extending Thread because it keeps your task logic decoupled from the threading mechanism. Your class only needs to provide one method — run() — and the same Runnable instance can be reused across multiple Thread objects. Because Runnable is a functional interface you can also express it as a lambda: new Thread(() -> System.out.println("hi")).start(). The Thread constructor accepts any Runnable, so you pass the task in when building the thread.
  • : Thread.sleep(milliseconds) is a static method that makes the currently executing thread stop running for (at least) the given number of milliseconds, freeing the CPU for other threads. It is the most common way to introduce a deliberate delay — for example, in animations, polling loops, or simulating slow operations in demos. The method throws the checked exception InterruptedException, which you must handle; this allows another thread to wake the sleeping thread early by calling interrupt() on it.
  • : join() is used when one thread must wait for another to complete before proceeding. Calling worker.join() on the main thread blocks the main thread until the worker thread terminates. This is essential when the rest of your program depends on the result produced by a background thread. join() also throws InterruptedException in case the waiting thread is interrupted. You can optionally pass a timeout in milliseconds — join(2000) waits at most 2 seconds even if the thread has not finished.
  • : Every Java thread has a priority between 1 (MIN_PRIORITY) and 10 (MAX_PRIORITY), with the default being 5 (NORM_PRIORITY). Higher-priority threads are scheduled more often by the JVM, but this is only a hint to the OS scheduler — it does not guarantee execution order. Use setPriority() before starting the thread and getPriority() to read the current value. Priority is useful for background tasks (low) that should not compete with interactive work (high), but you should never rely on priority alone to coordinate thread execution; use synchronization primitives for that.
  • : Each thread has a human-readable name (default "Thread-N") and a unique numeric ID assigned by the JVM. You can set a custom name either via the Thread constructor (Thread(Runnable, String name)) or by calling setName() before start(). Meaningful names appear in thread dumps and profilers, making debugging much easier. getId() returns a long that is unique for the lifetime of the JVM process. getState() returns one of the Thread.State enum values: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.
  • : A daemon thread is a background thread that runs only as long as there are non-daemon threads alive. When the last non-daemon thread finishes, the JVM exits and all daemon threads are killed automatically — even if they are in the middle of their run() method. This makes daemon threads ideal for housekeeping tasks like garbage collection, auto-save, or heartbeat monitoring, where you do not need them to finish cleanly. You must call setDaemon(true) before calling start(); calling it afterwards throws an IllegalThreadStateException.
  • : This example shows how to launch multiple threads simultaneously. Five Thread objects are created in a loop, each capturing its own id variable (which must be effectively final for use inside a lambda). All threads are started in a second loop, so they run concurrently — the OS scheduler decides which runs first, so the print order will vary between runs. The third loop calls join() on every thread so the main thread waits until all workers are done before printing the final message. The Thread.currentThread().interrupt() call in the catch block preserves the interrupted status for callers further up the call stack.
  • : When multiple threads share a variable, a race condition can occur: two threads read the old value simultaneously, both increment it, and both write back — losing one update. The synchronized keyword prevents this by turning the method into a mutually exclusive critical section. When a thread enters a synchronized method, it acquires the intrinsic lock (monitor) of the object (or class, for static methods). Any other thread that tries to enter any synchronized method on the same lock will block until the first thread exits and releases the lock. Without synchronized here, the final count would be unpredictably less than 2000.
  • : A synchronized block is more flexible than a synchronized method because you choose exactly which object to lock and exactly which lines of code are protected. The syntax is synchronized (lockObject) { ... } — only the code inside the braces is serialized; the rest of the method can run concurrently. Using a dedicated private lock object (like the static final Object lock here) is a best practice because it prevents outside code from accidentally or maliciously acquiring the same lock. Smaller critical sections also mean less contention and better performance compared to synchronizing an entire method.

Data Structures

  • : A stack is a Last-In-First-Out (LIFO) data structure. This implementation uses a fixed-size integer array and a top pointer initialised to -1 (empty). push() increments top and places the value there; pop() reads the value at top and decrements it. Bounds checking prevents overflow (pushing onto a full stack) and underflow (popping from an empty stack). peek() returns the top element without removing it. Stacks are used in function call management, expression evaluation, undo operations, and backtracking algorithms.
  • : A queue is a First-In-First-Out (FIFO) data structure. This linear-array implementation uses two pointers: front (points to the first element) and rear (points to the last element), both initialised to -1. enqueue() moves rear forward and places the value; dequeue() reads the value at front and moves front forward. When front surpasses rear the queue is logically empty and pointers are reset. Queues are used in task scheduling, print spooling, BFS graph traversal, and producer-consumer pipelines.
  • : A singly linked list is a chain of nodes where each node holds a data value and a next pointer to the following node. The list is accessed only through the head pointer. insert() traverses to the last node and appends a new node. delete() handles three cases: deleting the head, deleting a middle node, and the key not being found — in each case it adjusts the next pointer of the preceding node so the target node is skipped and becomes eligible for garbage collection. Linked lists grow and shrink dynamically, unlike arrays.
  • : A doubly linked list extends the singly linked list by giving each node a prev pointer in addition to next. This bidirectional linkage allows traversal in both directions. insertEnd() walks to the tail and sets both newNode.prev and the old tail's next. displayForward() follows next pointers from head; displayBackward() first walks to the tail then follows prev pointers back to head. The extra pointer doubles memory per node but makes operations like deletion (without a separate previous reference) and reverse traversal O(1) once the node is found.
  • : In a circular linked list the last node's next pointer points back to the head instead of null, forming a ring. insert() walks until temp.next == head (the last node), then links the new node between the old last node and head. display() uses a do-while loop — starting at head and stopping when temp returns to head — because checking temp != head at the start of a while loop would immediately terminate for a single-node list. Circular lists are used in round-robin scheduling, multiplayer game turns, and media playlist looping.
  • : A Binary Search Tree (BST) keeps every node's left subtree smaller and right subtree larger than the node's value. insert() uses recursion: if the current node is null it creates a new leaf; otherwise it goes left or right based on comparison. The three classic depth-first traversals visit nodes in different orders — inorder produces sorted ascending output, which is the most common use case; preorder is useful for copying a tree; postorder is useful for deletion (process children before parent). All three run in O(n) time.
  • : Searching a BST exploits the ordering property to eliminate half the remaining nodes at every step, giving O(log n) time on a balanced tree. search() compares the key with the current node's data: equal means found; less means the key can only be in the left subtree; greater means it can only be in the right subtree. Recursion naturally follows the path down the tree. If a null node is reached the key is absent. In the worst case (a degenerate tree that looks like a linked list) search degrades to O(n), which is why balanced BSTs like AVL trees and Red-Black trees exist.
  • : Bubble Sort repeatedly steps through the array and swaps adjacent elements that are out of order, causing larger values to "bubble up" to the right. The outer loop runs at most n-1 passes; after each pass the rightmost i elements are in their final sorted position, so the inner loop shrinks by one each time. The swapped flag enables an early-exit optimisation: if a full pass makes no swaps the array is already sorted and the algorithm terminates before completing all n-1 passes. Time complexity is O(n²) average and worst case, O(n) best case (already sorted). It is simple to understand but inefficient for large datasets.
  • : Selection Sort divides the array into a sorted left portion and an unsorted right portion. In each pass it scans the unsorted portion to find the minimum element, then swaps it into the first position of the unsorted portion, growing the sorted portion by one. This means exactly n-1 swaps are performed regardless of the initial order — making Selection Sort attractive when write operations are costly. However, the inner scan always runs in full, giving O(n²) comparisons for all cases (best, average, worst). It is not stable (equal elements may change relative order) and not adaptive (sorted input takes the same time as random input).
  • : Insertion Sort builds the sorted array one element at a time, much like sorting a hand of playing cards. For each element (key), it finds the correct position within the already-sorted left portion by shifting larger elements one step right to make room, then inserts the key. The while loop shifts elements right as long as they exceed the key; when the loop stops, j+1 is the correct insertion index. Time complexity is O(n²) average and worst case, but O(n) for nearly-sorted data — the inner loop exits early. It is stable (equal elements keep their relative order), in-place, and efficient for small or nearly-sorted arrays.

Design Patterns

  • : The Singleton Pattern restricts a class to exactly one instance and provides a global access point to it. The constructor is private so no external code can call new. The static getInstance() method creates the object the first time it is called and returns the same object on every subsequent call. Common use-cases include database connections, configuration managers, and logging services where having multiple instances would waste resources or cause inconsistency.
  • : The Factory Pattern defines a method (getShape) that returns objects of a common interface without exposing the instantiation logic to the caller. The client only knows about the Shape interface; it does not depend on Circle, Rectangle, or Triangle directly. Adding a new shape requires only a new class and a new case in the factory — existing client code stays unchanged. This loose coupling makes the codebase easier to extend and test.
  • : The Abstract Factory Pattern provides an interface for creating families of related objects without specifying their concrete classes. Here GUIFactory is the abstract factory; WindowsFactory and MacFactory are concrete factories that each produce a consistent set of widgets (Button + Checkbox). The buildUI() method only talks to the GUIFactory interface, so swapping factories swaps the entire UI toolkit in one place. This pattern is ideal when a system must be independent of how its products are created and when products are designed to work together.
  • : The Builder Pattern separates the construction of a complex object from its representation, allowing the same construction process to produce different results. The inner Builder class collects optional parameters step by step using method chaining (each setter returns this). The final build() call creates the immutable Pizza. This avoids telescoping constructors (constructors with many parameters) and makes the code readable — each step clearly states what it sets. Useful for objects with many optional fields such as HTTP requests, database queries, or UI components.
  • : The Prototype Pattern creates new objects by copying (cloning) an existing object called the prototype, rather than constructing from scratch. Java's built-in Cloneable interface and Object.clone() support shallow copies. This is useful when object creation is expensive (e.g., loading from a database or performing complex initialization) and many similar objects are needed. Cloning is faster because it copies memory directly. After cloning, each copy can be independently customised. For objects with mutable reference fields, a deep clone may be needed to avoid shared state between copies.
  • : The Adapter Pattern acts as a bridge between two incompatible interfaces, converting the interface of one class into another that the client expects. Here PrinterAdapter implements the NewPrinter interface that the client requires, but internally delegates work to OldPrinter by translating the call. The client code only depends on NewPrinter; it never knows OldPrinter exists. This is especially valuable when integrating third-party libraries or legacy code that cannot be modified. The pattern follows the Open/Closed Principle: the old class is unchanged, and the adapter adds compatibility.
  • : The Decorator Pattern attaches additional responsibilities to an object dynamically by wrapping it in decorator objects that share the same interface. Each decorator forwards calls to the wrapped object and adds its own behaviour before or after. Decorators can be stacked in any order and combination, giving flexible extensibility without modifying the original class or creating an explosion of subclasses. Here a plain coffee is progressively wrapped with Milk, Sugar, and Vanilla decorators, each adding to the description and cost. Java's I/O library (BufferedReader wrapping FileReader) is a classic real-world example of this pattern.
  • : The Observer Pattern defines a one-to-many dependency so that when one object (the Subject) changes state, all its dependents (Observers) are notified and updated automatically. The StockMarket holds a list of Observer references; when setPrice() is called it iterates the list and calls update() on each. Observers can subscribe or unsubscribe at runtime. This promotes loose coupling — the Subject does not know concrete Observer types, only the Observer interface. The pattern underpins event systems, GUI frameworks, and reactive programming. Java's java.util.Observable (deprecated) and PropertyChangeListener are built-in examples.
  • : The Strategy Pattern defines a family of algorithms, encapsulates each one in its own class, and makes them interchangeable. The Context class (Sorter) holds a reference to a SortStrategy interface and delegates sorting to it. Swapping the strategy object changes the algorithm without altering the Sorter class. This eliminates long if-else or switch blocks and follows the Open/Closed Principle — new sorting algorithms can be added as new classes without touching existing code. Real-world uses include payment processing (CreditCard, PayPal, Crypto strategies), data compression, and path-finding algorithms.
  • : The Command Pattern encapsulates a request as a standalone object, letting you parameterise methods with actions, queue or log operations, and support undoable operations. Each Command object knows its receiver (TextEditor) and stores any data needed to reverse the action. The Invoker (CommandInvoker) calls execute() and pushes the command onto a history stack; undoLast() pops from the stack and calls undo(). This decouples the sender of a request from the object that performs it. Real-world applications include text editors (Ctrl+Z), transaction management, task schedulers, and GUI button actions.

Advanced Java Concepts

  • : An enum (enumeration) in Java is a special type that defines a fixed collection of named constants. Unlike plain int constants, enums are type-safe — you cannot accidentally assign an invalid value. Every enum constant is an instance of the enum class. Key built-in methods include values() (returns all constants as an array), ordinal() (returns the zero-based position), name() (returns the constant name as a String), and valueOf(String) (converts a string back to the constant). Enums work naturally in if and switch statements, and can be used as keys in EnumMap or elements in EnumSet for high-performance collections.
  • : Java enums can carry data and behaviour just like regular classes. Each constant can call a private constructor with specific arguments, setting instance fields. You can add methods that compute derived values from those fields, making each constant a self-contained object. This avoids separate lookup tables or switch statements. The classic Planet example (from the official Java docs) stores mass and radius per planet and computes surface gravity and weight with a formula. Enums can also implement interfaces, contain abstract methods (where each constant provides its own implementation), and even hold mutable state — though immutable fields with final are the recommended pattern.
  • : Annotations are a form of metadata that can be attached to classes, methods, fields, and other program elements. A custom annotation is declared with @interface. The @Retention annotation controls how long the annotation lives: SOURCE (discarded after compilation), CLASS (stored in bytecode but not available at runtime), or RUNTIME (available via reflection). The @Target annotation limits where it can be applied — method, field, class, etc. Here @TestCase marks test methods with a description and priority. At runtime, reflection inspects each method with isAnnotationPresent() and getAnnotation() to read the values. This pattern is the foundation of testing frameworks like JUnit (@Test) and dependency injection frameworks like Spring (@Autowired).
  • : Reflection is the ability of a Java program to inspect and modify its own structure at runtime. The entry point is a Class object (obtained via ClassName.class, object.getClass(), or Class.forName("name")). From it you can retrieve Fields, Methods, Constructors, annotations, modifiers, and superclass information. getDeclaredFields() and getDeclaredMethods() include all access levels (public, private, protected, package-private), while getFields() and getMethods() return only public members including inherited ones. The Modifier class converts the integer modifier bitmask into readable strings like "public", "private", "static", "final". Reflection is the backbone of frameworks such as Spring, Hibernate, JUnit, and JSON serialisers like Jackson.
  • : Reflection's Method.invoke() lets you call any method dynamically — you specify the method name and parameter types at runtime rather than at compile time. getMethod() retrieves public methods (including inherited ones); getDeclaredMethod() retrieves any method declared in the class regardless of access level. For private methods, setAccessible(true) suppresses the Java access check — use this sparingly as it bypasses encapsulation. Static methods are invoked by passing null as the object instance. invoke() returns Object (the result must be cast) and wraps checked exceptions in InvocationTargetException. This technique powers dependency injection, ORM mapping, unit testing frameworks, and dynamic proxy generation.
  • : Records (introduced in Java 16) are a concise way to declare immutable data-carrier classes. The compiler automatically generates a canonical constructor (setting all fields), public accessor methods named after each component (e.g. x(), y()), and correct equals(), hashCode(), and toString() implementations. All record fields are implicitly private and final, making instances immutable. A compact constructor (without a parameter list) lets you validate or normalise data before fields are set. You can still add your own methods, static fields, and static methods. Records cannot extend other classes (they implicitly extend java.lang.Record) but can implement interfaces. They are ideal for DTOs, value objects, and return types carrying multiple values.
  • : Switch expressions (standardised in Java 14) extend the traditional switch statement into an expression that produces a value. The arrow (->) syntax eliminates fall-through bugs and the need for break statements — each arm is independent. Multiple labels can be combined in a single arm with a comma. When a branch needs multiple statements, use a block and the yield keyword to return the value (yield is to switch expressions what return is to methods). Switch expressions are exhaustive — the compiler enforces that all possible values are covered (use default as a catch-all). They work with int, String, enums, and (from Java 21) patterns. The result can be assigned to a variable, returned from a method, or used inline.
  • : CompletableFuture (introduced in Java 8) is the modern way to write asynchronous, non-blocking code. supplyAsync() starts a task on a background thread from the common ForkJoinPool, returning a CompletableFuture. thenApply() chains a function that transforms the result (similar to map in streams); thenAccept() consumes it without returning a new value; thenCompose() is used when the transformation itself returns a CompletableFuture (flatMap). exceptionally() provides a fallback value if any stage throws an exception, preventing crashes. get() blocks the calling thread until the result is ready — in real applications you would chain callbacks instead to stay fully non-blocking. CompletableFuture is ideal for parallel API calls, I/O tasks, and building responsive applications.
  • : Optional<T> (Java 8+) is a wrapper that explicitly signals a value may be absent, replacing the error-prone practice of returning null. Wrapping a value with Optional.of() (non-null) or Optional.ofNullable() (possibly null) makes the absence intentional and visible. Key operations: isPresent()/isEmpty() check presence; get() retrieves the value (throws if empty, so prefer safer alternatives); orElse() returns a default value; orElseGet() lazily computes one from a Supplier; map() transforms the contained value; flatMap() chains multiple Optional-returning methods without nesting Optionals inside each other; ifPresent() runs a Consumer only when a value exists. Optional is best used as a return type for methods that might not have a result — not as a field type or method parameter.
  • : Autoboxing is the automatic conversion of a primitive type (int, double, boolean, etc.) to its corresponding wrapper class (Integer, Double, Boolean). Unboxing is the reverse — wrapper to primitive. The Java compiler inserts the conversion calls (Integer.valueOf() for boxing, intValue() for unboxing) so you rarely need to write them explicitly. This makes code cleaner and lets primitives work with generics and collections, which require objects. Two important pitfalls: first, comparing boxed integers with == tests object identity, not value — only values in the cache range -128 to 127 are guaranteed to be the same object, so always use .equals() for wrapper comparisons; second, unboxing a null wrapper throws a NullPointerException, so check for null before unboxing.