I have this code
public class LimitTest{
public static void main(String[] args){
long l;
double d;
l = 9223372036854775807L;// The largest number a long can hold.
d = l;
System.out.println(l);
System.out.println(d);
System.out.println(l == d);
}
}
Now, the result it produces is kinda unexpected, but again, I am not very experienced with type conversions.
Output
9223372036854775807
9.223372036854776E18
true
Now, the two numbers printed are clearly NOT EQUAL, so why does l == d
return true
?
Above code type casting object of a Derived class into Base class and it will throw ClassCastExcepiton if b is not an object of the Derived class. If Base and Derived class are not related to each other and doesn't part of the same type hierarchy, the cast will throw compile time error.
The process of conversion of higher data type to lower data type is known as narrowing typecasting. It is not done automatically by Java but needs to be explicitly done by the programmer, which is why it is also called explicit typecasting.
In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. In this section, we will discuss type casting and its types with proper examples.
The variables l
and d
have different types, so the expression long == double
casts the long
to a double
...
P.S. l
is a bad variable name imho, since it looks a lot like 1
when glancing over code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With