如果在Java中将整数值作为参数传递,则隐式类型转换不起作用 [英] Implicit typecasting not working if passing integer value as argument in java

查看:110
本文介绍了如果在Java中将整数值作为参数传递,则隐式类型转换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,对整数9进行隐式类型转换,并将其分配给大小为8位的byte数据类型变量.

In the following code , implicit typecasting for an integer value 9 take place and assigned to variable of byte datatype which is of size 8 bits.

class Demo1
{
   public static void main(String args[])
    {

    byte b=9;
    System.out.println(b);

    }

}

愉快地编译并执行了代码.

The code happily compiled and executed .

但是当我编写以下代码时,它给了我编译错误

but when i wrote the following code it gave me compilation error

class Demo2 
{
   void func1(byte b)
    {
        System.out.println(b);
    }

   public static void main(String[] args) 
    {
       Demo2 d1=new Demo2();
       d1.func1(9);
    }
}

请解释一下为什么后一个代码中没有进行隐式(自动类型转换)?

please explain me why implicit (auto typecasting) is not taking place in the latter code?

谢谢大家的期待.

推荐答案

因为byte(8位)可以容纳的信息少于int(32位),所以编译器不会自动将int强制转换为byte,因为您可能会在此过程中丢失信息.例如:

Because byte (8 bits) can hold less information than int (32 bits), so the compiler will not automatically cast int to byte because you can lose information in the process. For example:

    int a = 150;
    byte b = (byte) a;
    System.out.println(b); 

这将打印-106,因为150超出了字节范围(-128-127).

This will print -106 because 150 is out of byte range (-128 - 127).

编译器需要您手动将int强制转换为byte,以确保这不是错误并且您了解强制转换的含义.

Compiler needs you to manually cast int to byte to make sure this is not an error and that you understand the implications of the cast.

这篇关于如果在Java中将整数值作为参数传递,则隐式类型转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