0

Can someone explain this

Can someone explain to me how the output is 15 class Exe { public static void main(String args[]) { float x=9; float y=5; int z= (int)(x/y); switch(z) { case 1: x+=2; case 2: x+=3; default: x+=1; } System.out.println(x); } }

26th Aug 2019, 7:53 AM
Dprincebh
Dprincebh - avatar
7 Answers
+ 6
x/y returns 1.8 (float) (int) 1.8 returns 1 (taking only integral part) in switch, falls into the first case. x = 9 + 2 = 11 no break, so second handling also executed x = 11 + 3 = 14 still no break, so third handling also executed x = 14 + 1 = 15
26th Aug 2019, 9:57 AM
Gordon
Gordon - avatar
+ 7
Amir01 Thanks for your question. - - - Because it is a double instead of a float. quote: A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d. It means that it's a single precision floating point literal rather than double precision. source: https://stackoverflow.com/questions/13704028/why-is-the-letter-f-used-at-the-end-of-a-float-no/13704077 - - - Double has more precision and is more accurate, but it also takes up more memory. Here is a reading about the difference between double and float : https://javarevisited.blogspot.com/2016/05/difference-between-float-and-double-in-java.html?m=1
27th Aug 2019, 2:24 AM
Gordon
Gordon - avatar
+ 4
Remember: If you donot use break statement at end of each case in switch, then all the cases that comes after matching case will also be executed.
26th Aug 2019, 9:37 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 3
For your case, put 'break;' at the end of case It will solve your problem like this, switch(z) { case 1: x+=2; break; case 2: x+=3; break; default: x+=1; } The output should be 11.0 Good Luck~
26th Aug 2019, 8:00 AM
Uchiha Itachi
Uchiha Itachi - avatar
+ 2
nice!
27th Aug 2019, 1:45 AM
Juan Debenedetti
Juan Debenedetti - avatar
+ 1
Gordon ,you are right! It makes a question in my mind. I think float variables needs to f at the end,but why above code hasn't any f?
26th Aug 2019, 6:22 PM
Amir01
Amir01 - avatar
+ 1
Gordon thanks
27th Aug 2019, 7:44 AM
Amir01
Amir01 - avatar