What is the output of the below program?
class B {
public static void main(String[] d) {
int i;
i = 0;
System.out.println(i);
}
}
Before you scroll down, write your answer. This is one of the simplest Java programs you will see in an interview.
The correct output is: 0
Here is exactly what happens, line by line.
Step 1: The class is declared
class B { ... } defines a class named B. It has one method, main.
Step 2: The main method is invoked
public static void main(String[] d) is the entry point. The JVM calls this method when the program starts.
Step 3: The variable is declared
int i; declares an integer variable named i. It has no value yet.
Step 4: The variable is assigned
i = 0; assigns the value 0 to i. Now i holds 0.
Step 5: The value is printed
System.out.println(i); prints the value of i, which is 0. The println also moves to the next line.
Final output: 0
Why this question is asked
It is not a trick question. It tests whether you understand the basics:
- Variable declaration vs assignment. You can declare a variable without a value. You assign it later.
- Primitive types.
intis a primitive type that holds whole numbers. - Printing.
System.out.printlnprints the value and adds a newline.
If you can explain this program clearly, you understand the foundation of Java. Every complex program builds on these basics.
Common variations of this question
Interviewers sometimes change one line to see if you are paying attention.
| Variation | Output | Why |
|---|---|---|
int i; without assignment, then print |
Compile error | Local variables must be initialized before use. |
static int i; without assignment, then print |
0 |
Static fields get default values. int defaults to 0. |
int i = 5; then print |
5 |
The value is whatever you assign. |
System.out.print(i); instead of println |
0 (no newline) |
print does not add a newline. Same value, different formatting. |
Where to go next
You now know the answer is 0. You know why. You also know the variations that interviewers ask next.
If you want to go deeper, try this: remove the i = 0; line and compile. Watch the error. Then make i a static field and remove the assignment. Watch it print 0 again. The difference between local variables and static fields is a common follow-up question.
And the next time someone shows you a "simple" program, do not rush. Check the types, check the assignment, check the print. The basics are where most bugs hide.
No comments:
Post a Comment