Reputation: 89
This more of a clarity than a doubt. In the following :
int a = 10;
System.out.println(a);
What I conclude is that variable 'a' of the primitive type int
is first converted to the Integer
Wrapper class object and then toString
method is invoked for that Integer
object which returns the integer value in String form to the println
method. Is my understanding correct? If not what is the correct explanation?
Upvotes: 2
Views: 444
Reputation: 11020
If you check the type of System.out
, you'll see it's a PrintStream
. Read the docs.
Quote:
public void println(int x)
Prints an integer and then terminate the line. This method behaves
as though it invokes print(int) and then println().
Parameters:
x - The int to be printed.
So, no, no conversion to Integer
is done. The int
matches the signature of the above method exactly, so that method is called. What happens internally is unspecified, but it probably calls Integer.toString()
directly, with out a conversion to Integer
.
Upvotes: 1
Reputation: 1064
To be precise, it actually uses the String.valueOf(int)
method.
This is the source code, from PrintStream
/**
* Prints the string representation of the int {@code i} followed by a newline.
*/
public void println(int i) {
println(String.valueOf(i));
}
Upvotes: 0
Reputation: 6104
No i think it's not the way you explained.
System.out is a static reference of PrintStream class (present in java.io package) which has methods to print primitives directly!!!
Upvotes: 0