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
Aleks Dahlberg
19,103 PointsWould there be any reason not to use a switch statement instead of an array?
```switch (randomNumber) { case 0: fact = "Ants don't actually exist!"; break; case 1: fact = "Ants do actually exist!"; break; case 2: fact = "Ants may or may not exist!"; break; }
1 Answer
Felipe Laso-Marsetti
3,158 PointsA switch statement and an array are two completely different things. A switch is a conditional, used to check whether a variable is of a certain type and perform any actions as needed on each scenario in the switch statement. Switch is usually used to replace "if" statements that have a lot of potential paths. It saves a lot of code and is much cleaner to read.
An array is a data structure, its function is to store data along with providing some additional functionality should you use variants of it like an ArrayList. Using a switch statement to store create or get strings is possible, but it's quite a bad practice as you are creating a new string every single time you call it.
By using an array you have a single instance of every string in memory and if you need to access them they are already created (only once) for you to use. Using a switch will create it every time you access it. Also, let's assume you wanted to perform operations on the data, like re-shuffle the array, get the amount of items inside of it so you can do something with that value, iterate over the items of the array to make them all uppercase, etc.
While the performance impact of such a tiny switch statement versus an array in this scenario is virtually non-existent, as you progress in your development career and build more complex, robust systems that require performance to be at its best, it's little things like this that can go long ways towards helping you out.
:)