+ 2

In reverse a string code in java, what is the meaning of this line? String rev = ""; Please explain.

23rd Mar 2021, 12:11 PM
RAGUL
RAGUL - avatar
5 Réponses
+ 3
We generally create an empty string. String rev = ""; Then traverse over the original string from the last character and concat it to the string rev until you reach the first character. It basically stores your reversed string.
23rd Mar 2021, 12:34 PM
Avinesh
Avinesh - avatar
+ 2
I remember trying to work through the reversing a string challenge. I could not seem to get it through my head that strings in Java are immutable. I also didn't know I could use StringBuffer and StringBuilder. I didn't really need to create a new string object, I could have just printed it. But the code worked, even though getting there made me nuts 😂 char[] arr = text.toCharArray(); for(int i=0; i<arr.length/2; i++) { char character = arr[i]; arr[i] = arr[arr.length -i -1]; arr[arr.length -i -1] = character; } String reversed = new String(arr); System.out.print(reversed);
25th Mar 2021, 2:20 AM
Paul K Sadler
Paul K Sadler - avatar