开发者

What do two semicolons mean in Java for loop? [duplicate]

This question already has answers here: How does a for loop work, specifically for(;;)? (6 answers) Closed 1 year ago.

I was looking inside the AtomicInteger Class开发者_运维技巧 and I came across the following method:

/**
 * Atomically increments by one the current value.
 *
 * @return the previous value
 */
public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}

Can someone explain what for(;;) means?


It is equivalent to while(true).

A for-loop has three elements:

  • initializer
  • condition (or termination expression)
  • increment expression

for(;;) is not setting any of them, making it an endless loop.

Reference: The for statement


It's the same thing as

while(true) {
    //do something
}

...just a little bit less clear.
Notice that the loop will exit if compareAndSet(current, next) will evaluate as true.


It's just another variation of an infinite loop, just as while(true){} is.


That is a for ever loop. it is just a loop with no defined conditions to break out.


It's an infinite loop, like while(true).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