2014-12-01 21 views
2

这更清晰而不是怀疑。在下面的:通过System.out.println转换为Integer Wrapper类对象的int值?

int a = 10; 
System.out.println(a); 

我断定的是,变量“a”的基本类型int首先被转换到Integer包装类对象,然后toString方法被调用为该Integer对象返回的整数值的字符串形式到println方法。我的理解是否正确?如果不是什么正确的解释?

回答

6

你错了。它可以处理int,看到docs*

public void println(int x) 

*始终:)

+0

Yup..thats正确的解释。我对重载的方法“public void println(Object x)”感到困惑,在这种情况下默认的toString被调用。 – Singularity 2014-12-01 19:51:39

+0

@ user2580086当你想打印你自己的对象时,你完全正因为这个原因而重写'toString'。 – Maroun 2014-12-01 19:52:39

0

不,我认为这不是你解释的方式。

System.out是PrintStream类(存在于java.io包中)的静态引用,它具有直接打印基元的方法!

1

如果你检查System.out的类型,你会发现它是一个PrintStreamRead the docs.

报价:

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. 

所以,不,不转化为Integer完成。 int准确地匹配上述方法的签名,以便调用该方法。内部发生的情况未指定,但可能直接调用Integer.toString(),转换为Integer

0

准确地说,它实际上使用了String.valueOf(int)方法。

这是源代码,从PrintStream

/** 
* Prints the string representation of the int {@code i} followed by a newline. 
*/ 
public void println(int i) { 
    println(String.valueOf(i)); 
}