Last active
December 15, 2015 04:58
-
-
Save raineorshine/5205114 to your computer and use it in GitHub Desktop.
Enums vs Strings in Java (Beginner/Intermediate)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Enums are mostly for internal purposes. Think of it as a way to make your job as a developer | |
easier when you have a few predefined values and you don't want to have to remember obscure codes. | |
Let's say you have three different states in your program: 0 means INACTIVE, 1 means PENDING, and 2 | |
means ACTIVE. | |
*/ | |
// You could keep track of the state with an integer like so: | |
int programState = 1; // PENDING | |
// But then you have to always remember what those codes mean. This is a bad idea! You want your | |
// code to be simple and clear. Better to create an enum in this case: | |
enum State { | |
INACTIVE, | |
PENDING, | |
ACTIVE | |
} | |
// Then you can declare your state as follows | |
State programState = PENDING; | |
// Notice how the type is 'State' instead of 'int'. Then the value is one of the enumerated values | |
// themselves. Much clearer! | |
// However: There's not a good way to go back and forth between enums and strings. If you want to | |
// display something to the user, you're better off keeping a list of strings that you can index | |
// into: | |
String[] months = { "January", "February", ... }; | |
// Then you can print out a month from a given index: | |
int mIndex = scanner.nextInt(); | |
System.out.println(months[mIndex]); | |
/* | |
Enums are good for making internal codes such as states, statuses, and flags easier to understand | |
in your code. Strings are good when you are interacting with the user, either reading values in | |
or printing them out. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment