Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

for-loop

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?

like image 215
Shawn Avatar asked Apr 15 '11 12:04

Shawn


People also ask

What does double semicolon mean in Java?

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.

What does for with 2 semicolons mean?

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.

What does a semicolon mean for a for loop in Java?

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.

What happens if we put semicolon after for loop in Java?

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.


1 Answers

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

like image 164
Bozho Avatar answered Sep 23 '22 05:09

Bozho