java - 将方法参数传递给java中byte,int,int类型的方法参数

标签 java methods casting byte

以下方法接受三个类型为 byte,int,int 的参数,并且该方法是从另一个方法调用的,该方法给出了一个编译错误,即方法参数不适用于 int,int ,int。默认情况下,字节参数只有在显式转换完成后才能识别。

 public double subtractNumbers(byte arg1,int arg2,int arg3) {
    double sum=arg1+arg2+arg3;
    return sum;
}

现在方法调用另一个方法如下

 public void call(){
  subtractNumbers(15,16,17);   /*Compile error,but 15 is in byte acceptable 
 range of -128 to 127 */
  }

如果我将上面的调用更改为 subtractNumbers((byte)15,16,17); 它工作正常

当我将变量声明为 byte c=15 时,它被接受但是当 15 被传递给字节参数时为什么会出现编译错误;

int 是 byte,short,int,long 的默认字面值,这就是为什么字节 c=15 被接受而无需强制转换但不接受方法参数的原因。

提前致谢。

最佳答案

您的问题归结为:

为什么将 15 分配给 byte 在变量声明中有效:

byte b = 15;

但不是在调用方法时?

subtractNumbers(15,16,17);

这是因为这两种情况处于两种不同的上下文。第一个在赋值上下文中,而第二个在调用上下文中。

根据JLS §5.2 Assignment Contexts ,

Assignment contexts allow the use of one of the following:

...

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

15 当然是一个常量表达式,因此允许从 intbyte 的缩小原始转换。

然而,在调用上下文中,这是不正确的:

JLS §5.3 Invocation Context

Strict invocation contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)

Loose invocation contexts allow a more permissive set of conversions, because they are only used for a particular invocation if no applicable declaration can be found using strict invocation contexts. Loose invocation contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by widening reference conversion
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion

没有提到“narrowing primitive conversion”,所以在调用上下文中是不允许的。

关于java - 将方法参数传递给java中byte,int,int类型的方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240176/

相关文章:

java - Java 客户端<-->服务器套接字的问题

c# - 如何创建一个使用模式如锁的方法?

C++检测传递给函数的const int

java - Hbase 映射减少 : how to use custom class as value for the mapper and/or reducer?

java - 当两个java桌面应用程序使用相同的SQLite数据库时如何避免sql异常

javascript - 如何向内置 String 对象添加 getter 方法?

c++ - C++将对象强制转换为其原始类型

java - 类型转换 Math.pow() 时精度损失

java - ThreadPoolExecutor, future : correlating requests and responses

oop - 错误的方法名称及其对代码结构的说明