Open In App

Java Tricky Output Questions

Last Updated : 16 Aug, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




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


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 Output of the below code:




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


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 Output of the below code:




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


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.

 

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




public class Demo{
    public static void main(String[] arr){
        Integer num1 = 100;
        Integer num2 = 100;
        Integer num3 = 500;
        Integer num4 = 500;
          
        if(num1==num2){
            System.out.println("num1 == num2");
        }
        else{
            System.out.println("num1 != num2");
        }
        if(num3 == num4){
            System.out.println("num3 == num4");
        }
        else{
            System.out.println("num3 != num4");
        }
    }
}


Choices:

  • a) num1 == num2
        num3 == num4
  • b) num1 == num2
        num3 != num4
  • c) num1 != num2
        num3 == num4
  • d) num1 != num2
        num3 != num4

Answer: b)num1 == num2
                  num3 != num4
Reason: We always thought that whenever two object references are compared using “==”, it always evaluates to “false”. But here Integer caching changes the results.Integer class has a caching range of -128 to 127. Whenever a number is between this range and autoboxing is used, it assigns the same reference. That’s why for value 100, both num1 and num2 will have the same reference, but for the value 500 (not in the range of -128 to 127), num3 and num4 will have different reference.

 

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




public class Demo{
    public static void main(String[] arr){
          
    }
    public static void main(String arr){
          
    }
}


Choices:

  • a) Nothing
  • b) Error

Answer: a) Nothing
Reason: We can overload main() too. But JVM will always call main() that has String[] argument.

More Java Output Questions



Similar Reads

