top of page

The Ultimate Java Interview Questions Guide 2025 : Part-3

Database and JDBC

Q43: What is JDBC and its components?

JDBC (Java Database Connectivity) provides API for database operations:

Components:

  • DriverManager: Manages database drivers

  • Driver: Database-specific implementation

  • Connection: Database connection

  • Statement: SQL execution

  • ResultSet: Query results

// JDBC example
public class JDBCExample {
    public void connectToDatabase() {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String username = "user";
        String password = "password";
        
        try (Connection connection = DriverManager.getConnection(url, username, password);
             PreparedStatement statement = connection.prepareStatement(
                 "SELECT * FROM users WHERE age > ?")) {
            
            statement.setInt(1, 18);
            
            try (ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
                    System.out.println("Name: " + name + ", Age: " + age);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Q44: What is the difference between Statement and PreparedStatement?

StatementPreparedStatementSQL parsed every timePre-compiled SQLNo parameter bindingSupports parametersVulnerable to SQL injectionSafe from SQL injectionSlower performanceBetter performanceSimple queriesParameterized queries
// Statement - vulnerable to SQL injection
String sql = "SELECT * FROM users WHERE name = '" + userName + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);

// PreparedStatement - safe and efficient
String sql = "SELECT * FROM users WHERE name = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, userName);
ResultSet rs = pstmt.executeQuery();

Advanced Topics

Q45: What is reflection in Java?

Reflection allows inspecting and manipulating classes, methods, and fields at runtime:

import java.lang.reflect.*;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = String.class;
        
        // Get class information
        System.out.println("Class name: " + clazz.getName());
        System.out.println("Simple name: " + clazz.getSimpleName());
        
        // Get methods
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("Method: " + method.getName());
        }
        
        // Create instance and invoke method
        Object obj = clazz.getDeclaredConstructor().newInstance();
        Method lengthMethod = clazz.getMethod("length");
        int length = (Integer) lengthMethod.invoke("Hello");
        System.out.println("Length: " + length);
    }
}

Q46: What are annotations in Java?

Annotations provide metadata about code and can be processed at compile-time or runtime:

// Built-in annotations
@Override
public String toString() {
    return "Example";
}

@Deprecated
public void oldMethod() {
    // Deprecated method
}

@SuppressWarnings("unchecked")
public void uncheckedOperation() {
    List list = new ArrayList();
}

// Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Benchmark {
    String value() default "";
    int iterations() default 1;
}

// Using custom annotation
public class Service {
    @Benchmark(value = "Database operation", iterations = 100)
    public void performDatabaseOperation() {
        // Method implementation
    }
}

// Processing annotations with reflection
public class AnnotationProcessor {
    public static void processAnnotations(Class<?> clazz) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(Benchmark.class)) {
                Benchmark benchmark = method.getAnnotation(Benchmark.class);
                System.out.println("Benchmarking: " + benchmark.value());
                System.out.println("Iterations: " + benchmark.iterations());
            }
        }
    }
}

Q47: What is serialization and deserialization?

Serialization converts objects to byte streams for storage or transmission:

import java.io.*;

// Serializable class
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private String name;
    private int age;
    private transient String password; // Won't be serialized
    private static String company = "TechCorp"; // Won't be serialized
    
    public Employee(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
    
    // Getters and setters
}

// Serialization example
public class SerializationDemo {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 30, "secret123");
        
        // Serialization
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("employee.ser"))) {
            oos.writeObject(emp);
            System.out.println("Employee serialized");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream("employee.ser"))) {
            Employee deserializedEmp = (Employee) ois.readObject();
            System.out.println("Employee deserialized: " + deserializedEmp.getName());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Q48: What is the difference between shallow copy and deep copy?

import java.util.*;

class Address implements Cloneable {
    private String city;
    private String state;
    
    public Address(String city, String state) {
        this.city = city;
        this.state = state;
    }
    
    // Deep copy
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new Address(this.city, this.state);
    }
    
    // Getters and setters
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
}

