java: can anyone explain. why does my code print out ##### and ***** instead of just #####?
int a=1, b=2, c=3;
if(a<b)
System.out.println("####");
else
System.out.println("&&&&");
System.out.println("****");
Answer :
int a=1, b=2, c=3;
if(a<b) // STATEMENT 1
System.out.println("####"); // STATEMENT
2
else // STATEMENT 3
System.out.println("&&&&"); //
STATEMENT 4
System.out.println("****"); // STATEMENT
5
EXPLANATION :
Here, STATEMENT 1, holds true ie. ( 1 < 2 ) , then the STATEMENT 2 executes . So, it will print #####
And , STATEMENT 3 and STATEMENT 4 , will not executed as " if " condition holds true. But STATEMENT 5 will be displayed , because there is no braces around the else statement , hence by default only the STATEMENT 4 will be considered as a part of else statement and not the STATEMENT 5.
Hence, it will also print *****
Hence, it will print both ##### and ***** instead of just #####.
BUT , IF WE WANT TO PRINT ONLY #####. ( We have to put curly braces around else statment ).
THE CODE changes to :
int a = 1, b = 2, c = 3; if (a < b) System.out.println("####"); else { System.out.println("&&&&"); System.out.println("****"); }
OUPTUT OF UPDATED CODE :
Get Answers For Free
Most questions answered within 1 hours.