0
I know that by default when initializing a variable of an integer type Java classifies it as int
, but in the case of short s = 2
, Java already understands 2 as short
? Or is there some conversion?
0
I know that by default when initializing a variable of an integer type Java classifies it as int
, but in the case of short s = 2
, Java already understands 2 as short
? Or is there some conversion?
0
There is no conversion, but there is one cast implicit, so even though technically its literal is a int
, if it can be considered a short
this will be done by the compiler when generating the code. The compiler knows how to understand the int
as if it were a short
at no cost. A cast can be performed by the compiler without implying in code to be executed, therefore without conversion. In memory only 2 bytes will be reserved and the number will be encoded in this way without losses or conversions (if it fits in the track of this type, you cannot do this if the number escapes from the track).
Not all cast generates conversion, the compiler makes effort to only interpret in the different way he needs in that context, in some cases not being possible he will make a conversion, but it is not this case, he knows he can only interpret that number as a short
.
Browser other questions tagged java typing literal
You are not signed in. Login or sign up in order to post.
Maniero, I don’t understand the beginning of your explanation. If there is a cast, then there is a conversion, no?
– Alexandre S. V. Oliveira
No, if cast if ever a conversion would call Conversion and not cast. You probably don’t understand what a cast.
– Maniero
So by the site I’m studying the author speaks in conversion. Even he says there is no cast operation. He just says that java understands short because the type is short (speaking of a value that is among the values that a short can represent). May I know the reference you used for your reply?
– Alexandre S. V. Oliveira
Did you ask for reference to who is teaching you wrong? Probably he also does not know what is a cast, I suggest looking for a better source. If there’s an operation going on he should prove it. It’s much harder for me to prove something that doesn’t happen. Cast is something that only the compiler can apply, does not execute anything https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html, https://en.wikibooks.org/wiki/Java_Programming/Literal, shttps://stackoverflow.com/questions/2294934/Setting-short-value-java#comment2259689_2294977, https://stackoverflow.com/a/5193983/221800
– Maniero