Multiple Choice java code

  • #1
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:

Answers and Replies

  • #2
jtbell
Mentor
15,659
3,729
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.
 
  • #4
34,271
5,910
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 FactChecker
  • #5
Borg
Science Advisor
Gold Member
1,885
2,391
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);
    }
}
 

Related Threads on Multiple Choice java code

  • Last Post
Replies
5
Views
3K
Replies
2
Views
6K
  • Last Post
Replies
9
Views
1K
Replies
11
Views
2K
Replies
5
Views
3K
  • Last Post
Replies
7
Views
3K
Replies
11
Views
4K
Replies
18
Views
6K
Replies
2
Views
1K
Replies
3
Views
2K
Top