Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (retired 2014) Learning the Language Conditionals: Writing an if Statement

david Flores
david Flores
748 Points

Find Answer

What will be the value of the answer variable after the following code is executed? String answer = “”; int code = 2; if (code == 0) { answer = “Blue”; } else if (code == 1) { answer = “Red”; }

//possible answers a. " " b. "Blue" c. "Red" d. None of The Above

I chose "d" because the code is setting the "int code = 2. From what I understood this line of text is setting the code variable to 2, but according to the lesson I was wrong. Cold some one please explain?

5 Answers

String answer = “”; 
int code = 2; 
if (code == 0) { answer = Blue; } 
else if (code == 1) { answer = Red; }
  • The first line initialises the String variable answer to an empty string.
  • Next it initialises the value of code to 2
  • Since neither of the conditions match i.e. code is neither equal to 0 or 1 thus, the code in the if statements will never be executed and no answer will not be set to Blue or Red
  • So if we print out the value of String it will still remain as empty string i.e. " "

Hope that helps.

Jeremy Stenseth
Jeremy Stenseth
16,916 Points

answer = " "; int code = 2; if code is == to 0 then answer is changed to "blue" but its not so answer is still " ". then it checks if code is == 1 if it is answer is changed to ="Red" but its not so answer is still = " "

david Flores
david Flores
748 Points

Oh ok I think I got it. Since the beginning of the code it sets the int variable to 2 the the only logical answer would be "" because there is no 2 option.

Jeremy Stenseth
Jeremy Stenseth
16,916 Points

Correct. Answer is set to " " and answer will always be " " unless a condition is met to change it.

david Flores
david Flores
748 Points

thank you everyone for you help

I could use some help. I'm still a little lost with this... what exactly is the int code = 2; doing? Since there is no randomGenerator like in the lesson I'm not clear on what is happening here.