Variable not visible outside of the block it is declared in

I’m now taking online course GTx CS1331xI on edX which is introduction to JAVA.
I have a question about debug. Please see my code below:

public class Bad2 {
    public static void main(String[] args) {
        int a = 1331;
        int b = 0;
        System.out.println("Welcome to \nCS 1331!");
        if (b != 0) {
          int c = a / b;
        } else {
          int c = 0;
        }
        System.out.println("c is equal to: " + c);
    }
}

When I run the code, the system always show:

Bad2.java:11: error: cannot find symbol
        System.out.println("c is equal to: " + c);
                                               ^
  symbol:   variable c
  location: class Bad2
1 error

I tried to change type c to double or float which doesn’t work.

>Solution :

Variables only exist in the scope they’re declared. Broadly speaking (and glossing over a lot of details), that roughly means they exist until the next closing brace.

if (b != 0) {
  int c = a / b;
} else {
  int c = 0;
}
System.out.println("c is equal to: " + c);

This creates two different variables called c. Both of them exist inside their respective branch and then are gone by the end of the if statement. Outside the if, there’s no c variable. If you want c to persist outside the if, you need to declare it outside.

int c;
if (b != 0) {
  c = a / b;
} else {
  c = 0;
}
System.out.println("c is equal to: " + c);

Leave a Reply