问题
What do (long)
and (int)
in the following statements before the expression mean?
long years = (long) (minutes / minutesInYear);
int remainingDays = (int) (minutes / 60 / 24) % 365;
回答1:
(minutes / minutesInYear)
is unclear as to what variable type it will return. If you want it in an int variable, you must write (int)
before it. This is called "typecasting", and it basically converts one format to another. You'll notice that int a = 10.5;
doesn't work but int a = (int) 10.5;
does.
In your example, you want this: (minutes / minutesInYear)
to be stored in a float. So, to make sure it becomes a float, you typecast it using (float)
回答2:
The thing that you are talking about is called casting.
You can cast the expression on the right hand side to the one on the left.
The casting can be done on primitive types and also to classes.
Casting means taking an Object of one particular type and “turning it into” another Object type. This process is also called casting a variable.
For more you can read here.
In your case you use casting because you are converting a variable of primitive type double (which is on the right side) to one of type int which is on the left side.
回答3:
What you see there is casting from one value type to another.
EDIT: The reason why this is possible is that you might need it if you are working with generic types or inheritance (see the example) and you can not determine the object type beforehand. For this kind of code though, it is often better to just work with the correct types in the first place and avoid mistakes! (in this case double)
Since an int has no decimal values, the data stored in the int object will not be the exact value of the calculation (the same for a long)
If you want the exact values, you should look at a double instead.
This also works for non numeric values by the way:
Object car = new Car();
Car myNewCar = (Car) car;
I hope this helps.
回答4:
Casting object because int is not a long, and long is not an int.
int i = (int) 10L;
- because 10L is long, and you want it to be int.
回答5:
Having a type inside a parentheses usually means casting, not only in Java but also in other languages (for instance, C#).
In the first case, if minutes and minutesInYear are integers, the operation will produce an integer. Then you cast it to a long, which is the same as an integer but 64 bits instead of 32 (it can store bigger values).
In the second case just happens to be the same, but you cast it to an integer, which is probably redundant (not necessary) as the result is already an integer.
Nevertheless, if you cast a non integer value (float, double) to an integer value (byte, short, int, long) it will return the truncated value, not the rounded value.
来源:https://stackoverflow.com/questions/35706362/what-does-long-name-long-expression-do-in-java