Java Tricky Output Questions

Question 1: What will be the Output of the below code:

filter_none

edit
close

play_arrow

link
brightness_4
code

public class A {
    public static void main(String[] args)
    {
        if (true)
            break;
    }
}

chevron_right


Choices:

  • a) Nothing
  • b) Error

Answer: b) Error
Reason: Break statement can only be used with loop or switch. So, using break with if statement causes “break outside switch or loop” error.



 

Question 2: What will be the Ouput of the below code:

filter_none

edit
close

play_arrow

link
brightness_4
code

public class A {
    public static void main(String[] args)
    {
        System.out.println('j' + 'a' + 'v' + 'a');
    }
}

chevron_right


Choices:

  • a) java
  • b) Something else (Other than simple concatenation)

Answer: b) Something else (Other than simple concatenation)
Reason: “java” would be printed if String literals (in double quotes) are used, but in the question since character literals has been used, these won’t be concatenated. Therefore After execution of the program, an addition of each equivalent ASCII(Unicode) value of the character will be obtained.
Hence the output is 106 + 97 + 118 + 97 = 418



 

Question 3: What will be the Ouput of the below code:

filter_none

edit
close

play_arrow

link
brightness_4
code

public class A {
    public static void main(String[] args)
    {
        int $_ = 5;
    }
}

chevron_right


Choices:

  • a) Nothing
  • b) Error

Answer: a) Nothing
Reason: It looks like $ will cause an error, but it won’t. In java, identifier rule says, identifier can start with any alphabet or underscore (“_”) or dollar (“$”). So answer is Nothing.

More Java Output Questions



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.