Win a copy of OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 this week in the Programmer Certification forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

Whizz Labs Diagnostic Test

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code:



Why the switch expression take case y? For me switch( x+y ) is 2, also it should print default. x and y are both final! And I thought (x+y) is allowed in a switch expression?

Thanks for help.
 
Marshal
Posts: 66237
250
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suggest you start by evaluating the four cases; rather than writing case i: write case 4: or similar. Remember that the default: case is only chosen if none of the other cases is picked. Youi may find the bytecode useful: javap -c Whizz
 
Ranch Hand
Posts: 73
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mike Gualeni wrote:I have the following code:



Why the switch expression take case y? For me switch( x+y ) is 2, also it should print default. x and y are both final! And I thought (x+y) is allowed in a switch expression?

Thanks for help.

because the switch evaluates the x+y =2 then  compiler search for a related value, case y: has the value 2, so it jumps to case y but not the default reason is that switch has the ability to create a jump statement  whatever the cases you have, so answer is case y exicuited which has the value 2 related to case x+y
 
Mike Gualeni
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello

You're right. But this behavior I didn't read in no book!! But I think it's an important behavior.

If I change the values in the code vice versa final int x = 2; and final int y = 0; the output is:

A
B
default
C



because no break stops from falling down! And now the program choose case x: {System.out.println("A");}!! Strange behavior!!??
 
Why fit in when you were born to stand out? - Seuss. Tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!