Java Code Snippets:)

Madhav Ganesan - Aug 6 - - Dev Community

Syntax

Access Modifiers:

Public
The classes, methods, or variables which are defined as public, can be accessed by any class or method.

Protected
Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
(Note: This keyword is only allowed for nested classes)

Private
The private class, methods, or variables defined as private can be accessed within the class only.

Default
Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.

package com.example;

public class Example {
    private int privateVar = 10;
    int defaultVar = 20;
    protected int protectedVar = 30;
    public int publicVar = 40;

    public static void main(String[] args) {
        Example example = new Example();

        // Accessing all variables within the same class
        System.out.println("Private Var: " + example.privateVar);
        System.out.println("Default Var: " + example.defaultVar);
        System.out.println("Protected Var: " + example.protectedVar);
        System.out.println("Public Var: " + example.publicVar);
    }
}

//Another file
package com.example;

public class Example1 {
    public static void main(String[] args) {
        Example example = new Example();

        // Private variable is inaccessible
        System.out.println("Default Var: " + example.defaultVar);
        System.out.println("Protected Var: " + example.protectedVar);
        System.out.println("Public Var: " + example.publicVar);
    }
}

// File: Different.java
package com.example.subpackage;

import com.example.Example;

public class Different extends Example {
    public static void main(String[] args) {
        Example example = new Example();
        Different subClassExample = new Different();

        // Private variable is inaccessible
        // Default variable is inaccessible
        // Protected variable is inaccessible
        System.out.println("Public Var: " + example.publicVar);

        // Accessing protected variable through inheritance
        System.out.println("Protected Var (through inheritance): " + subClassExample.protectedVar);
    }
}
Enter fullscreen mode Exit fullscreen mode

Packages

They are used for organizing and managing classes, interfaces and sub-packages. They provide namespace management and code reusability.

package com.example.myapp;

public class MyClass {
    // Class code here
}
Enter fullscreen mode Exit fullscreen mode

Datatypes

public class Main {

    // Class to demonstrate structure equivalent
    static class Person {
        String name; // Default value is null
        int age; // Default value is 0
        float salary; // Default value is 0.0f
    }

    // Enumeration to demonstrate enum equivalent
    enum Color { RED, GREEN, BLUE }

    public static void main(String[] args) {

        // Basic data types
        int a = 10; // Default value is 0
        float b = 5.5f; // Default value is 0.0f
        char c = 'A'; // Default value is '\u0000'
        double d = 2.3; // Default value is 0.0d
        long e = 123456789L; // Default value is 0L
        short f = 32000; // Default value is 0
        byte g = 100; // Default value is 0
        boolean h = true; // Default value is false

        // Array
        int[] arr = {1, 2, 3, 4, 5};

        // Structure equivalent
        Person person1 = new Person();
        person1.age = 30;
        person1.salary = 55000.50f;

        // Enumeration
        Color myColor = Color.RED;
    }
}

Enter fullscreen mode Exit fullscreen mode

Overloading

Method Overloading occurs when multiple methods have the same name but different parameters within the same class. This is resolved at compile time.

class MathOperations {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to add two double values
    public double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();

        System.out.println(math.add(2, 3));
        System.out.println(math.add(1, 2, 3));
        System.out.println(math.add(2.5, 3.5));
    }
}
Enter fullscreen mode Exit fullscreen mode

Overriding

Method Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This is resolved at runtime

class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound(); // Calls method in Animal class

        Dog myDog = new Dog();
        myDog.makeSound(); // Calls overridden method in Dog class
    }
}
Enter fullscreen mode Exit fullscreen mode

Conversion

