OCAJP – How to use a switch statement?

This post is about the OCAJP exam objective “Use a switch statement“. You will be mainly tested in the exam about allowed data type variables for switch and Question contains switch statement with compile time errors, you need to correct those errors by selecting the given options.

Here, We would explain each and every important points regarding switch statement. If you have any questions regarding this article, please write it in the comments section.

TRY NOW : 25 Free OCAJP Mock Exam Questions

How to use switch statement?

Here are the few important points about switch statement in Java.

  • A switch statement is a complex decision-making structure in which a single value is evaluated and flow is redirected to the first matching branch known as a case statement.
  • If no such case statement is found that matches the value, an optional default statement will be called.
  • If no such default option is available, the entire switch statement will be skipped.
    • if and if-else statements can used to support both simple and complex decision logic.
    • In many cases switch statement provides a cleaner way to handle complex decision logic.
    • Let’s see an example to understand difference between if-else and switch statements.

Example :

int x=3;
if(x==1){
    System.out.println("x equals 1");
} else if(x==2) {
    System.out.println("x equals 2");
}else if(x==3) {
    System.out.println("x equals 3");
}else 
{
    System.out.println("Don't know x value");
}
  • The same functionality using switch statement.

Example :

int x=3;
switch(x){
   case 1 :
      System.out.println("x equals 1");
      break;
   case 2 :
      System.out.println("x equals 2");
      break;
   case 3 :
      System.out.println("x equals 3");
      break;
   default :
      System.out.println("Don't know x value");
 }
  • The main difference between if-else and switch is ” if-else statement checks each and every condition but switch directly executes the particular condition.
  • The general form of switch statement is :
switch(expression){
   case constant1 : code block
   case constant2 : code block
   case constant3 : code block
   .
   .
   .
   default : code block
}
  • It may contain zero or more case branches.
  • Curly braces are mandatory even though there are no statements in the switch.
  • No need to write case branches in a particular order. You can write in any order.
  • case branch syntax is important because some may test with invalid syntax.
  • A switch statement should contain only one default branch.
  • You can write default branch at any place within switch statement.

Allowed data types for switch parameter value

  • You can’t use the switch statement to compare all types of values, such as all types of objects and primitives.
  • There are limitations on the types of arguments that a switch statement can accept.
  • A switch statement accepts arguments of type char, byte, short, int, and String(starting from Java version 7).
  • It also accepts arguments and expressions of types enum, Character, Byte, Integer, and Short, but because these aren’t on the OCAJP exam objectives, We won’t cover them in these article.
  • The switch statement doesn’t accept arguments of type long, float, double,boolean or any object besides String.
  • The following examples doesn’t compile because those data types are not allowed by the switch.

Examples :

long x = 1;
switch (x) {//compile time error at this line because long is not allowed.

}

 

float x = 2.0f;
switch (x) {//compile time error at this line because float is not allowed.

}

 

double  x = 5.0;
switch (x) {//compile time error at this line because double is not allowed.

}

 

boolean  x = true;
switch (x) {//compile time error at this line because boolean is not allowed.

}

 

  • Apart from passing a variable to a switch statement, you can also pass an expression to the switch statement as long as it returns one of the allowed types.
  • The following code is valid:

Example :

 
byte a = 3, x = 6;
switch (a+x) {
// ..code
}

Compile-time Constant Values

  • The values in each case label must be compile-time constant values of the same data type as the switch value
  • This means you can use only literals, enum constants, or final constant variables of the same data type as case label value.
  • By final constant, we mean that the variable must be marked with the final modifier and initialized with a literal value in the same expression in which it is declared.
  • The value of a case label must be a compile-time constant value. That is, the value should be known at the time of code compilation
  • Remember switch parameter variable value need not be compile-time constant. But case label must be a compile-time constant value.

Example :

int a = 5, b = 12, c = 4;
switch (a) {
    case b + c: // gives compile time error because it is evaluated at run time. so it is not compile time constant
    System.out.println(b + c);
    break;
    case 2 * 7:
	System.out.println("14");
   }
  • You can use variables in an expression if they’re marked final because the value of final variables can’t change once they’re initialized:

Example :

final int a = 3;
final int b = 4;
final int c = 5;
switch (a) {
	case b + c: // doesn't gives compile time error because it is evaluated
	// at compile time because all are final variables. so it is compile time constant
	System.out.println(b + c);
	break;
}

  • You may be surprised to learn that if you don’t assign a value to a final variable with its declaration, it isn’t considered a compile-time constant:

Example :

final int a = 10;
final int b = 20;
final int c;
c = 30;
switch (a) {
	case b + c: //Line 1
	System.out.println(b + c);
	break;
  }
  • Line1 gives compile time error because it is evaluated at run time.
  • Because c is a final variable but it is initialized in the next line.So it is evaluated at run time. so the whole expression evaluated at run time.
  • So it is not compile time constant. It gives compile time error.

Case values should assignable to the passed to the switch statement

  • Examine the following code, in which the type of argument passed to the switch statement is byte and the case label value is of the type float. Such code won’t compile:

Example :

byte b = 5;
switch (b) {
  case 4.5: 
  System.out.println(1); 
  break;
}
  • Null is not allowed as a case label.
  • Code that tries to compare the variable passed to the switch statement with null won’t compile, as demonstrated in the following code:

Example :

String name = "OCA";
switch (name) {
case "OCA": 
System.out.println("OCAJP");
break;
case null: 
System.out.println("null");
}
  • In switch every case label value should be unique. If more than one case label value is same , you will get compile time error.
  • See the following code demonstrated this rule. This code won’t compile.

Example :

int x = 5;
switch(x){
    case 1 :
	System.out.println("Hi");
	break;
    case 1 :
	System.out.println("Hello");
 }
		

Fall through in switch block

  • Once case constant is matched, JVM will executes the associated case branch and subsequent code blocks , if there is no break statement after first matched case.
  • See the following code demonstrated this rule.

Example :

String color = "green";
switch (color) {
    case "red":
	System.out.println("red");
    case "green":
	System.out.println("green");
    case "blue":
	System.out.println("blue");
  }

It outputs like :

green
blue

Conclusion

For OCAJP exam you need to remember all these points about switch statement.You will mainly tested about allowed data types to switch parameter and compile time constant concept, fall through concepts.

If you are interested in practicing more questions, consider our 650+ mock exam questions for OCAJP certification exam.

If you are looking for any support or help on preparing for OCAJP certification exam, please contact our support or call us.

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

1 thought on “OCAJP – How to use a switch statement?”

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top