0

How does this code print the reverse of a string?

String str = “stressed”; for (int i = str.length()-1; i >= 0; i—) System.out.print(str.charAt(i));

7th Aug 2019, 8:46 PM
Samuel
Samuel - avatar
1 Answer
+ 6
step by step code explaination: //this declares the String and gives it a value String str = "stressed"; //this for-loop in this case starts from 7 and goes down to 0, in general it starts from the index of the last charater of the string for(int i=str.length()-1;i>=0;i--){ //this prints the character of an String at an specific index System.out.print(str.charAt(i)); } step by step for-loop iterations: i = 7, str.charAt(7) = 'd' i = 6, str.charAt(6) = 'e' i = 5, str.charAt(5) = 's' i = 4, str.charAt(4) = 's' i = 3, str.charAt(3) = 'e' i = 2, str.charAt(2) = 'r' i = 1, str.charAt(1) = 't' i = 0, str.charAt(0) = 's' for-loop condition stops
7th Aug 2019, 9:04 PM
Anton Böhler
Anton Böhler - avatar