Jason arora Jason arora - 1 year ago 60
Java Question

Output for reversing a string does not come as expected

Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it?


The first line contains an integer T, denoting the number of test cases.
Each test case contains a string S, comprising of only lower case letters.


For each test case, print the reverse of the string S.


1 <= T <= 10
1 <= |S| <= 30

Input Sample Output(Plaintext Link)

ab ba
aba aba

Time Limit

1 sec(s) for each input file.

Memory Limit

256 MB

Source Limit

1024 KB



To reverse a string I used XOR logic to reverse the string.


public static void main(String args[] ) throws Exception
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; ++i)
String input = sc.next();
int len = input.length();
StringBuilder input1 = new StringBuilder(len);

int end = input.length()-1;
int start = 0;
while (start<end)


I am still getting the following error.

How do I correct this?

Answer Source

For approach 1, all you need to do is remove the call to sc.nextLine() and everything will be fine. That's because each line contains a "token" i.e. a word, delimited by whitespace. That's what sc.next() will return. No need to call nextLine() after that.

For your approach 2, you should carefully read the API documentation of StringBuilder. This shows you how to create a String from a StringBuilder, and vice versa. (Whenever I write Java code, I have a browser window with the API documentation for quick reference next to my editor window. It's very useful.)

Edit (after the latest edit to the question):

There is a compilation problem and a runtime problem. First, the XOR operator produces a result of type int, even if its operands are char. So you should put your expression in parentheses and cast it to char. Once you've done that, you'll get a runtime error because you are trying to index an element of a StringBuilder which does not yet exist. When you created the StringBuilder like this:

StringBuilder input1=new StringBuilder(len);

len is the initial capacity. The value of the StringBuilder instance is initially "". You then call setCharAt() but the current size of the StringBuilder is 0, so you get an index-out-of-bounds exception. You need to initialise the StringBuilder with the string itself:

StringBuilder input1=new StringBuilder(input);

Now you won't get an exception, but you'll get the wrong answer. That's because of a problem with your XOR logic.