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

Java

switch() OR if()

When is an appropriate time to use a switch statement instead of an if statement? Can you please provide some examples?

Diego

1 Answer

Hi Diego,

I'm not a Java guy, but the concept is the same across languages.

You want to use Switch statements any time you're checking one variable against a bunch of possible values. For example, let's say you were checking to see what option someone chose from a drop-down. Rather than using an if statement to see if they chose the first option, else if they chose the second option, else if they chose the third option, etc., you can use a switch statement.

I'm not sure if Java uses enumerations, or enums, but they are a great use case for switch statements: there's a defined number of choices, and you can check all of them in your switch statement.

if and if-else statements should be used for simpler checks.

Hope this helps!

Cheers :beers:

-Greg