Java Interview Questions ยท Coding Problems
Reversing a String in Java
Learn a fundamental Java technique: reversing a string. This example uses a for loop to build the reversed string character by character.
StringReverser.java
public class StringReverser {
public static void main(String[] args) {
String original = "Java";
String reversed = "";
System.out.println("Original string: " + original);
for (int i = original.length() - 1; i >= 0; i--) {
reversed = reversed + original.charAt(i);
}
System.out.println("Reversed string: " + reversed);
}
}
Step by step
- The program starts in the main method. We declare a String variable 'original' and initialize it with the value "Java". This string is stored in the String Pool.
- Next, we declare another String variable 'reversed' and initialize it as an empty string. This will hold our final reversed string.
- We print the original string to the console to see the starting value.
- We begin a for loop. First, the initialization part runs: 'int i = original.length() - 1'. 'original.length()' is 4, so 'i' is initialized to 3. This 'i' points to the last character's index.
- Loop Iteration 1: Check the condition 'i >= 0'. Since 3 >= 0 is true, the loop body will execute.
- Inside the loop, we get the character at index 'i' (which is 3) from 'original'. This character is 'a'. We concatenate it to the 'reversed' string. 'reversed' is now "a".
- End of Iteration 1: The update statement 'i--' is executed. 'i' is now 2.
- Loop Iteration 2: Check the condition 'i >= 0'. Since 2 >= 0 is true, the loop body will execute.
- We get the character at index 'i' (which is 2) from 'original'. This character is 'v'. We concatenate it to 'reversed'. 'reversed' is now "av".
- End of Iteration 2: The update statement 'i--' is executed. 'i' is now 1.
- Loop Iteration 3: Check the condition 'i >= 0'. Since 1 >= 0 is true, the loop body will execute.
- We get the character at index 'i' (which is 1) from 'original'. This character is 'a'. We concatenate it to 'reversed'. 'reversed' is now "ava".
- End of Iteration 3: The update statement 'i--' is executed. 'i' is now 0.
- Loop Iteration 4: Check the condition 'i >= 0'. Since 0 >= 0 is true, the loop body will execute.
- We get the character at index 'i' (which is 0) from 'original'. This character is 'J'. We concatenate it to 'reversed'. 'reversed' is now "avaJ".
- End of Iteration 4: The update statement 'i--' is executed. 'i' is now -1.
- Loop Termination: We check the condition 'i >= 0'. Since -1 >= 0 is false, the loop terminates. The variable 'i' goes out of scope.
- Finally, we print the value of the 'reversed' string to the console.