Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 214
Stefan Jankovic Avatar asked Aug 26 '26 02:08

Stefan Jankovic


1 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
like image 77
Borislav Stoilov Avatar answered Aug 28 '26 14:08

Borislav Stoilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!