Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to byte casting in Java

Tags:

java

In Java we can do

byte b = 5;    

But why can't we pass same argument to a function which accepts byte

myObject.testByte(5);
public void testByte (byte b)
{
  System.out.println("Its byte");
}     

It gives following error

The method testByte(byte) in the type Apple is not applicable for the arguments (int)

PS: May be a silly question, I think I need to revise my basics again.

Thanks.

like image 617
Ajinkya Avatar asked Sep 10 '11 03:09

Ajinkya


1 Answers

Hard-coded initializer values are somewhat special in Java - they're assumed to have a coercion to the type of the variable you're initializing. Essentially, that first bit of code effectively looks like this:

byte b = (byte) 5;

If you did this...

myObject.testByte((byte) 5);

...you wouldn't get that error, but if you don't do that, then the 5 is created by default as an int, and not automatically coerced.

like image 72
Amber Avatar answered Sep 19 '22 23:09

Amber