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

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

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

8条回答
  •  长情又很酷
    2020-12-13 21:09

    From an object to primitive -> Type conversion

    String s = "1234";
    int i = Integer.parseInt(s);
    int j = Integer.valueOf(s);
    

    From an primitive to object -> Type conversion

    int i = 55;
    String s = String.valueOf(i);
    String t = Integer.toString(i);
    

    From a primitive to primitive(or object to object) -> Type casting(explicit when narrowing and implicit when widening)

    //explicit  
    double d = 3.14156;
    int i = (int)d; 
    //implicit
    int i = 100;
    double d = i;
    

    Note: In case of object type casting, we cannot use child class reference to hold parent object

提交回复
热议问题