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

  1. 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.
  2. Next, we declare another String variable 'reversed' and initialize it as an empty string. This will hold our final reversed string.
  3. We print the original string to the console to see the starting value.
  4. 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.
  5. Loop Iteration 1: Check the condition 'i >= 0'. Since 3 >= 0 is true, the loop body will execute.
  6. 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".
  7. End of Iteration 1: The update statement 'i--' is executed. 'i' is now 2.
  8. Loop Iteration 2: Check the condition 'i >= 0'. Since 2 >= 0 is true, the loop body will execute.
  9. 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".
  10. End of Iteration 2: The update statement 'i--' is executed. 'i' is now 1.
  11. Loop Iteration 3: Check the condition 'i >= 0'. Since 1 >= 0 is true, the loop body will execute.
  12. 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".
  13. End of Iteration 3: The update statement 'i--' is executed. 'i' is now 0.
  14. Loop Iteration 4: Check the condition 'i >= 0'. Since 0 >= 0 is true, the loop body will execute.
  15. 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".
  16. End of Iteration 4: The update statement 'i--' is executed. 'i' is now -1.
  17. Loop Termination: We check the condition 'i >= 0'. Since -1 >= 0 is false, the loop terminates. The variable 'i' goes out of scope.
  18. Finally, we print the value of the 'reversed' string to the console.