public class Main {
    public static void main(String[] args) {

        // 1. Convert String to Number (Integer)
        String strToInt = "123";
        int intValue = Integer.parseInt(strToInt);

        // 2. Convert Number (Integer) to String
        int numToStr = 456;
        String intToString = String.valueOf(numToStr);  // or Integer.toString(numToStr);

        // 3. Convert String to Double
        String strToDouble = "123.45";
        double doubleValue = Double.parseDouble(strToDouble);

        // 4. Convert Double to String
        double doubleToStr = 456.78;
        String doubleToString = String.valueOf(doubleToStr);  // or Double.toString(doubleToStr);

        // 5. Convert Char to Number (ASCII value)
        char charToNum = 'A';
        int asciiValue = (int) charToNum;

        // 6. Convert Char to String
        char charToStr = 'B';
        String charToString = String.valueOf(charToStr);  // or Character.toString(charToStr);

        // Bonus: Convert int to double and double to int
        int intToDouble = 10;
        double convertedDouble = (double) intToDouble;  // int to double

        double doubleToInt = 10.99;
        int convertedInt = (int) doubleToInt;  // double to int

    }
}
Enter fullscreen mode Exit fullscreen mode
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // 1. Convert Array to ArrayList
        Integer[] array = {1, 2, 3, 4};
        ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(array));
        System.out.println("Array to ArrayList: " + arrayList);

        // 2. Convert ArrayList to Array
        Integer[] arrayFromArrayList = new Integer[arrayList.size()];
        arrayList.toArray(arrayFromArrayList);
        System.out.println("ArrayList to Array:");
        for (int num : arrayFromArrayList) {
            System.out.print(num + " ");
        }
        System.out.println();

        // 3. Convert ArrayList to LinkedList
        LinkedList<Integer> linkedListFromArrayList = new LinkedList<>(arrayList);
        System.out.println("ArrayList to LinkedList: " + linkedListFromArrayList);

        // 4. Convert LinkedList to ArrayList
        ArrayList<Integer> arrayListFromLinkedList = new ArrayList<>(linkedListFromArrayList);
        System.out.println("LinkedList to ArrayList: " + arrayListFromLinkedList);

        // 5. Convert Queue to Stack
        Queue<Integer> queue = new LinkedList<>(Arrays.asList(1, 2, 3));
        Stack<Integer> stackFromQueue = new Stack<>();
        while (!queue.isEmpty()) {
            stackFromQueue.push(queue.remove());
        }
        System.out.println("Queue to Stack: " + stackFromQueue);

        // 6. Convert Stack to Queue
        Queue<Integer> queueFromStack = new LinkedList<>();
        while (!stackFromQueue.isEmpty()) {
            queueFromStack.add(stackFromQueue.pop());
        }
        System.out.println("Stack to Queue: " + queueFromStack);

        // 7. Convert Array to Stack
        Stack<Integer> stackFromArray = new Stack<>();
        for (int num : array) {
            stackFromArray.push(num);
        }
        System.out.println("Array to Stack: " + stackFromArray);

        // 8. Convert Stack to Array
        Integer[] arrayFromStack = new Integer[stackFromArray.size()];
        int i = 0;
        while (!stackFromArray.isEmpty()) {
            arrayFromStack[i++] = stackFromArray.pop();
        }
        System.out.println("Stack to Array:");
        for (int num : arrayFromStack) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Enter fullscreen mode Exit fullscreen mode

Array

Arrays and Objects are always passed by reference not as copy. Primitive data types are passed by value.

import java.util.Arrays

public class Main {
    public static void main(String[] args) {

        // Integer array
        int[] intArray = new int[5]; // Default values: 0
        int[] intArray2 = {1, 2, 3, 4, 5}; // Initialized with specific values

        int length = arr.length;

        Arrays.sort(arr);
        int index = Arrays.binarySearch(arr, key);
        Arrays.equals(arr1,arr2);
        Arrays.toString(arr);

        int[][] matrix = {
           {1, 2, 3},
           {4, 5, 6},
           {7, 8, 9}
        };

        // Float array
        float[] floatArray = new float[5]; // Default values: 0.0f
        float[] floatArray2 = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f}; // Initialized with specific values

    }
}
Enter fullscreen mode Exit fullscreen mode

Default Keyword

Default method is a method defined in an interface with the default keyword. This allows interfaces to provide method implementations without affecting the classes that implement the interface.

interface Animal {
    void makeSound(); // abstract method

    // Default method
    default void sleep() {
        System.out.println("Sleeping...");
    }
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();

        dog.makeSound(); // Output: Bark
        dog.sleep();     // Output: Sleeping...

    }
}
Enter fullscreen mode Exit fullscreen mode

this keyword

The this keyword is used to refer to the instance variables of the current class. This is particularly useful when the method or constructor parameters have the same names as the instance variables.

public class Example {
    private int value;

    public Example(int value) {
        this.value = value; // Refers to the instance variable 'value'
    }

    public void setValue(int value) {
        this.value = value; // Refers to the instance variable 'value'
    }
}
Enter fullscreen mode Exit fullscreen mode

Static keyword

It indicates that a member (variable, method, or nested class) belongs to the class itself rather than to instances of the class.
(Note: We cannot declare a static variable inside a non-static method)