class Person implements Cloneable {
    private String name;
    private Address address;
    
    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }
    
    // Shallow copy - shares address reference
    public Person shallowCopy() {
        return new Person(this.name, this.address);
    }
    
    // Deep copy - creates new address
    public Person deepCopy() throws CloneNotSupportedException {
        return new Person(this.name, (Address) this.address.clone());
    }
    
    // Getters
    public Address getAddress() { return address; }
}

// Usage example
public class CopyExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("New York", "NY");
        Person original = new Person("John", address);
        
        // Shallow copy
        Person shallowCopy = original.shallowCopy();
        shallowCopy.getAddress().setCity("Boston");
        System.out.println("Original city: " + original.getAddress().getCity()); // Boston
        
        // Deep copy
        Person deepCopy = original.deepCopy();
        deepCopy.getAddress().setCity("Chicago");
        System.out.println("Original city: " + original.getAddress().getCity()); // Boston
    }
}

Coding Challenges

Q49: Write a program to reverse a string without using built-in methods.

public class StringReversal {
    // Method 1: Using character array
    public static String reverse1(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        
        char[] chars = str.toCharArray();
        int left = 0, right = chars.length - 1;
        
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
        
        return new String(chars);
    }
    
    // Method 2: Using StringBuilder
    public static String reverse2(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            sb.append(str.charAt(i));
        }
        
        return sb.toString();
    }
    
    // Method 3: Using recursion
    public static String reverse3(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        
        return reverse3(str.substring(1)) + str.charAt(0);
    }
}

Q50: Find the first non-repeated character in a string.

import java.util.*;

public class FirstNonRepeatedChar {
    // Method 1: Using HashMap
    public static Character findFirst1(String str) {
        Map<CharacterInteger> charCount = new LinkedHashMap<>();
        
        // Count characters
        for (char c : str.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
        
        // Find first non-repeated
        for (Map.Entry<CharacterInteger> entry : charCount.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }
        
        return null;
    }
    
    // Method 2: Using array (for ASCII characters)
    public static Character findFirst2(String str) {
        int[] charCount = new int[256];
        
        // Count characters
        for (char c : str.toCharArray()) {
            charCount[c]++;
        }
        
        // Find first non-repeated
        for (char c : str.toCharArray()) {
            if (charCount[c] == 1) {
                return c;
            }
        }
        
        return null;
    }
    
    public static void main(String[] args) {
        String test = "abccba";
        System.out.println("First non-repeated: " + findFirst1(test)); // null
        
        test = "abccbad";
        System.out.println("First non-repeated: " + findFirst1(test)); // d
    }
}

Q51: Check if a string is a palindrome.

public class PalindromeChecker {
    // Method 1: Two pointers
    public static boolean isPalindrome1(String str) {
        if (str == null || str.length() <= 1) {
            return true;
        }
        
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        int left = 0, right = str.length() - 1;
        
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        
        return true;
    }
    
    // Method 2: Using StringBuilder
    public static boolean isPalindrome2(String str) {
        if (str == null || str.length() <= 1) {
            return true;
        }
        
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        String reversed = new StringBuilder(str).reverse().toString();
        
        return str.equals(reversed);
    }
    
    // Method 3: Recursive approach
    public static boolean isPalindrome3(String str) {
        if (str == null || str.length() <= 1) {
            return true;
        }
        
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        return isPalindromeRecursive(str, 0, str.length() - 1);
    }
    
    private static boolean isPalindromeRecursive(String str, int left, int right) {
        if (left >= right) {
            return true;
        }
        
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        
        return isPalindromeRecursive(str, left + 1, right - 1);
    }
    
    public static void main(String[] args) {
        System.out.println(isPalindrome1("A man, a plan, a canal: Panama")); // true
        System.out.println(isPalindrome1("race a car")); // false
    }
}

Q52: Implement binary search algorithm.

public class BinarySearch {
    // Iterative approach
    public static int binarySearchIterative(int[] arr, int target) {
        int left = 0, right = arr.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return -1; // Not found
    }
    
