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); } }
ex1.num1=30 ex2.num1=30 ex1.num2=30 ex2.num2=50
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); } }
static field has only one copy while instance field has copy in each object.