public class StaticExample {
    // Static variable
    static int staticVariable = 10;

    // Instance variable
    int instanceVariable = 20;

    // Static method
    static void staticMethod() {
        // Can access static variable
        System.out.println(staticVariable);

        // Cannot access instance variable directly
        // System.out.println(instanceVariable);
    }

    // Instance method
    void instanceMethod() {

        // Can access static variable
        System.out.println(staticVariable);

        // Can access instance variable
        System.out.println(instanceVariable);
    }

    // Static nested class
    static class StaticNestedClass {
        void display() {
            System.out.println("Static nested class method called.");
            // Can access static members of the outer class
            System.out.println("Static variable from nested class: " + staticVariable);
        }
    }

    public static void main(String[] args) {
        // Call static method
        StaticExample.staticMethod();

        // Create an instance of the class
        StaticExample example = new StaticExample();
        // Call instance method
        example.instanceMethod();

        // Create an instance of the static nested class
        StaticNestedClass nestedClass = new StaticNestedClass();
        nestedClass.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Initialization

(Note: Only instance and static variables are intialized with default values)

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
          int num;
          int num1=0;
          System.out.println(num); //Throws error
          System.out.println(num1); // prints 0 
    }
}
Enter fullscreen mode Exit fullscreen mode

Display methods and its parameters of a class

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        Class<?> clazz = LinkedList.class;
        // Get all methods of the class
        Method[] methods = clazz.getDeclaredMethods();
        // Print the names and parameters of all methods
        for (Method method : methods) {
            System.out.print("Method Name: " + method.getName());
            System.out.print(", Parameters: ");
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter : parameters) {
                System.out.print(parameter.getType().getName() + " " + parameter.getName() + ", ");
            }
            System.out.println();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Basic Input/Output

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // Reading integer input
        System.out.print("Enter an integer: ");
        int intValue = scan.nextInt();
        System.out.println("Integer entered: " + intValue);

        // Reading double input
        System.out.print("Enter a double: ");
        double doubleValue = scan.nextDouble();
        System.out.println("Double entered: " + doubleValue);

        // Reading string input (including spaces)
        System.out.print("Enter a string: ");
        scan.nextLine(); // Consume the newline character
        String stringValue = scan.nextLine();
        System.out.println("String entered: " + stringValue);

        // Reading character input
        System.out.print("Enter a character: ");
        char charValue = scan.next().charAt(0);
        System.out.println("Character entered: " + charValue);

        // Reading boolean input
        System.out.print("Enter a boolean (true/false): ");
        boolean booleanValue = scan.nextBoolean();
        System.out.println("Boolean entered: " + booleanValue);

        // Reading input until there is no more input available
        System.out.println("Enter multiple lines of input (Ctrl+D / Ctrl+Z to exit):");
        scan.nextLine(); // Consume the newline character
        while (scan.hasNext()) {
            String line = scan.nextLine();
            System.out.println("Input: " + line);
        }

        scan.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

For Loop

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; ++i) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
Enter fullscreen mode Exit fullscreen mode

While Loop

public class Main {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            System.out.print(i + " ");
            ++i;
        }
        System.out.println();
    }
}
Enter fullscreen mode Exit fullscreen mode

Functions

public class Main {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println("Sum: " + result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Classes and Objects

public class Rectangle {
    private int width, height;

    public Rectangle(int w, int h) {
        this.width = w;
        this.height = h;
    }

    public int area() {
        return width * height;
    }

    public static void main(String[] args) {
        Rectangle rect = new Rectangle(5, 3);
        System.out.println("Area: " + rect.area());
    }
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

public class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
}

public class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }

    public static void main(String[] args) {
        Shape shape = new Circle();
        shape.draw();
    }
}
Enter fullscreen mode Exit fullscreen mode

Singleton

public class Singleton {
    private static Singleton instance;

    // Private constructor to prevent instantiation
    private Singleton() { }

    // Public method to provide access to the instance
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Final keyword

It is created by adding final keyword

1) Final variable
This variable once initialized cannot be changed

public class FinalVariableExample {
    public static void main(String[] args) {
        final int x = 10;
        // x = 20; // This will cause a compilation error
        System.out.println(x);// 10
    }
}
Enter fullscreen mode Exit fullscreen mode

2) Final method
These methods cannot be overriden

class Parent {
    final void show() {
        System.out.println("This is a final method.");
    }
}

