Core Java Interview Questions

author image Hirely
at 05 Jan, 2025

Question: How do you compare two strings in Java?

Answer:

In Java, there are several ways to compare strings, depending on what kind of comparison you want to perform. Here are the common methods:


1. Using equals() Method

The equals() method compares the content (i.e., characters) of two strings and returns true if they are identical, and false otherwise.

Example:

public class StringCompareExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = "World";

        // Compare using equals()
        if (str1.equals(str2)) {
            System.out.println("str1 and str2 are equal.");
        } else {
            System.out.println("str1 and str2 are not equal.");
        }

        if (str1.equals(str3)) {
            System.out.println("str1 and str3 are equal.");
        } else {
            System.out.println("str1 and str3 are not equal.");
        }
    }
}

Explanation:

  • str1.equals(str2) checks if the two strings have the same sequence of characters.
  • This method is case-sensitive, meaning "Hello" is not equal to "hello".

2. Using equalsIgnoreCase() Method

If you want to compare two strings ignoring case (e.g., "hello" and "HELLO" should be considered equal), you can use equalsIgnoreCase().

Example:

public class StringCompareExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";

        // Compare ignoring case
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("str1 and str2 are equal ignoring case.");
        } else {
            System.out.println("str1 and str2 are not equal.");
        }
    }
}

Explanation:

  • str1.equalsIgnoreCase(str2) ignores case sensitivity while comparing the strings.

3. Using compareTo() Method

The compareTo() method compares two strings lexicographically (i.e., based on the Unicode value of each character). It returns:

  • 0 if the strings are equal.
  • A positive value if the calling string is lexicographically greater than the argument string.
  • A negative value if the calling string is lexicographically less than the argument string.

Example:

public class StringCompareExample {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";
        String str3 = "apple";

        // Compare using compareTo()
        int result1 = str1.compareTo(str2);
        int result2 = str1.compareTo(str3);

        System.out.println("Comparison result between str1 and str2: " + result1);
        System.out.println("Comparison result between str1 and str3: " + result2);
    }
}

Explanation:

  • str1.compareTo(str2) returns a negative number because "apple" is lexicographically less than "banana".
  • str1.compareTo(str3) returns 0 because both strings are identical.

4. Using compareToIgnoreCase() Method

The compareToIgnoreCase() method works like compareTo(), but it ignores case differences when comparing strings.

Example:

public class StringCompareExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";

        // Compare ignoring case
        int result = str1.compareToIgnoreCase(str2);

        if (result == 0) {
            System.out.println("str1 and str2 are equal ignoring case.");
        } else if (result > 0) {
            System.out.println("str1 is greater than str2.");
        } else {
            System.out.println("str1 is less than str2.");
        }
    }
}

Explanation:

  • str1.compareToIgnoreCase(str2) ignores the case when comparing the two strings.
  • The result is 0 if they are equal, a positive value if str1 is lexicographically greater than str2, and a negative value if str1 is less.

5. Using == Operator

The == operator checks if two string references point to the same memory location (i.e., it checks for reference equality, not content equality). This is usually not what you want when comparing the content of two strings.

Example:

public class StringCompareExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");

        // Compare using ==
        if (str1 == str2) {
            System.out.println("str1 and str2 refer to the same object.");
        } else {
            System.out.println("str1 and str2 do not refer to the same object.");
        }

        if (str1 == str3) {
            System.out.println("str1 and str3 refer to the same object.");
        } else {
            System.out.println("str1 and str3 do not refer to the same object.");
        }
    }
}

Explanation:

  • str1 == str2 returns true because both strings refer to the same literal "Hello" in the string pool.
  • str1 == str3 returns false because str3 is created using new String(), meaning it refers to a different memory location, even though both strings have the same content.

Note: The == operator should not be used to compare the contents of two strings in Java. Use equals() for content comparison.


Summary of Methods:

MethodDescriptionUse Case
equals()Compares two strings for content equality.When you need to check if strings are equal in value.
equalsIgnoreCase()Compares two strings for content equality ignoring case.When case-insensitivity is required.
compareTo()Compares two strings lexicographically (returns integer).When you need to order or sort strings.
compareToIgnoreCase()Compares two strings lexicographically ignoring case.When case-insensitivity and lexicographic comparison are required.
== (Reference comparison)Compares if two strings refer to the same object in memory.Never use for content comparison (for reference checks).

Conclusion:

  • Use equals() for checking if two strings are equal in content.
  • Use compareTo() when you need to sort strings or find their lexicographic relationship.
  • Use equalsIgnoreCase() or compareToIgnoreCase() when you need case-insensitive comparison.
  • Avoid using == for content comparison as it checks for reference equality, not content equality.

Question: How to reverse a string in Java?

Answer:

In Java, there are multiple ways to reverse a string. Below are several methods to achieve this:


1. Using StringBuilder or StringBuffer

