Multiple Choice java code

• Java
Consider the following java code

Java:
int a=1;
if (a != 0)
{
int a=3;
}
System.out.print(a);

What is the output
A. 0
B. 1
C. 3
D. No output. A compilation error occurs

The answer is B. I wanna ask why the output shown will not be 3. As the 1 is not equal to 0, should the ' int a ' be modified to 3?
Thank you

Last edited by a moderator:

jtbell
Mentor
I suggest you review the concept of "scope" of a variable. In your code, there are two separate variables named 'a'. One of them is "visible" only outside the curly braces, and contains the value 1. The other one is "visible" only inside the curly braces, and contains the value 3.

Mark44
Mentor
Pay a bit more attention to where you put your closing braces. At first I thought your code was missing the right brace on the if statement. The closing brace should be aligned with the code that follows it, like so:
Java:
int a=1;
if (a != 0)
{
int a=3;
}
System.out.print(a);

FactChecker
Borg
Gold Member
jackylaucf, your example as shown doesn't compile if you place it within a method. I'm assuming that you haven't copied it correctly and have left off important info. The answer would be D unless the question looks something like this:
Java:
class SomeJavaClass {
int a = 1;

void someJavaMethod() {
if (a != 0) {
int a = 3;
}

System.out.print(a);
}
}