Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to define a switch statement in JShell in Java 9?
JShell is based on the REPL (Read-Evaluate-Print-Loop) introduced in Java 9. This tool can be used to execute simple statements, evaluate it, and prints the result.
A switch statement can test multiple conditions just like an else clause and handles the default possibility. The default clause can be executed when none of the cases match, and a break statement can be used to break out of switch after a successful match.
In the below code snippet, we can define the switch statement in JShell.
Snippet-1
jshell> int i = 10;
i ==> 10
jshell> switch(i) {
...> case 1 : System.out.println("1");
...> case 10 : System.out.println("10");
...> default : System.out.println("default");
...> }
10
default
jshell> int i = 1;
i ==> 1
jshell> switch(i) {
...> case 1 : System.out.println("1");
...> case 10 : System.out.println("10");
...> default : System.out.println("default");
...> }
1
10
default
In the below code snippet, we can define a switch statement with a break in JShell.
Snippet-2
jshell> switch(i) {
...> case 1 : System.out.println("1"); break;
...> case 10 : System.out.println("10"); break;
...> default : System.out.println("default"); break;
...> }
1Advertisements