The easiest and most efficient way to reverse a string in Java is by using the StringBuilder or StringBuffer class. Both classes have a built-in method reverse() which can reverse the string.

Example (Using StringBuilder):

public class StringReverseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Using StringBuilder to reverse the string
        StringBuilder reversedStr = new StringBuilder(str);
        System.out.println("Reversed string: " + reversedStr.reverse());
    }
}

Explanation:

  • StringBuilder has a method reverse() that reverses the contents of the string and returns the reversed string.
  • StringBuffer works the same way as StringBuilder, but StringBuffer is synchronized (thread-safe), whereas StringBuilder is not.

2. Using a for Loop

You can also reverse a string manually by iterating over it in reverse order and appending each character to a new string.

Example:

public class StringReverseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String reversedStr = "";

        // Reversing the string using a for loop
        for (int i = str.length() - 1; i >= 0; i--) {
            reversedStr += str.charAt(i); // Appending each character
        }

        System.out.println("Reversed string: " + reversedStr);
    }
}

Explanation:

  • The loop iterates from the end of the string (str.length() - 1) to the beginning (i >= 0).
  • Each character is retrieved using charAt(i) and appended to a new string.

Note: Using String concatenation (+=) in a loop is inefficient for large strings because strings are immutable in Java, which means each concatenation creates a new string.


3. Using Recursion

You can also reverse a string using recursion, where the string is broken down into smaller substrings and reversed recursively.

Example:

public class StringReverseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Using recursion to reverse the string
        String reversedStr = reverseString(str);
        System.out.println("Reversed string: " + reversedStr);
    }
    
    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return str; // Base case: return empty string
        }
        return reverseString(str.substring(1)) + str.charAt(0); // Recursive case
    }
}

Explanation:

  • The reverseString method recursively calls itself on the substring starting from the second character (str.substring(1)), appending the first character (str.charAt(0)) to the reversed substring.
  • This process continues until the string is empty.

Note: Recursion is not the most efficient way for reversing long strings due to the risk of stack overflow and performance issues.


4. Using Java 8 Streams (for Advanced Users)

If you’re using Java 8 or later, you can leverage streams to reverse a string by converting it to a stream of characters, reversing the stream, and then collecting it back into a string.

Example:

import java.util.stream.Collectors;

public class StringReverseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Using Java 8 Streams to reverse the string
        String reversedStr = str.chars() // Convert to IntStream
                                 .mapToObj(c -> (char) c) // Convert to Character stream
                                 .collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
                                     java.util.Collections.reverse(list); // Reverse the list
                                     return list.stream();
                                 }))
                                 .map(String::valueOf) // Convert each character back to String
                                 .collect(Collectors.joining()); // Join all characters into one string
        
        System.out.println("Reversed string: " + reversedStr);
    }
}

Explanation:

  • str.chars() converts the string into an IntStream of characters.
  • .mapToObj(c -> (char) c) converts the stream of primitive ints into a stream of Character objects.
  • Collectors.collectingAndThen is used to reverse the list of characters.
  • The final step joins the characters back together into a string using Collectors.joining().

This method is not the most common but demonstrates how to use Java streams for this purpose.


5. Using char[] Array (Manual Reversal)

You can also convert the string into a char[] array, reverse the array, and then create a new string from the reversed array.

Example:

public class StringReverseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Convert the string to a char array
        char[] charArray = str.toCharArray();
        
        // Reverse the array manually
        int start = 0;
        int end = charArray.length - 1;
        while (start < end) {
            char temp = charArray[start];
            charArray[start] = charArray[end];
            charArray[end] = temp;
            start++;
            end--;
        }
        
        // Convert the reversed array back to a string
        String reversedStr = new String(charArray);
        System.out.println("Reversed string: " + reversedStr);
    }
}

Explanation:

  • The string is converted to a character array using toCharArray().
  • The array is then manually reversed by swapping characters from both ends.
  • Finally, the reversed character array is converted back into a string using the String(char[]) constructor.

Summary of Methods:

MethodDescriptionUse Case
StringBuilder.reverse()Simple and efficient way to reverse a string.Most commonly used method for reversing strings.
for loopManually reverse the string by iterating from end to start.Useful for understanding the reversal logic.
RecursionReverse the string by calling a method recursively.Good for educational purposes or for smaller strings.
Java 8 StreamsUse streams for advanced users who prefer a functional style.Useful for stream-based processing or learning functional programming in Java.
char[] arrayManually reverse the string using a character array.Useful when you need direct control over the characters.

Conclusion:

  • Use StringBuilder.reverse() for most cases, as it is efficient and easy to use.
  • Use a loop or recursion for educational purposes or when you want to manually control the process.
  • Java 8 Streams is an advanced method that is not commonly used but demonstrates the power of functional programming in Java.
  • Character array manipulation is an option when you want fine control over the reversal process.

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