OneBite.Dev - Coding blog in a bite size

reverse a string in java

Code snippet on how to reverse a string in java

String inputString = "ABC"; 
  
// convert String to character array 
// by using toCharArray 
char[] charArray = inputString.toCharArray(); 

/* Our goal is to store reversed array 
   in the same variable, hence using 
   same array */
for (int i = charArray.length - 1; i >= 0; i--)  
{ 
   char temp = charArray[i]; 
   charArray[i] = charArray[charArray.length - i - 1]; 
   charArray[charArray.length - i - 1] = temp; 
} 

// convert charArray to String 
String result = new String(charArray); 
  
// print the reversed String 
System.out.println("Reversed String is: " + result); 

This code takes in a String input and reverses it. First, the String input is converted to a character array using the toCharArray() method. A loop is then used to iterate through each char element, swapping the current char with the char at the last index position. After the loop, the char array is converted back to a String and the reversed String is printed out.

java