New to java, forgive the amateur question...
I am reversing a string. I understand the beginning, but I got confused when declaring char ch...
How is it that char ch is allowed in the for loop as well as again in the while loop? Does it overwrite the previous char ch, or does it look at it as new? I assume it has to remember what ch is because I can use .pop() on it, and it knows I am referring to the created stack.
Also, How is it that when I pop (remove) an item, I can immediately after store it in a string? Isn't it removed...? Is the reason because pop returns the value being popped, so I can store ch, the variable popping, and it simply attaches that result?
Code below:
public static String reverseString(String str) {
int size = str.length();
Stack s = new Stack(size);
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
s.push(ch);
}
String result = "";
while(!s.isEmpty()) {
char ch = s.pop();
result = result + ch;
}
return result;
}