Home > Blockchain >  Scope of variables inside switch case statement in Java
Scope of variables inside switch case statement in Java

Time:01-06

I have the following code, my question is how can we persist the value of String A and B and use it in another case statement for comparing it.

String A = null;
String B = null;
Switch(key) {

   case “ABC”:
     A = “Hello”;
   break;
   case “XYZ”:
     B = “Hi”;
    break;
   case “compare”:
      A.equals(B); //Exception here as A and B are nulls.

Can anyone please guide me here as I’am really confused with the variable scope in switch case.

CodePudding user response:

The problem you are having is not related to the lifetime of the switch-case block or objects A and B. The String.equals() method throws a NullPointerException because you are assigning null values to objects A and B. If you want String objects to not get this error, initialize String objects to empty; for example String city = ""

public class HelloWorld
{
     public static void main(String []args)
     {
        String A = "";
        String B = "";
        String key = "compare";

        switch(key) 
        {
           case "ABC":
                A = "Hello";
                break;

           case "XYZ":
                B = "Hi";
                break;

           case "compare":
               if(A.equals(B))
                    System.out.println("true");
               else
                    System.out.println("false");
               break;
        }
        System.out.println(A);
        System.out.println(B);
    }
}

Additionally, your code editor is currently generating non-ASCII compliant text; the character you are using is invalid. Additionally, the switch keyword is written in lowercase.

CodePudding user response:

In your Switch-case statement you're comparing whatever is in key with the different cases, proceeding as follows:

  • is key equals to "ABC"? then A = "Hello"

  • is key equals to "XYZ"? then B = "Hi"

  • is key equals to "compare"? then compare A and B (which so far, are nulls)

Note, that if your code reaches the last case statement, means it skipped the other two, so A and B are nulls. Also, your code is assuming that key will have the next possible values: "ABC", "XYZ", or "compare", and if key does not have any of those values, your program will do nothing.

CodePudding user response:

Can anyone please guide me here as I am really confused with the variable scope in switch case.

The following are for a classic (Java 11 or earlier) switch statement.

  • Variables declared outside of the switch block are "in scope" inside the switch block.

  • Variables declared inside of the switch block are "in scope" inside the switch block. The scope starts at the point of the declaration and continues for the remainder of the switch block.

    Thus, a variable declared in one case will be in scope in following cases if the cases "drop through".

So, in your example, A and B are in scope before the switch, within the switch, and after it. But if they were declared within the switch they wouldn't be in scope after the switch.


The initialization of variables declared within a switch is governed by the normal rules. Explicit initializers are executed when the declaration is encountered, and variables must be definitely initialized before they are used.

switch (num) {
case 1: 
    int a = 1;
    // No break ...
case 2:
    System.out.println(a); // ERROR - not definitely initialized.
}
System.out.println(a);     // ERROR - not in scope.

In the above, a is in scope in the second switch case, but will not be initialized in all paths to its println statement.


As @Sercan notes, the reason for your NPE is nothing to do with scopes, or definite initialization. The actual problem is that the execution path that your code takes in the "compare" case does not assign a non-null value to A. (Or B either. But the non-nullness of B should not cause an NPE.)

  •  Tags:  
  • Related