2

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?

4 Answers 4

6

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

public void println(int x)

* Always :)

Sign up to request clarification or add additional context in comments.

2 Comments

Yup..thats correct explanation. I got confused with the overloaded method "public void println(Object x)" in which case the default toString is invoked ..
@user2580086 When you want to print your own object, then you override toString exactly because of that.
1

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.

Comments

0

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!!!

Comments

0

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.