Output of Java Programs | Set 50
Last Updated :
22 May, 2023
Q 1. What is the output of this program?
Java
class Example {
private int x;
public static void main(String args[])
{
Example obj = new Example( 5 );
}
public Example( int x)
{
System.out.println( "x = " + x);
}
public void Example( int x) { System.out.println(x); }
}
|
Option
A. 0
B. Garbage value
C. Compile time error : variable is not initialized
D. Run time error : a is the blank variable
Output:
C. Compile time error : variable is not initialized
Explanation: In Java, final variable becomes 0 by default. Only three ways to initialize the final variable 1. using constructor 2. initialization block 3. At the time of variable declaration.
Q 2: What is the output of this program?
Java
class Test {
public static void main(String args[])
{
String str1 = new String( "Hello World" );
String str2 = new String( "Hello World" );
String str3 = "Hello World" ;
String str4 = "Hello World" ;
int a = 0 , b = 0 , c = 0 ;
if (str3 == str4)
a = 1 ;
else
a = 2 ;
if (str1.equals(str3))
b = 1 ;
else
b = 2 ;
if (str1 == str4)
c = 1 ;
else
c = 2 ;
System.out.println( "a= " + a + " b= " + b
+ " c= " + c);
}
}
|
Option
A. 0
B. Garbage value
C. Compile time error
D. No output: Blank Screen
Output:
D. No output : Blank Screen
Explanation: There are no constructors in this program. This is a method just like name of the class but it is not a constructor because the constructor does not return type. So in this program output is a blank screen.
Q 3: What is the output of this program?
Option
A. x = 5
B. 5
C. Compile time error: ambiguous call of Example(int)
D. Run time error
Output:
A. x = 5
Explanation: In this program “public Example(int)” is the constructor and “public void Example(int)” is the method so the compiler will not be confused. And constructor will be automatically called at the time of object creation.
Q 4: What is the output of this program?
Java
class Test {
public static void main(String args[])
{
String str1 = new String( "Hello World" );
String str2 = new String( "Hello World" );
String str3 = "Hello World" ;
String str4 = "Hello World" ;
int a = 0 , b = 0 , c = 0 ;
if (str3 == str4)
a = 1 ;
else
a = 2 ;
if (str1.equals(str3))
b = 1 ;
else
b = 2 ;
if (str1 == str4)
c = 1 ;
else
c = 2 ;
System.out.println( "a= " + a + " b= " + b
+ " c= " + c);
}
}
|
Option:
A. a=2 b=1 c=2
B. a=2 b=2 c=2
C. a=1 b=2 c=1
D. a=1 b=1 c=2
Output:
D. a=1 b=1 c=2
Explanation: When we make the object with the help of new keyword then a new memory created and reference variable contain the memory location. Here two times memory is created with same string but we are comparing objects not string, so object are pointing to different memory locations so they are not equal.
Q 5. How many objects created in the above example?
Option:
A. 1
B. 2
C. 3
D. 4
Output:
B.2
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...