Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
Scope of variables inside switch case statement in Java

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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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 = "";. If you want objects A or B to be compared after a value is assigned and the program to be redirected to another control, you can review the example below. If there is a different problem, try to explain the problem by drawing a flowchart.

public class HelloWorld
{
    public static boolean Compare(String s1, String s2)
    {
        if(s1.equals(s2))
            return true;
        return false;
    }
    
     public static void main(String []args)
     {
        String A = "", B = "Hello", key = "ABC";

        switch(key) 
        {
           case "ABC": /* assignment and comparison */
                A = "Hello";
                
                if(Compare(A, B))
                { /* program can be directed according to the situation. */}
                else
                { /* program can be directed according to the situation. */}
                break;
           case "XYZ": /* assignment and comparison */
                B = "Hi";
                
                if(Compare(A, B))
                { /* program can be directed according to the situation. */}
                else
                { /* program can be directed according to the situation. */}
                break;
           case "compare": /* just comparison */
                if(Compare(A, B))
                { /* program can be directed according to the situation. */}
                else
                { /* program can be directed according to the situation. */}
                break; 
        }
        System.out.printf("A: %s B: %s", A, B);
    }
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!