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
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:
true for further useIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With