Confused idea of ​​implicit narrowing of primitives in Java

The next seemingly trivial problem shocked the core of my understanding of how primitives work in Java.

I came across a term according to which a variable of a type of a smaller range is allowed to hold a literal value of a type of a wider range if this value falls into this smaller size, range. As I know, Java admits that only among bytes, char, short and int. "implicit narrowing"

For example, a CAN byte variable accepts int if this value is small enough to match a range of byte types.

byte b1 = 3; // allowed even though 3 is an int literal
byte b2 = 350; // compilation error because a byte cannot go beyond positive 127

So this works great:

byte k = 3;

But I do not know why the line below does not work !!

Byte k = new Byte(3);

If I do not change the latter to , I get this error compilation : Byte k = new Byte((byte)3)

error: no suitable constructor found for Byte(int)
        Byte k = new Byte(3);                                        
                 ^             
constructor Byte.Byte(byte) is not applicable                    
(actual argument int cannot be converted to byte by method invocation conversion)

error message, , , :

"... actual argument int cannot be converted to 
 byte by method invocation conversion"

:
?! , int literal int literal , ?

, , int. . , , , !

+4
4

( ) .

Java (JLS) 8 §3.10, Java 6 : IntegerLiteral, FloatingPointLiteral, BooleanLiteral, CharacterLiteral, StringLiteral NullLiteral.

3.10.1 :

Integer long, ASCII L l (ell); int (. 4.2.1).

(. 4.2.1 - )

IntegerLiteral 7 , . , int , .

. , .

JLS, . , . .. int , long , int , byte, .

+9

, , . , , , . , , . , . : , , public Byte (int i)? , , , . , - , , .

+3

, char, short int, .

byte b1 = 3; .

, int, , , , int.

Byte k = new Byte(3); int , .

+1

k = (3);

1) "" , , .

2) When creating an object of type Byte , the constructor will consider the argument as Integer , so we must explicitly cast the argument to the byte as:

Byte k = new byte ((byte) 3);

0
source

Source: https://habr.com/ru/post/1570818/


All Articles