开发者

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

开发者 https://www.devze.com 2023-01-22 17:52 出处:网络
What is the difference between typecasting and typeconversion in C++ or Ja开发者_如何学Pythonva ?Type casting is treating a value (block of memory) referenced by a variable as being of a different typ

What is the difference between typecasting and typeconversion in C++ or Ja开发者_如何学Pythonva ?


Type casting is treating a value (block of memory) referenced by a variable as being of a different type than the type the variable is declared as.

Type conversion is actually performing a conversion of that value.

In many languages, some casts (usually numeric ones) do result in conversions (this will vary quite a bit by language), but mostly it's just "treat this X as a Y".

Like most aspects of human language, unfortunately the terms are used slightly differently in different communities, mostly along language lines. For instance, see James' comment below about C++ — the word "cast" there has a much broader meaning than the above definition, which is more in the C or Java mold. And just to make things fun, the Java Language Spec actually gets into various kinds of casts, including casting conversions. But the above is a good rule of thumb.

But to take a simple case:

In Java, prior to generics it wasn't unusual to have to do a lot of typecasting when dealing with maps:

Map m = new HashMap();
m.put("one", "uno");

// This would give a compiler error, because although we know
// we'll get a String back, all the compiler knows is that it's
// an Object
String italian = m.get("one");

// This works, we're telling the compiler "trust me, it's a String"
String italian = (String)m.get("one");

Fortunately, the addition of generics addressed this, as casting in this way tends to be a fragile process with maintenance issues.

In contrast, you'd convert if you had a String of digits:

String s = "1234";

...and needed to know what number those digits represented in decimal:

// Wrong (cast)
int n = (int)s;

// Right (conversion)
int n = Integer.parseInt(s, 10);


Maybe an example can help:

  • If you cast 33 to a string, you get "!".
  • If you convert 33 to a string, you get "33".

[Note: this example makes all sorts of not-necessarily-valid assumptions about the encodings and in-memory representations of numbers and strings, but I hope the mechanism is clear.]


Typecasting is just taking a pen and writing "this is now a int" on the variable, conversion is actually convert the content to the desired type so the value keeps having a sense.


Type conversion:

double value = 3; // implicit conversion to double value 3.0
int nValue = 3.14156; // implicit conversion to integer value 3

Casting is a request by the programmer to do an explicit type conversion.

int nValue = 10;
double dvalue = double(nValue); // explicit type casting


The terms are often used interchangeably.

Java

Type casting and type conversion are the same thing in Java, though if someone says that they are casting, they are usually referring to an explicit conversion.

A cast in Java will be done at runtime, so can potentially fail (throw an exception). Some types of invalid casts can be caught at compile time. When the cast fails, the instance was seated in an object reference, so the compiler couldn't tell what cast was going to be performed, until it actually ran the code.

C++

Type casting and type conversion are different in C++. There are five types of casts in C++, which all have different behavior: static_cast, dynamic_cast, reinterpret_cast, const_cast, and c-style casts ((int)someVariable).

Some C++ casts perform type conversion (hence why this concept is confusing), calling code and potentially doing runtime checks. Other C++ casts simply fake the type change of the referring variable - no memory will be modified, moved, or copied, so the resulting datatype might not be properly converted. This can give great speed at runtime, and can be a powerful tool for low-level code, but tends to be avoided for high level code.

Note that the c-style cast syntax (which happens to look exactly like the Java syntax) is one of the casts that will not necessarily call conversion code.

Type conversion in C++ often refers to calling a copy constructor or assignment operator, which will copy data over to a new instance of a different class/structure. If a type has conversion operators defined, then the conversion syntax could look like a cast, or simply a straight assignment. The main difference here is that code is called to do the conversion.


According to the Wikipedia article:

"In the C family of languages, the word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretaion of a bit-pattern or a real conversion."

Here is a C++ example:

double d = 42.0;
int i = d; // Here you have an implicit conversion from double to int
int j = static_cast<int>(d); // Here you have a cast (explicit conversion).

Here is a Java example (note that in Java unlike C++ you can't implicitly convert from double to int):

int i = 42;
double d = i; // Here you have an implicit conversion from int to double
int j = (int)d; // Here you have a cast (explicit conversion).


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号