Search code examples
javaloopsconditional-statementsinfinite-loopinfinite

Assigning values in while condition


First of all I know what is difference between = and ==. I want to use = to implicitly make infinite loop. So my code looks like this:

 boolean flag= true;
    while (flag=false){
        System.out.println("inside loop");
    }
    System.out.println("rest");

Unfortunately it doesn't enter the loop and prints "rest". Why? Am I reading this wrong? In while condition I am assigning value false to flag. So it loops while flag=false (which is).

And when I do this(changed from false to true) it enters infinite loop:

boolean flag= true;
    while (flag=true){
        System.out.println("inside loop");
    }
    System.out.println("rest");

In my opinion both of these examples should enter the loop. But only the 1st one does. Please help me understand this. Thanks


Solution

  • while (flag=false) does two things:

    1. It assigns false to flag
    2. It evaluates to while(false)

    Since it evaluates to while(false), its body will not be executed.

    Similarly,

    while (flag=true) does two things:

    1. It assigns true to flag
    2. It evaluates to while(true)

    Since it evaluates to while(true), its body will be executed infinitely.