class Child extends Parent {
    // void show() { // This will cause a compilation error
    //    System.out.println("Trying to override.");
    // }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        Child c = new Child();
        c.show(); // Output: This is a final method.
    }
}
Enter fullscreen mode Exit fullscreen mode

Super keyword

The super keyword in Java is used to refer to the immediate parent class of the current object. It provides a way to access members (methods and variables) of the parent class from within the child class.

class Parent {
    int x = 10;

    void display() {
        System.out.println("Parent's display method");
    }

    Parent() {
        System.out.println("Parent's constructor");
    }
}

class Child extends Parent {
    int x = 20;

    void display() {
        super.display(); // Calls the display method of Parent class
        System.out.println("Child's display method");
    }

    Child() {
        super(); // Calls the constructor of Parent class
        System.out.println("Child's constructor");
    }
}

public class Test {
    public static void main(String[] args) {
        Child obj = new Child();
        System.out.println("Value of x in Child: " + obj.x);
        obj.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Abstract

The abstract keyword in Java is used to define abstract classes and abstract methods. Abstract classes cannot be instantiated directly and are meant to be subclassed. Abstract methods do not have a body and must be implemented by subclasses.
It contains abstract and concrete methods

abstract class Animal {
    // Abstract method (does not have a body)
    abstract void makeSound();

    // Regular method
    void eat() {
        System.out.println("This animal is eating.");
    }
}

class Dog extends Animal {
    // The body of the abstract method is provided here
    void makeSound() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.makeSound();  // Output: Woof
        myDog.eat();        // Output: This animal is eating.
    }
}
Enter fullscreen mode Exit fullscreen mode

When one interface wants to inherit the methods from another interface, it uses the extends keyword.

An abstract class can implement an interface. This means the abstract class provides a partial implementation of the interface using the implements keyword.

An abstract class can extend another abstract class using extends keyword

Interface

It is a reference type similar to class that contains only constants, default methods, static methods and method signatures
(Note: Only default method's definition be present in interface)
(Note: Constants declared inside interface are public, static and final)

interface Animal {
    void makeSound(); // abstract method
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();

        dog.makeSound(); // Output: Bark
        cat.makeSound(); // Output: Meow
    }
}
Enter fullscreen mode Exit fullscreen mode

Overcomes Diamond Problem (multiple inheritance):

interface A {
    void display();
}

interface B extends A {
    default void display() {
        System.out.println("Display from B");
    }
}

interface C extends A {
    default void display() {
        System.out.println("Display from C");
    }
}

class D implements B, C {

    @Override
    public void display() {
        B.super.display();
        C.super.display();
        System.out.println("Display from D");
    }
}

public class Main {
    public static void main(String[] args) {
        D d = new D();
        d.display();

        //Output
        //Display from B
        //Display from C
        //Display from D
    }
}
Enter fullscreen mode Exit fullscreen mode

List

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

public class ListExample {
    public static void main(String[] args) {

        // Declare list as LinkedList
        List<Character> list = new LinkedList<>();

        // Add elements
        list.add('A');
        list.add('B');
        list.add('C');

        // Change implementation to ArrayList
        list = new ArrayList<>(list);

        // Add more elements
        list.add('D');
        list.add('E');

        // Change implementation to Vector
        list = new Vector<>(list);

        // Add more elements
        list.add('F');
        list.add('G');
    }
}
Enter fullscreen mode Exit fullscreen mode

Queue

The Queue interface in Java is part of the Java Collections Framework and represents a collection designed for holding elements prior to processing. It typically orders elements in a FIFO (first-in-first-out) manner, but other orderings are possible, such as LIFO (last-in-first-out) in the case of Deque implementations.

import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Deque;

public class QueueExample {
    public static void main(String[] args) {
        // Using LinkedList as a Queue
        Queue<String> queue = new LinkedList<>();
        queue.add("Java");
        queue.add("Python");
        queue.add("C++");

        // Reassigning to PriorityQueue
        queue = new PriorityQueue<>();
        queue.add("Java");
        queue.add("Python");
        queue.add("C++");

        // Reassigning to ArrayDeque
        queue = new ArrayDeque<>();
        queue.add("Java");
        queue.add("Python");
        queue.add("C++");
    }
}
Enter fullscreen mode Exit fullscreen mode

Collections

ArrayList

1.Dynamic resizing
2.Implements List interface

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);

        for (int num : list) {
            System.out.print(num + " ");
        }
        System.out.println();

        // Inserting an element
        list.add(2, "Ruby");

        // Accessing elements
        System.out.println("Element at index 3: + list.get(3));

        // Removing an element 
        list.remove(1);

        // Size of the list 
        System.out.println(list.size());

        // Check if list is empty 
        System.out.println("Is list empty? + list.isEmpty());

        // Check if list contains an element 
        System.out.println(list.contains("Java"));

        // Index of an element 
        System.out.println(list.indexOf("JavaScript"));

        // Last index of an element 
        System.out.println(list.lastIndexOf("Ruby"));

        // Clear the list
        list.clear()
    }
}
Enter fullscreen mode Exit fullscreen mode

