?
What is the output of the above program?
What is the output of the above program?
class Num {
Num(double x ){
System.out.println( x ) ;
}
}
public class Test extends Num {
public static void main(String[] args){
Num num = new Num( 2 ) ;
}
}
class Num {
Num(double x ){
System.out.println( x ) ;
}
}
public class Test extends Num {
public static void main(String[] args){
Num num = new Num( 2 ) ;
}
}
Answer & Solution
Correct Answer:
Option
C
The given program creates a class Num that has a constructor with a double parameter.
In the main method, an object of the Num class is created with the value 2, which is passed as a double value.
Since 2 is treated as an integer, Java automatically converts it to a double (2.0), and the constructor prints this value.
Thus, the output of the program is 2.0.
In the main method, an object of the Num class is created with the value 2, which is passed as a double value.
Since 2 is treated as an integer, Java automatically converts it to a double (2.0), and the constructor prints this value.
Thus, the output of the program is 2.0.
Join the Discussion
Login to post a comment or share your explanation.
LoginThe compile-time legality of a casting conversion is as follows:
1. An expression of a primitive type may undergo casting conversion to another primitive type, by an identity
conversion (if the types are the same), or by a widening primitive conversion, or by a narrowing primitive
conversion, or by a widening and narrowing primitive conversion.
2. An expression of a primitive type may undergo casting conversion to a reference type without error, by
boxing conversion.
3. An expression of a reference type may undergo casting conversion to a primitive type without error, by unboxing conversion.
thus you have to manually typecast value before passing to the constructor.
Ex :
1. Num num = new Num((double) 2); // this is right as passing primitive type to construtor accepting reference
type of same type. So you to do typecasting manually.
2. Num num = new Num(new Double(2)); // is right by Rule 2.
3. Num num = new Num(2); this is wrong as By Rule 1: as you are passing an integer value (primitive type ) to the constructor which accepts Double (reference type of different type).
Because in java every number stored in double data type memory
but if we do changes like num class inherit test class that will become right and will output 2.0
It will work:
class Num{
Num(double x)
{
System.out.println("Hi");
}
Num(int x)
{
System.out.println("Hi2");
}
}
class Test extends Num {
Test(){
super(2.0);
}
public static void main(String args[]) {
Test b =new Test();
}
}