Learn Pain Less

HomeOur TeamContact
Java
Switch statement in java
Pawneshwer Gupta
Pawneshwer Gupta
February 18, 2015
1 min
Switch statement in java

Switch statement is same as else if statement. In switch statement only 1 condition will be true and that will be executed. Switch is easier than else if statement. In else if statement we wrote condition in every block like

If (a == 1){
}
else if (b == 1) {
}

And so on. But in switch statement we use cases.

For example

switch (condition){
case 1:
// Do your work here
break;
case 2:
// Do your work here
break;
default:
// If all cases are false then this block will b3 executed.
break;
}

This is syntax of switch statement. And you can see we have to write condition just one time on top, and after that we will use cases. Case will be any integer value which is result of condition written in switch statement.

For example, if we wrote condition

int a = 3;
switch(a){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
}

When we execute this program then we will get three as output. We can’t use String value as condition in switch statement. Switches based on integers can be optimized to very efficient code. Switches based on other data type can only be compiled to a series of if() statements.  

For that reason, C & C++ only allow switches on integer types, since it was pointless with other types.  

The designers of C# decided that the style was important, even if there was no advantage.  

The designers of Java apparently thought like the designers of C. as soon as you start switching on non-primitives you need to start thinking about “equals” versus ”==“. Firstly, comparing two strings can be a fairly lengthy procedure, adding to the performance problems that are mentioned above. Secondly if there is switching on strings there will be demand for switching on strings ignoring case, switching on strings considering/ignoring locale, switching on strings based on regex… I would approve of a decision that saved a lot of time for the language developers at the cost of a small amount of time for programmers.

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Tags

startswitch

Share


Pawneshwer Gupta

Pawneshwer Gupta

Software Developer

Pawneshwer Gupta works as a software engineer who is enthusiastic in creating efficient and innovative software solutions.

Expertise

Python
Flutter
Laravel
NodeJS

Social Media

Related Posts

Working with Files, Folders java
Working with Files, Folders java
March 25, 2015
1 min
Learn Pain Less  © 2024, All Rights Reserved.
Crafted with by Prolong Services

Quick Links

Advertise with usAbout UsContact Us

Social Media