user7784168
user7784168

Reputation: 9

How post Increment ++ Operator works while initialization

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

Upvotes: 0

Views: 158

Answers (2)

dsharew
dsharew

Reputation: 10665

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];

Upvotes: 0

Satish Saini
Satish Saini

Reputation: 2968

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

Upvotes: 1

Related Questions