Java For simple loop code – output clarification

Can somebody explain me how this code prints 8 2
as the result?

public class Check{

    public static void main(String args[]){

        int x=0;
        int y=0;

        for(int z=0;z2||++y>2){

         System.out.println(x+" "+y);


How to understand unknown pieces of code:

  1. Indent the code properly. That helps enormously with reading code and it’s a simple, safe operation to get used to the code.

  2. Try to find a different way to express the same code in a more simple way. Run the code after each change to make sure your changes didn’t break anything.

    This means to replace ++x
    with x=x+1
    in the right place.

  3. Untangle nested/complex if()

So the rewritten code could look like this:

for(int z=0; z 2 ) { // first half of the OR
        x = x + 1;
    } else {
        // first half of the OR is false, we end up here
        y = y + 1; // pre increment
        if( y > 2 ) {
            x = x + 1;

Another good solution is to use poor man’s debugger:

for(int z=0; z<5; z++) {

    System.out.println("x="+x+", y="+y+", z="+z); // add this line in several places to see what happens
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java For simple loop code – output clarification

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录