[英]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
. 因此,这里的
strToChar[strToChar.length-j]
应该抛出ArrayIndexOutOfBoundException
。
But it runs fine. 但是运行良好。 How is that happening?
这是怎么回事? Shouldn't it evaluate to this?
它不应该对此进行评估吗?
outString[0] = strToChar[6]; //This should throw exception
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. 在这里, strToChar.length将返回数组的实际长度为6。
The correct way to iterate an array with for loop would be: 使用for循环迭代数组的正确方法是:
for(int j = 0; j < strToChar.length;j++)
The index starting from 0 and going to < strToChar.length 索引从0开始到<strToChar.length
Acording to the java doc : 根据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.
Java编程语言保证运算符的操作数似乎按照特定的评估顺序(即从左到右)进行评估。
Which means j
is incremented before evaluating the right side of the expression. 这意味着
j
在计算表达式的右侧之前会增加。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.