What is the difference between type casting and type conversion in C++ or Java?

后端 未结 8 1604
Happy的楠姐
Happy的楠姐 2020-12-13 20:15

What is the difference between typecasting and typeconversion in C++ or Java ?

8条回答
  •  温柔的废话
    2020-12-13 21:10

    If you concentrate on Java and numeric types, according Javadoc I think the main differences between type casting and type conversion are:

    • without information and precision loss (type conversion)
    • precision loss (type conversion)
    • information loss (type casting)

    To consider more detail, first(without information and precision loss), conversion can be done without information and precision loss. These conversions include: byte to short, short to int, char to int, int to long, int to double and finally float to double. For example:

    byte b = 2;
    System.out.println(b); 
    short s = b; // without information and precision loss (type conversion)
    System.out.println(s);
    

    result:

        2
        2
    

    Secondly(precision loss), conversion is performed with precision loss, it means that the result value has the right magnitude however with precision loss. These conversions include: int to float, long to float and long to double. For example:

    long l = 1234567891;
    System.out.println(l); 
    double d = l; // precision loss (type conversion)
    System.out.println(d);
    

    result:

        1234567891
        1.234567891E9
    

    Thirdly (information loss), conversion is done via information loss, it means that you are casting the values, so it has its own syntax. These conversions include: double to long, double to int and so forth. For example:

    double d = 1.2;
    System.out.println(d); 
    long l = (long) d; // information loss
    System.out.println(l);
    

    result (fractional part is omitted):

        1.2
        1
    

提交回复
热议问题