3
Byte byte1=10;
Short short1=20;
Integer integer=30;

In the above code autoboxing happens successfully see the below code here I am doing casitng explicitly because It is taking 20 as integer numeric literal by default.

Byte byte1=new Byte((byte) 20);
Short short1=new Short((short) 20);

but see the below code , I have to use l,f and d explicitly without this it is showing error........what is the reason behind it.I am not getting it.

Long long1=40l;
Float float1=50f;
Double double1=60d;
4

2 回答 2

3

Auto-boxing doesn't include automatic widening of primitives.

The default type of a constant integer numeric expression in java is int, so those numbers are ints, which will be auto boxed to Integers if required. Automatic widening will occur when a narrower primitive type is assigned to a wider type, such as an int to a long.

But the two compiler actions will not both happen; that's why you need to get the primitive constant expression to the appropriate type so that the auto boxing will be to the correct type.

于 2013-09-08T14:53:37.817 回答
1

This is part of the Language Specification for floating point literals, ie. F or f for float, and D or d for double

For decimal floating-point literals, at least one digit (in either the whole number or the fraction part) and either a decimal point, an exponent, or a float type suffix are required.

For integers,

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

The unboxing conversions are, among other,

From type long to type Long

From type float to type Float

From type double to type Double

So unless your types are the correct type, you cannot unbox.

As for the Byte, Short, Integer, the JLS again comes to the rescue

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

In your case, an explicit cast isn't necessary because the values fall within the range of their specific type. If instead, you had

Byte b = 1251;

that would create a compilation error, solved by doing

Byte b = (byte)1251;

but losing information in the value.

于 2013-09-08T15:06:48.253 回答