> 文章列表 > 理解指定的System.out.println()

理解指定的System.out.println()

理解指定的System.out.println()

如何理解指定的System.out.println()

1 源码分析

1.1 System部分源码的分析


/* The <code>System</code> class contains several useful class fields* and methods. It cannot be instantiated. <p>Among the facilities provided by the <code>System</code> class* are standard input, standard output, and error output streams;* access to externally defined properties and environment* variables; a means of loading files and libraries; and a utility* method for quickly copying a portion of an array. @author  unascribed* @since   JDK1.0*///System 是 java.lang类包中的一个,其中注意的是final的存在public final class System {/* register the natives via the static initializer. VM will invoke the initializeSystemClass method to complete* the initialization for this class separated from clinit.* Note that to use properties set by the VM, see the constraints* described in the initializeSystemClass method.*/private static native void registerNatives();static {registerNatives();}...
}

1.2 out 源码的分析

public final static PrintStream out = null;// 分析:其中的final static 修饰之后不能够改变类的方法,out是对象
/
*  1.out 是System中的一个静态的数据成员,而且这个成员是 java.io.PrintStream 类的引用
*  2.out通过static 修饰后,所以能够直接的使用类名 + 属性名称的方式进行调用,也就是System.out
*  3.out的真实的类型实际上是PrintStream 对象,因为是静态的,所以不需要创建爱你任何的东西,既不需要创建System类的对象。
*/

1.3 println源码的分析

  1. println() 就是 java.io.PrintStream 类中的一个方法,它的作用是向控制台输出信息
  2. 里面有很多的重载的方法,这样就保证了任意的东西都进行输出

/* Prints an Object and then terminate the line.  This method calls* at first String.valueOf(x) to get the printed object's string value,* then behaves as* though it invokes <code>{@link #print(String)}</code> and then* <code>{@link #println()}</code>. @param x  The <code>Object</code> to be printed.
*//
*  该方法的参数的类型实际上就是Object的类型,能够适用于多个类型
*/
public void println(Object x) {String s = String.valueOf(x);synchronized (this) {print(s);newLine();}
}

2. 总结

2.1 关于println()方法

  1. 对于该方法的重载,存在多种的格式,其中有的是对于基本数据类型、String数据类型的输出的方式、以及Object类型的输出结果类型。
  2. java打印的输出,会自动调用参数的toString方法,输出内容时的toString方法的返回值。

public class SystemTest {public static void main(String[] args) {char[] chars = {'X', 'Y'};System.out.println("char1"+chars);}
}//运行的结果:
char1[C@6d6f6e28// 分析:对于输出的格式,因为加上的是双引号,所以在调用的时候,自动调用println(String),也就是String类型,输出的格式是xxxx@XXXXX的格式

2.2 关于print方法

public void print(String s) {if (s == null) {s = "null";}write(s);
}
// 表示的是输出需要的内容,不进行换行的操作