by Dinesh Thakur Category: Control Structures

There will be times when we will want to include more than one statement in the initialization and iteration sections of the For loop. For example, consider the loop in the following program:

class CommaOperator

{
            public static void main(String args[] )
            {
                        int i,j;
                        for(i=1,j=20;j>=10;i++,j-=2)
                        {
                                    System.out.println(i+"  "+j);
                        }
            }
}

Comma Operator in Java

The value of variable i and j are set to 1 and 20 respectively in the for loop using comma operator. Since, the logical expression j >=10 is true (value of j = 20), body of the for loop will execute displaying the values i and j as 1 and 20 respectively on the screen. The value of i will be then incremented and the value of j will be decremented by 2. So, the next value displayed will be 2 and 18. The loop will execute for the time the logical expression j>=10 is true. In Java, the comma operator is applied only to the for loop.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article