Java Enum - enumeration with examples in Java
Source:
FreeCodeCamp An enumeration (enumeration or
enum for short) in Java is a special data type that contains a set of predefined constants. Typically, enum is used when working with values that do not need to be changed, such as days of the week, seasons, colors, and so on.
In this article, we will see how to create
an enum and how to assign its value to other variables. We will also learn how to use
an enum in a
switch statement or loop through its values.
How to create an Enum in Java
To create
an enum we use the enum keyword .
This is similar to how you create a class using the class keyword . Here's an example:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
In this code, we have created
an enum called
Colors . You may notice that all
enum values here are written in upper case - but this is just a general convention. If the values are written in lowercase, there will be no error. Each value in
enum is separated by a comma. Next we're going to create a new variable and assign it one of the values of our
enum .
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red);
}
}
This is similar to initializing any other variable. Here in the code we have initialized
the Colors variable and assigned it one of
the enum values using the dot syntax:
Colors red = Colors.RED; . Note that we can create our enum inside the
Main class and the code will still work:
public class Main {
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red);
}
}
If we want to get the ordinal number of any of the values, we will have to use the
ordinal() method . Here's another example:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red.ordinal());
}
}
red.ordinal() from the above code returns 0.
How to use Enum in a Switch statement
Now we will learn how we can use
enum in a
switch statement :
public class Main {
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public static void main(String[] args) {
Colors myColor = Colors.YELLOW;
switch(myColor) {
case RED:
System.out.println("The color is red");
break;
case BLUE:
System.out.println("The color is blue");
break;
case YELLOW:
System.out.println("The color is yellow");
break;
case GREEN:
System.out.println("The color is green");
break;
}
}
}
This is a very simple example of how we can use
enum in a
switch statement . We can output
"The color is yellow" to the console because this is the only case that matches the condition of the
switch statement .
How to loop through enum values
For enum, Java has a
values() method that returns an array of
enum values . We're going to use a
foreach loop to iterate through and print the values of our
enum . You can do it like this:
enum Colors {
RED,
BLUE,
YELLOW,
GREEN
}
public class Main {
public static void main(String[] args) {
for (Colors allColors : Colors.values()) {
System.out.println(allColors);
}
}
}
Conclusion
In this article, we learned what
an enum is in Java, how to create one, and how to assign its values to other variables. We also saw how to use the
enum type with a
switch statement , and how we can loop through
enum values . Happy coding!
While Loop in Java: Syntax and Uses
Source:
Dev.to Today we will understand the concept and syntax of a
while loop in Java and also look at how to use this loop to iterate through an array.
While Loop Concept
The while loop is one of the basic loop types in Java and can be used for several purposes in a program. Like the
for loop , the
while loop can be used to perform operations based on a condition. In a
while loop , the counter does not always turn on. The number of iterations of the
while loop depends on how often the loop condition returns
true . Initialization in a
while loop can be optional in most cases, unlike in a
for loop . Sometimes the
while loop is not always executed in a loop. Let's take a concrete example:
System.out.println("You Input a wrong number");
int i = input.nextInt();
while(i==1||i==2||i==3||i==4){
System.out.println("inside the while loop block");
}
System.out.println("outside the while loop block")
Here the code uses a
while loop to validate user input based on some conditions, so it repeats only once.
While loop syntax
while(condition){
}
The while loop condition takes an argument that returns the boolean value
true or
false . When
true the code in the
while loop is executed, but when
false the loop ends.
Flow of each while loop
The while loop has an accepted flow: initialization > condition > statements execution. The first stage is the initialization stage. It can be accomplished by declaring a variable and also initializing it. The second stage is the condition stage, this stage must return
true or
false . If it returns
true , the statement in the
while loop is executed, but if it returns
false , the loop ends.
Using a while loop as a counter
Like the
for loop , the
while loop can also be used as a counter. The program below uses a
while loop to iterate from 2 to 20. This is to print even numbers.
int j = 2;
while(j <=20){
System.out.println(j);
j+=2;
}
As you can see, in the program,
j is initialized to 2, the condition is tested if
j is less than or equal to 20. If it returns
true , the statement is executed, but if it returns
false , the
while loop ends.
A while loop can be used to iterate through an array
int[] age = {20, 30, 40, 40, 90};
int i = 0;
while (i < age.length)
{
System.out.println(age[i]);
i++;
}
In this code, we have an age array and a
while loop is used to iterate through the array and print out each element in the array. To check the total number of elements in an array,
age.length is used , in the above program
i serves as an index.
Break statement in a while loop
The break statement can also be used in a
while loop , just like a
for loop :
int i = 1;
while (true)
{
System.out.println(i);
if (i == 20)
{
break;
}
i++;
}
In the above program, the
break statement was used to stop the program from executing indefinitely.
While(true) means that the program will always return
true .
The while loop can be used to validate user input
System.out.println("Select an option\n"+
"1.Add Users\n"+
"2.Delete Users");
int x = input.nextInt();
while(x==1||x==2){
}
System.out.println("You Input a wrong number");
In the above program, a
while loop is used to check the user's input and ensure that the user selects either 1 or 2. If the user selects a different number, then
System.out.println("You Input a wrong number"); .
Conditional statement with while loop
int i = 0;
while(i<10){
i++;
if(i==5){
continue;
} System.out.println(i);
}
The conditional statement can also be used in a
while loop to skip a specific iteration. In the above program,
if statement is used to check
i==5 , if it returns
true then that particular iteration will be skipped.
while loop design
Let's create a guessing game using a
while loop .
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
static boolean hasWon;
static int count;
static int guess;
public static void main (String[] args)
{
System.out.println("Welcome to guess world");
System.out.println("Do you want to start the game? ");
System.out.println("1.Yes\n" +
"2.No");
int option= input.nextInt();
int guessNumber = (int) Math.floor(Math.random() * 10 + 1);
if (!( option == 2 ))
{
System.out.println("Welcome, choose a guess between 1 and 10\n" +
"you have only ten trials");
while (count <= 10)
{
int userGuess = input.nextInt();
if (userGuess == guessNumber)
{
hasWon = true;
System.out.println("Congratulation, you guessed right at " + count + " count");
count++;
break;
}
else if (userGuess < guessNumber)
{
hasWon = false;
System.out.println("Oops, you guessed a lower number, try an higher one");
count++;
}
else if (userGuess > guessNumber)
{
System.out.println("Oops, you guessed an high number, try an lower one");
hasWon = false;
}
}
if (hasWon == false)
{
System.out.println("You trials exceeds 10");
}
}
}
}
In this program, we create a number guessing game using a
while loop . The player has only 10 attempts. Once the number of times he has played the game exceeds 10, the game ends. If the player guesses the correct number, a congratulations message is displayed on the console.
Conclusion
The while loop may seem complicated, but it's not that difficult to master. It is also the second most commonly used loop in Java and can be used for a variety of purposes.
GO TO FULL VERSION