Java Programming Interview Questions

author image Hirely
at 05 Jan, 2025

Question: How to implement a simple calculator using switch-case in Java?

Answer:

A simple calculator in Java can be implemented using the switch-case statement to handle different arithmetic operations. The basic operations we’ll include are addition, subtraction, multiplication, and division. We’ll take input from the user for two numbers and the operation they want to perform.

Here is an example implementation of a simple calculator using switch-case:


Java Code for a Simple Calculator Using Switch-Case:

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        // Create a Scanner object to read user input
        Scanner scanner = new Scanner(System.in);

        // Input first number
        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        // Input second number
        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();

        // Input the operation to perform
        System.out.print("Enter the operation (+, -, *, /): ");
        char operation = scanner.next().charAt(0);

        // Result variable
        double result;

        // Switch case to handle operations
        switch (operation) {
            case '+': // Addition
                result = num1 + num2;
                System.out.println("Result: " + result);
                break;
                
            case '-': // Subtraction
                result = num1 - num2;
                System.out.println("Result: " + result);
                break;
                
            case '*': // Multiplication
                result = num1 * num2;
                System.out.println("Result: " + result);
                break;
                
            case '/': // Division
                // Handle division by zero
                if (num2 == 0) {
                    System.out.println("Error: Division by zero is not allowed.");
                } else {
                    result = num1 / num2;
                    System.out.println("Result: " + result);
                }
                break;

            default: // Invalid operation
                System.out.println("Error: Invalid operation. Please enter one of (+, -, *, /).");
                break;
        }

        // Close the scanner
        scanner.close();
    }
}

Explanation:

  1. Input:

    • The program first prompts the user to input two numbers (num1 and num2) and the operation they want to perform.
    • The operation is input as a character (e.g., +, -, *, /).
  2. Switch-Case:

    • The switch-case statement is used to determine the operation that the user wants to perform.
    • The operation is matched with cases:
      • + for addition,
      • - for subtraction,
      • * for multiplication,
      • / for division.
  3. Division by Zero Handling:

    • If the user selects the division operation (/), the program checks if num2 is zero. If num2 is zero, a message is displayed saying “Error: Division by zero is not allowed.”
    • If num2 is non-zero, it performs the division.
  4. Default Case:

    • If the user inputs an invalid operation, the default case is triggered, printing an error message.
  5. Output:

    • The result of the operation is printed to the console.

Example Output:

Case 1: Addition

Enter the first number: 10
Enter the second number: 5
Enter the operation (+, -, *, /): +
Result: 15.0

Case 2: Division by Zero

Enter the first number: 10
Enter the second number: 0
Enter the operation (+, -, *, /): /
Error: Division by zero is not allowed.

Case 3: Invalid Operation

Enter the first number: 10
Enter the second number: 5
Enter the operation (+, -, *, /): ^
Error: Invalid operation. Please enter one of (+, -, *, /).

Conclusion:

This is a simple implementation of a calculator using the switch-case statement in Java. It handles basic arithmetic operations and includes error handling for invalid operations and division by zero.

Question: How do you remove duplicates from an ArrayList in Java?

Answer:

In Java, you can remove duplicates from an ArrayList by utilizing several methods. Some of the common approaches include:

  1. Using a Set (HashSet or LinkedHashSet)
  2. Using Java Streams (Java 8 and above)

Let’s go through each approach with examples:


1. Using a Set (HashSet or LinkedHashSet)

A Set is a collection that doesn’t allow duplicate elements. By converting the ArrayList to a Set, duplicates are automatically removed. You can then convert the Set back to an ArrayList if needed.

  • HashSet removes duplicates but does not maintain the order of elements.
  • LinkedHashSet removes duplicates and preserves the insertion order.

Using HashSet:

import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Create an ArrayList with duplicates
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(4);

        // Convert ArrayList to HashSet to remove duplicates
        HashSet<Integer> set = new HashSet<>(list);

        // Convert HashSet back to ArrayList (optional)
        ArrayList<Integer> resultList = new ArrayList<>(set);

        // Print the result
        System.out.println("ArrayList without duplicates: " + resultList);
    }
}

Output:

ArrayList without duplicates: [1, 2, 3, 4]

Using LinkedHashSet (Preserving Order):

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Create an ArrayList with duplicates
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(4);

        // Convert ArrayList to LinkedHashSet to remove duplicates and preserve order
        LinkedHashSet<Integer> set = new LinkedHashSet<>(list);

        // Convert LinkedHashSet back to ArrayList (optional)
        ArrayList<Integer> resultList = new ArrayList<>(set);

        // Print the result
        System.out.println("ArrayList without duplicates (order preserved): " + resultList);
    }
}

Output:

ArrayList without duplicates (order preserved): [1, 2, 3, 4]

2. Using Java Streams (Java 8 and above)

In Java 8 and later, you can use Streams to easily remove duplicates by converting the ArrayList to a stream, applying the distinct() method, and then collecting the result back into an ArrayList.

Using Streams:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Create an ArrayList with duplicates
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(4);

        // Use streams to remove duplicates
        List<Integer> resultList = list.stream()
                                      .distinct()  // Removes duplicates
                                      .collect(Collectors.toList());

        // Print the result
        System.out.println("ArrayList without duplicates: " + resultList);
    }
}

Output:

ArrayList without duplicates: [1, 2, 3, 4]

3. Using a Manual Loop and Checking for Duplicates

This method involves manually checking each element of the ArrayList and adding it to a new list only if it hasn’t been added already. This approach does not rely on Set or Stream and can be useful in certain situations.

import java.util.ArrayList;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Create an ArrayList with duplicates
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(4);

        // Create a new ArrayList to hold unique values
        ArrayList<Integer> resultList = new ArrayList<>();

        // Loop through the original list and add elements to resultList if not already present
        for (Integer num : list) {
            if (!resultList.contains(num)) {
                resultList.add(num);
            }
        }

        // Print the result
        System.out.println("ArrayList without duplicates: " + resultList);
    }
}

Output:

ArrayList without duplicates: [1, 2, 3, 4]

Comparison of Methods:

MethodProsCons
Using HashSet or LinkedHashSetSimple and efficient for removing duplicates. LinkedHashSet maintains order.HashSet does not preserve insertion order.
Using StreamsConcise and modern approach. Very readable for Java 8+.Requires Java 8 or higher. May not be the most efficient for large lists.
Manual LoopGood for custom logic. No external data structures.Less efficient than using a Set. More verbose and harder to maintain.

Conclusion:

  • For removing duplicates efficiently, the best approach is typically to use a Set (either HashSet or LinkedHashSet depending on whether you need to preserve order).
  • If you’re using Java 8 or later, Streams offer a concise and functional approach to removing duplicates with the distinct() method.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Java interview questions, Java interview experiences, and details about various Java job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now