This week's book giveaway is in the JavaScript forum.We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Question from Dan Chisholm's mock exam

harsha puttaswamy
Greenhorn
Posts: 24
class JMM106 {
public static void main(String args[]) {
int x = -5; int success = 0;
do {
switch(x) {
case 0: System.out.print("0"); x += 5; break;
case 1: System.out.print("1"); x += 3; break;
case 2: System.out.print("2"); x += 1; break;
case 3: System.out.print("3"); success++; break;
case 4: System.out.print("4"); x -= 1; break;
case 5: System.out.print("5"); x -= 4; break;
case 6: System.out.print("6"); x -= 5; break;
default: x += x < 0 ? 2 : -2;
}
} while ((x != 3) || (success < 2));
}}

Can someone please explain to me what exactly happens in the default section ? For some reason I am thinking x should be set to 2 in the first step because x will be less than 10. But, it turns out that x evaluates to -3 in the first step.

Thank you,
Harsha.

sethu chiyan
Greenhorn
Posts: 10
Hi Harsha,

// code here

default: x += x < 0 ? 2 : -2;// Evaluation explained below

In First time Loop

Current x value is -5 as v know

x+= (x<0) ? 2 : -2
x += (-5<0) ? 2: -2
x+=2;
so x = -3 in 1rst iteration

In second time Loop

Current x value is -3 as v know

x+= (x<0) ? 2 : -2
x += (-3<0) ? 2: -2
x+=2;
so x = -1 in 2nd iteration

In Third time Loop

Current x value is -1 as v know

x+= (x<0) ? 2 : -2
x += (-1<0) ? 2: -2
x+=2;
so x = 1 in 2nd iteration

Then as v know it goes like this
System.out.print("1");
System.out.print("4");
System.out.print("3");
System.out.print("3");

So the O/P is 1433.

Hope this will help u.

Pl do contact me if u r still in trouble,

with regards,
Chiyan.

harsha puttaswamy
Greenhorn
Posts: 24
Thank you Chiyan, that makes sense !!

Harsha.