Test your understanding of how to reverse a string in Java without built-in methods, covering key interview concepts like immutability, loops, and string indexing. This quiz ensures you grasp the essential logic and details needed to solve common Java string interview questions.
Which of the following statements correctly explains why the expression s.reverse() does not work when attempting to reverse a String in Java?
Explanation: The String class in Java does not have a reverse() method, which is why s.reverse() is invalid. Unlike some other classes, String lacks this method due to its immutability. The idea that reverse() is only for integers or is a private method is incorrect, as reverse() doesn't exist at all in String. The mutability issue explains why we can't modify strings in-place, but it doesn't justify the absence of the method.
Given the statement that 'a string is immutable in Java,' what does this imply when reversing strings using loops?
Explanation: Immutability in Java means the original string's value cannot be modified, so reversing a string requires constructing a new string with characters in reverse order. No automatic reversal happens in memory, and reverse functions do not exist for String that change the original. Directly swapping indices or altering characters in place is not possible with immutable strings.
If you want to reverse the string 'selenium' using a for loop, at which index should you start iterating to access its characters in reverse order?
Explanation: To reverse a string, you need to start from the last character, which is at the index string length minus one because indexing is zero-based. Starting at zero would give you the first character, not the last. Indexing at total length is invalid because it is out of bounds. The median index would only help if you wanted partial reversal, not the whole string in reverse order.
In Java, what is the correct way to accumulate the reversed string inside a loop when iterating from end to start of the original string s?
Explanation: The correct way is to append each character from the original string at the current index to the accumulating reverse string using reverse = reverse + s.charAt(i);. The other expressions either don't exist in Java (such as s.reverse(i)) or use incorrect syntax for string concatenation, such as using multiplication or reversing at a given index.
When writing a for loop to reverse a string by accessing every character from last to first, what should be the correct loop condition?
Explanation: To include every character down to the first one, you should iterate while i is greater than or equal to 0, covering all valid indices. Using i u003C= length or i u003E length is incorrect, as those would go beyond the string's valid index range. Using i u003C= 0 would not include the starting index unless you started from a negative number, which is not logical here.