+ 2

Assignment of variables inside if-statement? (Java)

Hi people! Can variables be assigned inside if-statement in Java? How does it work? I don't understand the output of the code below, if someone could breafly explain it I would really appreciate it. Thanks a lot and forgive any grammar mistake https://code.sololearn.com/cAHFXELNqIkn/?ref=app

4th Jun 2019, 2:23 AM
Deroman
Deroman - avatar
6 Antworten
+ 14
● it is same as : boolean b=true; for (int i=0; i<10; i++){ if(b=!b){ System.out.println(b); } } ● if statement will execute when condition will be true : i=0 : b=!b (b=!true => b=false) => no output //now b is false i=1 : b=!b (b=!false => b=true) => output b that is true //now b is true i=2 : b=!b (b=!true => b=false) => no output //now b is false & so on... //that is why you can see output as true only, as it can only print when b is true.(also see it outputs true 5 times not 10 times, so 5 times value of b must be false)
4th Jun 2019, 3:18 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Hi Lenns! The line: if(b = !b) first reverses (or technically "negates") the value of b and then "assigns" it to b. It is good to know that assignment operation in Java returns the object to which value is being assigned. So, the value of b is returned as the condition for if-statement.
4th Jun 2019, 3:25 AM
777
777 - avatar
+ 4
Gaurav Agrawal is such a great teacher
9th Jun 2019, 11:31 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 2
try this: boolean b = true; for (int i = 0; i < 10; i++) { if (b = !b); System.out.printf("i=%d b=%b\n", i,b); } // output: i=0 b=false i=1 b=true i=2 b=false i=3 b=true ...
4th Jun 2019, 6:39 AM
zemiak
+ 2
Thank you very much to all of you! :)
4th Jun 2019, 10:35 AM
Deroman
Deroman - avatar