    // Recursive approach
    public static int binarySearchRecursive(int[] arr, int target) {
        return binarySearchRecursive(arr, target, 0, arr.length - 1);
    }
    
    private static int binarySearchRecursive(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1;
        }
        
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            return binarySearchRecursive(arr, target, mid + 1, right);
        } else {
            return binarySearchRecursive(arr, target, left, mid - 1);
        }
    }
    
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13, 15};
        System.out.println("Index of 7: " + binarySearchIterative(arr, 7)); // 3
        System.out.println("Index of 4: " + binarySearchRecursive(arr, 4)); // -1
    }
}

Q53: Find the second largest element in an array.

public class SecondLargest {
    public static Integer findSecondLargest(int[] arr) {
        if (arr == null || arr.length < 2) {
            return null;
        }
        
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;
        
        for (int num : arr) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num > secondLargest && num != largest) {
                secondLargest = num;
            }
        }
        
        return secondLargest == Integer.MIN_VALUE ? null : secondLargest;
    }
    
    // Using sorting (less efficient)
    public static Integer findSecondLargestUsingSorting(int[] arr) {
        if (arr == null || arr.length < 2) {
            return null;
        }
        
        Arrays.sort(arr);
        
        // Find second largest (handle duplicates)
        for (int i = arr.length - 2; i >= 0; i--) {
            if (arr[i] != arr[arr.length - 1]) {
                return arr[i];
            }
        }
        
        return null; // All elements are same
    }
    
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 1, 9, 3};
        System.out.println("Second largest: " + findSecondLargest(arr)); // 8
        
        int[] arr2 = {5, 5, 5, 5};
        System.out.println("Second largest: " + findSecondLargest(arr2)); // null
    }
}

Q54: Check if two strings are anagrams.

import java.util.*;

public class AnagramChecker {
    // Method 1: Using sorting
    public static boolean areAnagrams1(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() != str2.length()) {
            return false;
        }
        
        str1 = str1.toLowerCase().replaceAll("\\s", "");
        str2 = str2.toLowerCase().replaceAll("\\s", "");
        
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        
        return Arrays.equals(arr1, arr2);
    }
    
    // Method 2: Using character count
    public static boolean areAnagrams2(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() != str2.length()) {
            return false;
        }
        
        str1 = str1.toLowerCase().replaceAll("\\s", "");
        str2 = str2.toLowerCase().replaceAll("\\s", "");
        
        int[] charCount = new int[26];
        
        // Count characters in first string
        for (char c : str1.toCharArray()) {
            charCount[c - 'a']++;
        }
        
        // Subtract characters from second string
        for (char c : str2.toCharArray()) {
            charCount[c - 'a']--;
        }
        
        // Check if all counts are zero
        for (int count : charCount) {
            if (count != 0) {
                return false;
            }
        }
        
        return true;
    }
    
    // Method 3: Using HashMap
    public static boolean areAnagrams3(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() != str2.length()) {
            return false;
        }
        
        str1 = str1.toLowerCase().replaceAll("\\s", "");
        str2 = str2.toLowerCase().replaceAll("\\s", "");
        
        Map<CharacterInteger> charCount = new HashMap<>();
        
        // Count characters in first string
        for (char c : str1.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
        
        // Subtract characters from second string
        for (char c : str2.toCharArray()) {
            if (!charCount.containsKey(c)) {
                return false;
            }
            charCount.put(c, charCount.get(c) - 1);
            if (charCount.get(c) == 0) {
                charCount.remove(c);
            }
        }
        
        return charCount.isEmpty();
    }
    
    public static void main(String[] args) {
        System.out.println(areAnagrams1("listen", "silent")); // true
        System.out.println(areAnagrams2("The Eyes", "They See")); // true
        System.out.println(areAnagrams3("hello", "world")); // false
    }
}

Continue: The Ultimate Java Interview Questions Guide 2025 : Part-4

Comments


bottom of page