• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about a Java question on a quiz I had  RSS feed

 
Jack Odinson
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So here is the question:

What would be the value of x after the following statements were executed?


Now I know the answer is 20 because I already took this quiz. My question is why? To my understanding I thought it would be 60 because of that last x*=3, but I'm just new to Java and don't entirely understand how the break and default fields work. I'm guessing the break stopped the statement since it has a ; but what is the point of default being there at all? Would a real code look like this or was it just thrown in the quiz question to throw me off?
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

No, real-world code would not be like that; the question just checks if you know how a switch statement works. You need a to put the keyword "break" at the end of a case block, otherwise execution will "fall  through and keep executing statements until you get to a break or you reach the end of the switch statement. That's why you get 20, not 60.
 
chamini prashakthi
Ranch Hand
Posts: 127
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no break statement.So first two executions occur here.

see following example.



here if foo is 0 , and will occur.
if foo is 1 and will occur.

so according to your question at the  first time x is 10.
then x is 25(execute )
then goes to.(because there is no break statement.then breaks here.
then answer is 20 (20-5)
Hope you got it!
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chamini prashakthi wrote:then answer is 20 (20-5)

You mean 25-5 = 20.
 
chamini prashakthi
Ranch Hand
Posts: 127
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh I missed.
it is 25-5=20
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What a good explanation, and along with the about the − sign, it merits a cow.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!