Home > Software engineering >  Cant we assign a value for a variable inside if loops condition expression
Cant we assign a value for a variable inside if loops condition expression

Time:08-20

I have a small program like this

public class O{
public static void main(String args[]){
int x=10,y=20;
if((x<y)||(x=5)>10)
System.out.println(x);
else
System.out.println(y);
}
}

The output of this program seems 10

My doubt Why is this giving output 10 instead of 5.. since i am assigning 5 for x in the loop condition .Please give a valid explanation .Thanks in advance

CodePudding user response:

Because of conditional execution:

if((x<y)||(x=5)>10)

The first statement 10<20 is true, so why should Java evaluate the second expression if the outcome is clear. That is why the result is 10. If you say

if((x<y)&&(x=5)>10)

the result would be 5 and thus it would output the value 20 of y.

  • Related