+ 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
5 ответов
+ 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)
+ 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.
+ 4
Gaurav Agrawal is such a great teacher
+ 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
...
+ 2
Thank you very much to all of you! :)