Few Tricky Programs in Java
Comments that execute : Till now, we were always taught "Comments do not Execute". Let us see today "The comments that execute" Following is the code snippet: public class Testing { public static void main(String[] args) { // the line below this gives an output // \u000d System.out.println("comment executed"); } } Output: comment executed
2 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Output of Java Program | Set 1
Difficulty Level: Rookie Predict the output of the following Java Programs.Program 1: Java Code // filename Main.java class Test { protected int x, y; } class Main { public static void main(String args[]) { Test t = new Test(); System.out.println(t.x + " " + t.y); } } Output: 0 0 In Java, a protected member is accessible in all cl
3 min read
Output of Java Program | Set 2
Predict the output of the following Java programs. Question 1: Java Code package main; class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main { public static void DoPrint(Base o) { o.Print(); } public static void main(Str
3 min read
Output of Java Program | Set 3
Predict the output of the following Java Programs: Example1: Java Code // filename: Test.java class Test { // Declaring and initializing integer variable int x = 10; // Main driver method public static void main(String[] args) { // Creating an object of class inside main() Test t = new Test(); // Printing the value inside the object by // above cre
3 min read
Output of Java program | Set 23 (Inheritance)
Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); } } class B { public static String sing() { retu
3 min read
Output of Java Programs | Set 54 (Vectors)
Prerequisite : Vectors in Java Basics 1. What is the Output Of the following Program Java Code import java.util.*; class demo1 { public static void main(String[] args) { Vector v = new Vector(20); System.out.println(v.capacity()); System.out.println(v.size()); } } Output: 20 0 Explanation: function - int capacity( ) Returns the capacity of the vect
6 min read
Output of Java programs | Autoboxing and Unboxing
Prerequisite - Autoboxing and unboxing in Java 1)What is the output of the following program? class Main { public static void main(String[] args) { Double x1, y1, z1; double x2, y2, z2; x1 = 10.0; y1 = 4.0; z1 = x1 * x1 + y1 * y1; x2 = 10.0; y2 = 4.0; z2 = x2 * x2 + y2 * y2; System.out.print(z1 + " "); System.out.println(z2); } } Options:
3 min read
Fast Output in Java
While doing problems in various coding platforms in some questions we end up with (TLE). At that point of time even if we use fast input then also, sometimes (TLE) remains in Java. At that time if we use fast output with fast input it can reduce the time taken. The fast output is generally used when we have to print numerous items which is shown la
3 min read
XML Output Factory in Java StAX
StAX provides various classes to create XML stream readers, writers, and events by using the XMLInputFactory, XMLOutputFactory, and XMLEventFactory classes. In this article we're going to study about XML Output Factory . The class javax.xml.stream.XMLOutputFactory is a root component of the Java StAX API. From this class you can create both an XMLS
3 min read
Output of Java Program | Set 4
Predict the output of following Java Programs: Question 1 // file name: Main.java class Base { protected void foo() {} } class Derived extends Base { void foo() {} } public class Main { public static void main(String args[]) { Derived d = new Derived(); d.foo(); } } Output: Compiler Error foo() is protected in Base and default in Derived. Default a
2 min read
Redirecting System.out.println() Output to a File in Java
System.out.println() is used mostly to print messages to the console. However very few of us are actually aware of its working mechanism. We can use System.out.println() to print messages to other sources too, not just restricting it to the console. However, before doing so, we must reassign the standard output by using the following method of Syst
2 min read
Output of Java Program | Set 6
Difficulty level : Intermediate Predict the output of following Java Programs. Program 1: class First { public First() { System.out.println("a"); } } class Second extends First { public Second() { System.out.println("b"); } } class Third extends Second { public Third() { System.out.println("c"); } } public class MainCl
2 min read
Output of Java Program | Set 7
Difficulty level : Intermediate Predict the output of following Java Programs. Program 1 : public class Calculator { int num = 100; public void calc(int num) { this.num = num * 10; } public void printNum() { System.out.println(num); } public static void main(String[] args) { Calculator obj = new Calculator(); obj.calc(2); obj.printNum(); } } Option
4 min read
Output of Java programs | Set 10 (Garbage Collection)
Prerequisite - Garbage Collection in Java Difficulty level : Intermediate In Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Below are some important output questions on Garbage collection. Predict the output of following Java Progra
4 min read
Output of Java Program | Set 11
Predict the output of following Java programs: Question 1 : public class Base { private int data; public Base() { data = 5; } public int getData() { return this.data; } } class Derived extends Base { private int data; public Derived() { data = 6; } private int getData() { return data; } public static void main(String[] args) { Derived myData = new
4 min read
Output of Java Programs | Set 12
1) What is the output of the following program? Java Code public class Test implements Runnable { public void run() { System.out.printf("%d", 3); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Test()); thread.start(); System.out.printf("%d", 1); thread.join(); System.out.pri
5 min read
Output of Java programs | Set 13 (Collections)
Prerequisite - Collections in Java 1) What is the output of the following program? Java Code import java.util.*; public class priorityQueue { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(11); queue.add(10); queue.add(22); queue.add(5); queue.add(12); queue.add(2); while (queue.
3 min read
Output of Java program | Set 15 (Inner Classes)
Prerequisite :- Local inner classes , anonymous inner classes 1) What is the output of the following java program? public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + temp2
3 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Output of Java program | Set 17
1) What is the output of following program? public class Test { private static float temp() { public static float sum = 21; return(--(sum)); } public static void main(String[] args) { Test test = new Test(); System.out.println(test.temp()); } } a) 21 b) 20 c) Compilation error d) Runtime error Ans. (c) Explanation: static variables are associated w
2 min read
Output of Java program | Set 18 (Overriding)
Prerequisite - Overriding in Java 1) What is the output of the following program? class Derived { protected final void getDetails() { System.out.println("Derived class"); } } public class Test extends Derived { protected final void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derive
3 min read
Output of Java Program | Set 19
Predict the output of following Java Programs. Program 1 : public class RuntimePolymorphism { public static void main(String[] args) { A a = new B(); B b = new B(); System.out.println(a.c + " " + a.getValue() + " " + b.getValue() + " " + b.getSuperValue()); } } class A { protected char c = 'A'; char getValue() { return
3 min read
Output of Java programs | Set 24 (Final Modifier)
Difficulty level : Easy Prerequisite : final keyword in java Predict the output of following Java Programs: What will be output of following program? class Test { final int MAXIMUM; final double PI; public Test(int max) { MAXIMUM = max; } public Test(double pi) { PI = pi; } public static void main(String[] args) { Test t1 = new Test(1500); Test t2
3 min read
Output of Java program | Set 25 (Polymorphism)
Pre-requisite: Polymorphism in java 1) What is the output of the following program? class GFG { protected void getData() { System.out.println("Inside GFG"); } } class GeeksforGeeks extends GFG { protected void getData() { System.out.println("Inside GeeksforGeeks"); } } public class Test { public static void main(String[] args) {
3 min read
Formatted Output in Java using printf()
Sometimes in programming, it is essential to print the output in a given specified format. Most users are familiar with the printf function in C. Let us discuss how we can Formatting Output with printf() in Java in this article. Formatting Using Java Printf()printf() uses format specifiers for formatting. There are certain data types are mentioned
5 min read
Output of Java Programs | Set 14 (Constructors)
Prerequisite - Java Constructors 1) What is the output of the following program? [GFGTABS] Java class Helper { private int data; private Helper() { data = 5; } } public class Test { public static void main(String[] args) { Helper help = new Helper(); System.out.println(help.data); } } [/GFGTABS]a) Compilation error b) 5 c) Runtime error d) None of
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Servlet - Output Stream Class
ServletOutputStream class is a component of Java package javax.servlet, is an abstract class that provides an output stream to send binary data to the client. ServletOutputStream inherits OutputStream which is the superclass of all classes representing an output stream of bytes. Subclasses of ServletOutputStream class must implement the java.io.Out
3 min read
Frequently asked questions for Java Developer Position from a fresher
Java Based: OOPs concepts ( mostly polymorphism and difference between encapsulation and abstraction) Difference between abstract class and interface. Difference between == and .equals() functions. What is Hash Map ? What is Hash Table ? Types of Exceptions. Difference between Exceptions and Errors. Difference between throw, throws and throwable. D
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg