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?
According to the Java language standard, the second semicolon is an empty statement. An empty statement does nothing. EmptyStatement: ; Execution of an empty statement always completes normally. Follow this answer to receive notifications.
Two semicolons can also occur in for loops: for(;;) { ... } In this case, all three 'slots' are empty, nothing is initialized, or incremented, and there's no condition for when the loop should run. This is a way to write an eternal loop that can only be left from inside the block with a break statement.
That is a for ever loop. it is just a loop with no defined conditions to break out. Follow this answer to receive notifications. answered Apr 15, 2011 at 12:52.
If you place semicolon after a for loop then it is technically correct syntax. Because it is considered as an empty statement - that means nothing to execute. for(i=0;i<n;i++); An empty statement executed up to n times.
It is equivalent to while(true)
.
A for-loop has three elements:
for(;;)
is not setting any of them, making it an endless loop.
Reference: The for statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With