Stack

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {

        // Create a stack
        Stack<String> stack = new Stack<>();

        // Push elements onto the stack
        stack.push("Java");
        stack.push("Python");
        stack.push("C++");

        // Print the stack after pushes
        System.out.println("Stack after pushes: " + stack);

        // Get the size of the stack
        int size = stack.size();
        System.out.println("Size of stack: " + size);

        // Peek at the top element without removing it
        String topElement = stack.peek();
        System.out.println("Top element (peek): " + topElement);

        // Pop an element from the stack
        String poppedElement = stack.pop();
        System.out.println("Popped element: " + poppedElement);

        // Print the stack after pop
        System.out.println("Stack after pop: " + stack);

        // Check if the stack is empty
        boolean isEmpty = stack.isEmpty();
        System.out.println("Is stack empty? " + isEmpty);

        // Get the size of the stack after pop
        size = stack.size();
        System.out.println("Size of stack after pop: " + size);

        // Search for an element
        int position = stack.search("Java");
        System.out.println("Position of element 'Java': " + position);

        Iterator<Integer> it = stack.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

LinkedList

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        // Create a new LinkedList
        LinkedList<String> linkedList = new LinkedList<>();

        // Add elements to the LinkedList
        linkedList.add("Java");
        linkedList.add("Python");
        linkedList.add("C++");
        System.out.println("Initial LinkedList: " + linkedList);

        // Add element at specific index
        linkedList.add(1, "JavaScript");
        System.out.println("After add(1, 'JavaScript'): " + linkedList);

        // Add element at the beginning
        linkedList.addFirst("HTML");
        System.out.println("After addFirst('HTML'): " + linkedList);

        // Add element at the end
        linkedList.addLast("CSS");
        System.out.println("After addLast('CSS'): " + linkedList);

        // Get elements
        System.out.println("First element: " + linkedList.getFirst());
        System.out.println("Last element: " + linkedList.getLast());
        System.out.println("Element at index 2: " + linkedList.get(2));

        // Remove elements
        linkedList.remove(); // removes the first element
        System.out.println("After remove(): " + linkedList);

        linkedList.remove(2); // removes the element at index 2
        System.out.println("After remove(2): " + linkedList);

        linkedList.removeFirst(); // removes the first element
        System.out.println("After removeFirst(): " + linkedList);

        linkedList.removeLast(); // removes the last element
        System.out.println("After removeLast(): " + linkedList);

        // Check if the list contains a specific element
        System.out.println("Contains 'Python': " + linkedList.contains("Python"));

        // Get the size of the list
        System.out.println("Size of LinkedList: " + linkedList.size());

        // Clear the list
        linkedList.clear();
        System.out.println("After clear(): " + linkedList);

        // Check if the list is empty
        System.out.println("Is LinkedList empty? " + linkedList.isEmpty());

        Iterator<String> it = linkedList.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

HashMap

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Alice", 90);
        map.put("Bob", 85);

        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Hashset

import java.util.HashSet;

public class Example {
    public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);

        System.out.println(set.contains(2));        
        System.out.println(set.contains(4));

        set.remove(2);
        System.out.println(set.contains(2));
    }
}

Enter fullscreen mode Exit fullscreen mode

String

