If user passes a primitive type argument to println()
, what exactly happens behind the scene? e.g.
int i =1;
System.out.println("My Int"+i);
//and in
System.out.println(i)
How does it print "My Int 1"
and "1"
, even though it needs a String
object?
updated..
What I think is AutoBoxing
comes into play. Is that true, too?
System.out
is a PrintStream
. PrintStream
has plenty of overloads for println
, suche as println(int)
or println(String)
, so the compiler will simply choose the most appropriate.
What happens in your first example is that you construct a new String
using string concatenation of "My Int"
and i
and pass that String
to the println
method. That method needs not know how to "print concatenated String
values", because it simply gets a normal String
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With