Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If user passes a primitive type argument to println(), what exactly happens behind the scene?

Tags:

java

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?

like image 689
ngesh Avatar asked Dec 02 '22 01:12

ngesh


1 Answers

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.

like image 154
Joachim Sauer Avatar answered Apr 05 '23 23:04

Joachim Sauer