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

Why is the answer "" ?

I answered randomly on a question like this:

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"; }


And I answered A. "" . Well it is right, but I don't understand the reason behind the answer. Can you help me?

I thought the answer should be Blue or Red

1 Answer

String answer = "";
int code = 2;

if (code == 0) {
       answer = "Blue"; 
} else if  (code == 1) { 
       answer = "Red"; 
}

Reason:

If code is equal to 0. It's not. Code is 2. So the answer is not going to be blue. So we move to the else statement. Since else is an else if. We apply another condition to check. Is code equal to 1. Nope it's not. Code is not equal to 1 either. So answer does not equal red.

Looking at the code, based on what we have. String has not been set yet. Since code is not equal to 0. We never entered the code bock to set answer. We skipped it. Then, code is also not equal to 1. So we will skip that code block too. So we never really set answer yet have we?

In the real world, you would handle this with another else statement. So if the first condition and the second condition were false. We would do something in last else statement that made sense. But this code is just trying to make the point that based on only what you can see here. What will answer be. And well, answer would still be "".

Does that help clear it up for you? Let me know if not.

Thanks!