Java - What is the output: local variable vs instance variable

Question

What is the output of the following code?


public class Main {
  static int sum;
  static int n1 = 10; 

  public static void main(String[] args) {
    int n1 = 20; 
    int n2 = n1;
    System.out.println(n1);
    System.out.println(n2);
  }

  int n3 = n1; 
  
}


Click to view the answer

20
20

What is the value of n3?



Click to view the answer

10

Note

The scope of an instance variable and a class variable is the entire body of the class.

n1 and n3 can be referred to with its simple name anywhere in the class.

A local variable with the same name as a class field hides the name of the class field.

The local variable takes precedence in case of duplicate name.