Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cant we assign a value for a variable inside if loops condition expression

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading