Why does the output show 1 and not 3?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
jackylaucf
Messages
3
Reaction score
0
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 want to 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:
Physics news on Phys.org
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.
 
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);
 
  • Like
Likes   Reactions: FactChecker
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);
    }
}