Computing Magazine

Java Program to Reverse a String

Posted on the 15 April 2012 by In7rud3r

 

Open notepad or any other Java editor.
Type or copy paste the following code.
Code:

 

Java Program to reverse a String

public class Client {
public static void main(String[] args) {
// Create a stack
CharStack stack = new CharStack(40);
// Create a string to push on the stack
String str = “!no tis ot nuf era skcatS”;
int length = str.length();
System.out.println(“Original string: ” + str);
// Push the string char by char onto the stack
for (int i = 0; i<length; i++) {
stack.push(str.charAt(i));
}
System.out.print(“Reversed string: “);
// Pop and print each char from the stack
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
System.out.println();
}
}
// Source Filename: CharStack.java
public class CharStack {
}
Output from the program:
Original string: lleh ot og

Reversed string: go to hell


Back to Featured Articles on Logo Paperblog