Roel De Nijs wrote:Because every integral literal in Java is by default an int. Just like any decimal point literal is by default a double.
Puspender Tanwar wrote:
Roel De Nijs wrote:Because every integral literal in Java is by default an int. Just like any decimal point literal is by default a double.
I was aware of this, read it in K&B book, but in confusion that why not a suffix (like f, l, L) is used in short as integral type are by default int
Puspender Tanwar wrote:but in confusion that why not a suffix (like f, l, L) is used in short as integral type are by default int
Guillermo Ishi wrote:I think it is just incredibly annoyingly arbitrary. There are a few of those things.
System.out.println(myInt1 == myNumber1); // 12 compilation fails incompatible operand types int and Number. !!!
This statement is again a little tricky, but indeed does not compile. You may think the Java compiler will simply unbox this value as well (like with the other statements). But although Number is the (abstract) parent class of concrete classes Integer, Long, Float,... boxing/unboxing does not work with Number. The Java compiler needs to know exactly what type of number it's dealing with to perform the boxing/unboxing.
System.out.println(myInteger1 == myNumber1); // 17 true
Let's have a look at this tricky statement. It prints indeed true. But why? First of all, this code compiles successfully. No compiler error like with line16 and line18. So no incompatible types here, because these types are not different from each other. Integer IS-A Number. Now let's look at line6: Number myNumber1 = 10;. We already know this 10 is an int and thus the compiler will wrap/autobox it into an Integer using Integer.valueOf(10) resulting in this statement: Number myNumber1 = Integer.valueOf(10);
nick woodward wrote:Such a good post about boxing on the first page Roel, so I thought I'd bump this, rather than start a new thread.
nick woodward wrote:I'm guessing that the difference between these two is that the second is actually compiling because of the IS-A relationship and is not even attempting unboxing at all?
so the second statement is true not because the values are both 10, but because myNumber and myInteger both point to the cached object 10?
snakes are really good at eating slugs. And you wouldn't think it, but so are tiny ads:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|