Member-only story

Java Programming Language Tutorial: Switch Statement

Jesse L
3 min readMar 2, 2022

--

Hi everyone, welcome back. In this tutorial, we will be going over the switch statement. The switch statement can be used to decide which block of code to execute which is good for tasks that include choices or decision making. We will also be using the break and the default keywords in this tutorial as well. With this introduction out of the way, let’s get into in.

Switch Statement Example

Let’s look at an example of a switch statement and explain what’s happening. Take a look at the example below:

int number = 1;
switch (number){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
}
Output:
One

As we can see, we have set our number variable to 1. We then set our switch statement to check against the number variable and if it matches any of the cases given, it will execute the block of code within the case. So, in this instance, we set our number variable to 1 and the code within “case 1:” got executed and that can be verified with the output.

Default Keyword in the Switch Statement

Switch statements can have as many cases as you want. But now let’s say that we want to have a block of code that gets executed if…

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet