-2

Please find the most frequently ask java question on interview ie "Program to reverse String Array without using the inbuilt function"

package program;

public class StringReverse {

String[] input={"Welcome"};
int i;
char rev11[];

void ReversStr(){

    char rev11[] = input[i].toCharArray();//since we know that we cant traversed String Array ,hence we have to change String array into Char array
    System.out.println("Array after reverse:");
    for (int i = rev11.length-1; i>=0; i--)
        System.out.print(rev11[i]);
}



public static void main(String[] args) {
    StringReverse obj=new StringReverse();
    obj.ReversStr();


}

}
snig
  • 63
  • 1
  • 8
  • What's your question? Whether that's a bad interview question? Yes, it is. – Jeroen Mostert Feb 21 '18 at 08:47
  • Possible duplicate of [Printing reverse of any String without using any predefined function?](https://stackoverflow.com/questions/2612976/printing-reverse-of-any-string-without-using-any-predefined-function) – Nishant Gupta Feb 21 '18 at 08:49
  • Calling `toCharArray` rather than `charAt` would prompt an immediate question; why? Printing out to console rather than returning a `String` that has been reversed is, I would say, a rather massive issue - probably a fail. But this question is so trivial that it could only ever be used as part of automated testing and the usefulness of that is questionable at best... – Boris the Spider Feb 21 '18 at 08:50
  • @ Boris the Spider we annot use method charAt(int) in the type String bcos it is not applicable for the given arguments () – snig Feb 21 '18 at 09:50
  • @NishantGupta if you check my program is specially for [String Array],i know ,same can be done with String type also. – snig Feb 21 '18 at 09:53
  • Don't understand your point. You current code copies the `char[]` inside the `String` by calling `toCharArray` - using `charAt` doesn't do that as you can access `char` by index. – Boris the Spider Feb 21 '18 at 17:22
  • A more advanced question would be: how do you deal with surrogate pairs? – Boris the Spider Feb 21 '18 at 17:22

1 Answers1

0

First: probably a new reversed array is required.

In that such a reversing has one/two pitfalls:

void reverse(String[] a) {
    for (int i = 0; i < a.length / 2; ++i) {
        int complementaryI = a.length - 1 - i;
        String temp = a[i];
        a[i] = a[complementaryI];
        a[complementaryI] = temp;
    }
}

The beginner's error being i < a.length.

If not in-situ reversed, but a new array is required, but the same code must be altered, one must copy the middle element of odd length array, or loop till a.length.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Would prefer a `String reverse(String input)` method. If it's going to be an in-place reverse, wouldn't you take `char[]`? But given that `String` is immutable, you would always have to build a new one, so I don't see the purpose of the in place method. – Boris the Spider Feb 21 '18 at 17:20