Singularity
Singularity

Reputation: 89

int value converted to Integer Wrapper class object with System.out.println?

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

Answers (4)

markspace
markspace

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

jmm
jmm

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

Sarthak Mittal
Sarthak Mittal

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

Maroun
Maroun

Reputation: 95958

You're wrong. It can handle int, see the docs*:

public void println(int x)

* Always :)

Upvotes: 6

Related Questions