• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Specific method call

 
Sim Kim
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How this code gives an Error while the one below doesnot ?
How does specific method call works . Is it different for short,byte and char types ?
Code 1 :


Code 2 :
 
No�l Verdurmen
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Here you call m1 with two arguments of type int. The compiler cannot automatically convert an int to a short (that would be loss of precision), you would have to add an explicit cast to do that.

In code1 you need to cast the int, because you do not have an appropriate method signature --> compiler recognizes that and gives error.

In code2 you have a method signature that accepts two arguments of type int, so it is no problem there.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lavjeet: I think No�l probably answered your question , but I'm adding this in response to your private message...

Literal integral values are automatically considered type int. Therefore, when you call a method and provide literal integral values as arguments, then the compiler will look for the method that accepts ints as arguments.

Specifically, when you call m1(10, 10), the compiler looks for a method defined as m1(int x, int y).

If the compiler can't find such a method, then it looks for a method that accepts primitive arguments that are wider than what you provided, and automatically converts the ints you passed to the wider type. This is "method-call conversion," and presents no problem because widening a value doesn't lose any information.

However, the compiler will not automatically convert the arguments you provided to a narrower type (byte, char, or short), because that could result in a loss of information and give unexpected results.

So when you call m1(10, 10) with ints, and the compiler can only find m1() defined to take narrower arguments (like bytes or shorts), then it will give an error saying that it cannot find the requested method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic