Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Multiple Choice java code

Tags:
  1. Oct 8, 2014 #1
    Consider the following java code

    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: Oct 9, 2014
  2. jcsd
  3. Oct 9, 2014 #2

    jtbell

    User Avatar

    Staff: 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.
     
  4. Oct 9, 2014 #3
  5. Oct 9, 2014 #4

    Mark44

    Staff: 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:
    Code (Java):
    int a=1;
    if (a != 0)
    {
       int a=3;
    }
    System.out.print(a);
     
  6. Oct 9, 2014 #5

    Borg

    User Avatar
    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:
    Code (Java):
    class SomeJavaClass {
        int a = 1;

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

            System.out.print(a);
        }
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Multiple Choice java code
  1. Confused java HW code (Replies: 9)

Loading...