How post Increment ++ Operator works while initialization

穿精又带淫゛_ 提交于 2019-12-12 05:14:47

问题


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

回答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




回答2:


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


来源:https://stackoverflow.com/questions/43494358/how-post-increment-operator-works-while-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!