Our Best Offer Ever!! Summer Special - Get 3 Courses at 24,999/- Only. Read more
Hire Talent (HR):+91-9791 444 054

General

Switch Statement Java

Switch Statement Java

Switch Statement Java

To branch, a statement “switch” keyword is used. Based on switch conditional expression, it executes the relevant part of the code. The conditional expression can be any type int, short, string, byte…etc

Syntax

Switch (conditional expression)
{
Case value 1
break
//optional
Case value 2
break
//optional
Case value 2
break
//optional
default:
Statements
}

Example:

Public class switchExample {
public static void main(String[] args)
{
int trafficColor = 3;
String colors;
// switch statement with int data type
switch (trafficColor) {
case 1:
colors = "Red";
break;
case 2:
colors = "Yellow";
break;
case 3:
colors = "Green";
break;
default:
colors = "White";
break;
}
System.out.println(colors);
}
}

Important point:

  • Duplicate conditional expression. Cases with same expression not allowed
  • Data type should be consistent
  • In order to come out we can add break statement
  • Break is optional
  • Default is optional which can keep in switch anywhere

Click Here-> Get Java Training with Real-time Projects

Besant Technologies WhatsApp