Passing method arguments to the method parameters of type byte,int,int in java

Shashaank V V :

The following method accepts three arguments of type byte,int,int and the method is called from another method which gives a compilation error that the method parameters are not applicable for int,int,int.By default the byte parameter is not recognized until explicit casting is done.

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

Now method calling in another method as follows

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

If i change the above calling as subtractNumbers((byte)15,16,17); it works fine

When i declare a variable as byte c=15 it is accepted but when 15 is passed to a byte argument why there's a compile error;

int is the default literal for byte,short,int,long then why byte c=15 is accepted without casting but not method argument.

Thank you in advance.

Sweeper :

Your question boils down to:

Why does assigning 15 to a byte works in a variable declaration:

byte b = 15;

But not when calling a method?

subtractNumbers(15,16,17);

This is because those two situations are in two different contexts. The first is in an assignment context, while the second is in an invocation context.

According to the 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 is certainly a constant expression, so a narrowing primitive conversion from int to byte is allowed.

In an invocation context however, this is not true:

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" is not mentioned, so it is not allowed in invocation contexts.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98171&siteId=1