1

Why does this treat 100 as an int? Why not as a byte or short?

System.out.print(100);

I read this somewhere:

The compiler chooses the method that has the closest type of the argument in order of the implicit casting.

I don't understand what it means by "closest". Is it to do with the memory it takes in RAM or something?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Poobean
  • 27
  • 4
  • 3
    Does this answer your question? [How JVM finds method (parameter with the closest matching) to call in case of function overloading](https://stackoverflow.com/questions/17999480/how-jvm-finds-method-parameter-with-the-closest-matching-to-call-in-case-of-fu) – rph May 29 '20 at 02:52
  • 1
    this isn't complicated, just read the `JLS`. it's not a very fun read, but will answer your question – Eugene May 29 '20 at 03:00
  • 3
    I believe this has more to do with how the compiler interprets the literal `100` and not so much about method overloading. [Take a look at this SO answer about numeric literals in Java](https://stackoverflow.com/a/5193919). `100` is treated as an `int` even though it could technically fit in a `byte`. – roadkill May 29 '20 at 03:02
  • 2
    I think integer literal in Java is int by default. – MIKEC May 29 '20 at 03:11
  • As `System.out.print(byte)` and `System.out.print(short)` don't exist, and as `100` isn't a byte or short literal, it is difficult to see how your confusion arises, or what you think this has to do with method overloading. – user207421 May 29 '20 at 03:17
  • It's like MIKEC said: integer literals in Java are `int` by default and `long` if `int` can't store it. – akuzminykh May 29 '20 at 03:20
  • @akuzminykh The last part of your comment isn't correct. An explicit '`L` is required. – user207421 May 29 '20 at 03:27
  • @user207421 Yes, right. Thanks for pointing out. – akuzminykh May 29 '20 at 03:31

0 Answers0