Assigning values in while condition

Viewed 120

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

4 Answers

This is due to the way assignment operators works.

In your loop condition you are stating

flag = true

Which returns true, but before that is assigns true to flag

This is because we are allowed do multiple assignments at once like this:

boolean test = flag = true;
// test == true

essentially (flag = true) translates to:

  • assign true to flag
  • return true for further use

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.

The only difference between = and == is :

  • = is an assignment operator, you give the value to the int, boolean, or whatever is the constant / variable.
  • == is an operator, which is used mainly in loops (for, else for, if, and while)

For your case, I might say that you need to use == inside the while loop :

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

It is also not great to use an infinite loop. You won't go outside and it will bug your code.

The first step your while loop test does is

flag=false

immediately followed by testing its value, which is false.

On a false value, the while loop isn't entered.

Related