public class StringExamples {
    public static void main(String[] args) {
        // Creating an empty string
        String emptyString = new String();
        System.out.println("Empty String: \"" + emptyString + "\"");

        // Creating a string from another string
        String original = "Hello, World!";
        String copy = new String(original);
        System.out.println("Copy of original: " + copy);

        // Creating a string from a character array
        char[] charArray = {'J', 'a', 'v', 'a'};
        String fromCharArray = new String(charArray);
        System.out.println("String from char array: " + fromCharArray);

        // Length of the string
        int length = original.length();
        System.out.println("Length of original string: " + length);

        //Check if two strings are equal
        String str1 = "Java";
        String str2 = "Java";

        System.out.println(str1.equals(str2)); // true


        // Check if the string is empty
        boolean isEmpty = original.isEmpty();
        System.out.println("Is original string empty? " + isEmpty);

        // Character at a specific index
        char charAt2 = original.charAt(2);
        System.out.println("Character at index 2 in original string: " + charAt2);

        // Convert to uppercase
        String upperCaseStr = original.toUpperCase();
        System.out.println("Uppercase: " + upperCaseStr);

        // Convert to lowercase
        String lowerCaseStr = original.toLowerCase();
        System.out.println("Lowercase: " + lowerCaseStr);

        // Character methods
        char ch1 = 'A';
        char ch2 = 'a';
        char ch3 = '1';
        char ch4 = ' ';
        char ch5 = '\u2603'; // Unicode character for snowman

        System.out.println("isDigit('1'): " + Character.isDigit(ch3)); // true
        System.out.println("isLetter('A'): " + Character.isLetter(ch1)); // true
        System.out.println("isLetterOrDigit('a'): " + Character.isLetterOrDigit(ch2)); // true
        System.out.println("isLowerCase('a'): " + Character.isLowerCase(ch2)); // true
        System.out.println("isUpperCase('A'): " + Character.isUpperCase(ch1)); // true
        System.out.println("isWhitespace(' '): " + Character.isWhitespace(ch4)); // true
        System.out.println("toLowerCase('A'): " + Character.toLowerCase(ch1)); // 'a'
        System.out.println("toUpperCase('a'): " + Character.toUpperCase(ch2)); // 'A'

        // Reverse a string using StringBuilder
        String reversedStr = reverseUsingStringBuilder(original);
        System.out.println("Reversed string: " + reversedStr);
    }

    public static String reverseUsingStringBuilder(String str) {
        StringBuilder stringBuilder = new StringBuilder(str);
        stringBuilder.reverse();
        return stringBuilder.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

File I/O

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        // Write to file
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, file I/O!\n");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read from file
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Exception Handling

(Note: When catching exceptions the more specific exceptions must be listed before the more general)

public class Main {
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("Division by zero");
        }
        return a / b;
    }

    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Inner Classes

An inner class is a class defined within another class.

  1. Member Inner Class A member inner class is associated with an instance of the outer class. It has access to the outer class's instance variables and methods.
public class OuterClass {
    private String outerField = "Outer Field";

    class InnerClass {
        void display() {
            System.out.println("Accessing outer field: " + outerField);
        }
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.display();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Static Nested Class A static nested class is a static class defined within another class. It does not have access to the instance members of the outer class but can access its static members.
public class OuterClass {
    private static String staticField = "Static Field";

    static class StaticNestedClass {
        void display() {
            System.out.println("Accessing static field: " + staticField);
        }
    }

    public static void main(String[] args) {
        OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
        nested.display();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Local Inner Class A local inner class is defined within a block or method and can access local variables (which must be final or effectively final) and the outer class's members.
public class OuterClass {
    void method() {
        final String localVariable = "Local Variable";

        class LocalInnerClass {
            void display() {
                System.out.println("Accessing local variable: " + localVariable);
            }
        }

        LocalInnerClass localInner = new LocalInnerClass();
        localInner.display();
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.method();
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Anonymous Inner Class An anonymous inner class is a type of inner class without a name. It can extend exactly one class or implement exactly one interface
class BaseClass {
    void display() {
        System.out.println("BaseClass display()");
    }
}

public class Main {
    public static void main(String[] args) {
        BaseClass obj = new BaseClass() {
            @Override
            void display() {
                System.out.println("Anonymous inner class display()");
            }
        };

        obj.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Lambda Expressions

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

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>();
        nums.add(1);
        nums.add(2);
        nums.add(3);
        nums.add(4);
        nums.add(5);

        nums.replaceAll(n -> n * 2);

        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Enter fullscreen mode Exit fullscreen mode

Switch Statement

public class Main {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid day");
                break;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Normal Pointers

Java does not use explicit pointers as C++ does;

Lower and Upper case:

public class Main {
    public static void main(String[] args) {
        String str1 = "Hello, World!";
        String str2= "HELLO, WORLD!";

        String lowerStr = str2.toLowerCase();
        String upperStr = str1.toUpperCase();

        System.out.println(lowerStr);  // Output: hello, world!
        System.out.println(upperStr);  // Output: HELLO, WORLD!
    }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .