Java - What is the output: static field vs instance field

Question

What is the output of the following code.

public class Main {
     static int num1 = 10;
     int num2 = 10;
     
     public static void main(String args[]){
          Main ex1 = new Main();
          Main ex2 = new Main();
          
          ex1.num1 = 20;
          ex2.num1 = 30;
          System.out.println("ex1.num1=" + ex1.num1);
          System.out.println("ex2.num1=" + ex2.num1);
          ex1.num2 = 30;
          ex2.num2 = 50;
          System.out.println("ex1.num2=" + ex1.num2);
          System.out.println("ex2.num2=" + ex2.num2);
     }
}


Click to view the answer

ex1.num1=30
ex2.num1=30
ex1.num2=30
ex2.num2=50

Demo

public class Main {
     static int num1 = 10;
     int num2 = 10;
     //  w ww  . j  a  va  2  s. co  m
     public static void main(String args[]){
          Main ex1 = new Main();
          Main ex2 = new Main();
          
          ex1.num1 = 20;
          ex2.num1 = 30;
          System.out.println("ex1.num1=" + ex1.num1);
          System.out.println("ex2.num1=" + ex2.num1);
          ex1.num2 = 30;
          ex2.num2 = 50;
          System.out.println("ex1.num2=" + ex1.num2);
          System.out.println("ex2.num2=" + ex2.num2);
     }
}

Note

static field has only one copy while instance field has copy in each object.

Related Topic