0

I have written following code to reverse the given String:

String str = "abcdef";
char[] strToChar = str.toCharArray();
char[] outString = new char[strToChar.length];

for(int j = 0; j < strToChar.length; ) {
    int len = strToChar.length-j;
    outString[j++] = strToChar[strToChar.length-j];
}

As per my understanding initialization happens from Right to Left. Hence, strToChar[strToChar.length-j] here should throw ArrayIndexOutOfBoundException.

But it runs fine. How is that happening? Shouldn't it evaluate to this?

outString[0] = strToChar[6];    //This should throw exception
dsharew
  • 10,377
  • 6
  • 49
  • 75
  • 1
    well, you assign `outString[0] = strToChar[6-1]` here, which will result in no error. The key here is the `j++` which will lead to the right part not throwing an exception, as the left hand assignment variable will increase the `j` value due to the postincrement – SomeJavaGuy Apr 19 '17 at 11:27
  • The [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.7) states: "The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from _left to right_." – Thomas Apr 19 '17 at 11:28

2 Answers2

1

If I look at your code, then you have written your condition to be

for(int j = 0; j < strToChar.length;) 

here strToChar.length will return you the actual length of the array which is 6.

The correct way to iterate an array with for loop would be:

for(int j = 0; j < strToChar.length;j++)

The index starting from 0 and going to < strToChar.length

Satish Saini
  • 2,880
  • 3
  • 24
  • 38
  • well the missing last part of the for loop is the major part why there is no exception. So with the current implementation he´d either have to change it to `strToChar[strToChar.length-j-1]` or he´d be running into the exception he was curious about not beeing raised. – SomeJavaGuy Apr 19 '17 at 11:33
  • @SomeJavaGuy That's true! – Satish Saini Apr 19 '17 at 11:36
  • "The correct way to iterate an array with for loop [...]" no, this way is not "the correct way", it is the most common way. OP's code is somewhat uncommon but works just fine. – Gabriel Apr 19 '17 at 13:11
0

Acording to the java doc:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

Which means j is incremented before evaluating the right side of the expression.

So accordingly this code:

outString[j++] = strToChar[strToChar.length-j];

is evaluated to:

outString[0] = strToChar[6-1];

instead of:

outString[0] = strToChar[6-0];
dsharew
  • 10,377
  • 6
  • 49
  • 75