What's the output from the following statements?public class Foo { static int i = 0; static int j = 0; public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); } k = i + j; System.out.println("k is " + k); System.out.println("j is " + j); }}
Question
What's the output from the following statements?public class Foo { static int i = 0; static int j = 0; public static void main(String[] args) { int i = 2; int k = 3; { int j = 3; System.out.println("i + j is " + i + j); } k = i + j; System.out.println("k is " + k); System.out.println("j is " + j); }}
Solution
The output of the given Java code would be:
i + j is 23
k is 2
j is 0
Here's the step by step explanation:
-
The code first declares two static variables
iandjand initializes them to0. -
In the
mainmethod, it declares local variablesiandkand assigns them the values2and3respectively. -
Inside the inner block, it declares another local variable
jand assigns it the value3. -
It then prints "i + j is " followed by the value of
iandjwhich are2and3respectively. However, since it's a string concatenation, it doesn't addiandjbut appendsjtoi, resulting in
Similar Questions
What is the output of the following code :class MyClass {public static void main(String[] args) {int i=1,j=1;for (;i<3;i++){for(;j<4;j++);j++;System.out.print(i + j+" ");}}
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++; } } Group of answer choicesf2.i is 1 f2.s is 1f2.i is 1 f2.s is 2f2.i is 2 f2.s is 2f2.i is 2 f2.s is 1
e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}
What is the output of the following code snippet?class MyClass { static int count = 0; public MyClass() { count++; } public static int getCount() { return count; }}public class Main { public static void main(String[] args) { MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); System.out.println(MyClass.getCount()); }}Question 3Answera.0b.1c.2d.Compilation error
What is the output of the following code?public class Test { public static void main(String args[]) { int x = 10; System.out.print(x + " "); } static { int x = 20; System.out.print(x + " "); }}Options: Pick one correct answer from below10 2020 1010 1020 20
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.