Ask Question

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++;

}

}

A. f2. i is 1 f2. s is 1

B. f2. i is 1 f2. s is 2

C. f2. i is 2 f2. s is 2

D. f2. i is 2 f2. s is 1

+1
Answers (1)
  1. 17 November, 13:32
    0
    B. f2. i is 1 f2. s is 2

    Explanation:

    In Java there are two type of variables, first is static variables and second is instance variable. static variable class variable which means you can have only one variable for all instance of that class. But instance variable will only for instance/object of that class.

    For this code example, i is and instance variable, for every instance of class Foo, there will be separate i variable. but s is a static variable and that will be associated with class.

    So in this program the first instance incremented the s variable and changed its value to 1 as int's default value is 0 in the constructor. So for second instance, the s value changed to 2 that's why it prints f2. s as 2 and as we know i is instance variable and every instance of foo class have there own copy of i variable so it's value will remain same for every instance.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “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 ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers