Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unexpected results when type casting between long and double

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?

like image 809
JavaNewbie_M107 Avatar asked Aug 11 '13 14:08

JavaNewbie_M107


People also ask

What is typecast error?

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.

What is narrowing casting?

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.

What is type casting explain in detail with examples the 2 types of 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.


1 Answers

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.

like image 161
esej Avatar answered Oct 16 '22 09:10

esej