简体   繁体   中英

Casting vs Appending

Consider the following code:

int x = 300;
int y = 200;

float new_x = 300/1.2f;           // Appending 'f' to the end of operation
long new_y = (long)Math.pow(y,7); //Casting

When performing both operations my compiler wants to convert new_x and new_y to double.

But by appending or casting I can force the compiler to keep it the way I want.

My question is:

What is the difference between the casting method and the appending method

Appending a letter (l,d,f) to a LITERAL is only to specify to the compiler what type you mean that literal to be. If you write a literal in your source code, by default it is considered an int or a double.

Casting on the opposite is actually converting an existing value (for example the double returned by Math.pow) into another java type.

Casting a primitive can cause truncation. For example, a double casted to an int or to a long will loose the decimal part, converting a big long to int can result in a totally different number (if the long is higher than Integer.MAX_VALUE), and converting to short or byte is the same with stronger limits.

Casting is a much wider concept, you can cast instances and not only primitives :

public void aMethod(Number n) {
  Long l = (Long)n;  // Obviously will throw exception if you don't call it with a long
}

Casting can cause a ClassCastException if you try to cast an instance to something it is not.

This does not happen between primitives, which are automatically casted by the jvm.

For example calling :

aMethod(1);

Will throw an exception, even if a primitive int can be casted to a primitive long, an instance of Integer can't be cast to an instance of Long, as much as an instance of Person can't be cast to Dog.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM