将int和int文字分配给一个字节之间的区别?

Nik*_*nka 1 java

byte b = 100 ; 
Run Code Online (Sandbox Code Playgroud)

编译时没有任何错误,但是

int i = 100 ; 
byte b = i ; 
Run Code Online (Sandbox Code Playgroud)

抛出错误.为什么?即使直接将100分配给b,我们也会分配一个int文字.那么为什么我会收到错误?

Roh*_*ain 5

byte b = 100 ;
Run Code Online (Sandbox Code Playgroud)

100是一个编译时常量.因此可以分配到byte.

int i = 100 ; 
// i = i + 100;  // It's allowed to add this statement later on, 
                 // if `i` is not declared final. And hence, the next assignment
                 // will clearly fail at runtime. So, compiler saves you from it
byte b = i ; 
Run Code Online (Sandbox Code Playgroud)

现在在这种情况下,既然i没有声明final,所以它不再是compile time常数.而在这种情况下,您可以稍后来修改的值i,在之间initialization of i,并且assignment of i to byte,如在上述情况下.哪个肯定会失败.这就是为什么编译器不允许的分配ibyte打字.

但是,您可以使用显式转换来编译它,当然这可能crash在运行时.通过做一个显式演员,你告诉编译器 - "我知道我在做什么,只为我做".因此,它不会打扰该转换的运行时行为,并且会相信您没有做错任何事情.

所以,要么你可以声明你的int ias final,要么你需要进行投射: -

int i = 100 ;    // replace 100 with 130, and you will be surprised that it works
byte b = (byte)i ; 
Run Code Online (Sandbox Code Playgroud)

因此,当您使用值130并将其强制转换为时byte,您将通过compiler,但肯定会在运行时崩溃.而这正是compiler试图避免的问题.


现在让我们回到第一个案例: -

byte b = 128;
Run Code Online (Sandbox Code Playgroud)

上面的赋值现在无法编译.因为即使值128是编译时常量,它也不足以适应a byte,并且compiler知道.