What is the output of the second println statement in the main method? public class Foo { int i; static int s; public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); } public Foo() { i++; s++;

Respuesta :

Answer:

The second print statement will print:

f2.i is 1 f2.s is 2

Explanation:

Initially when the execution start. i and s are both 0. i declared as a variable while s is a static variable which value stays once it is re-defined.

When f1 call i and s; their value is both 1 based on the increment statement in the constructor.

For the second print statement:

When f2 call i; it is re-initialized to 1. When f2 call s; it has initial value of 1 and is incremented to 2 which is printed. s hold the initial value of 1 because of the static keyword.