- 1. println输出各类型的结果
- 1.1 int
- 1.2 String+int
- 1.3 char[ ]
- 1.4 String+char[ ]
- 1.5 int[ ]
- 1.6 总结
- 2.用源码分析结果
- 2.1 源码
- 2.2 要点
- 2.3 详细解析
int i = 1; System.out.println(i);
运行结果:
System.out.println("Hello" + i);
运行结果: hello1
1.3 char[ ] char[] c = {'x','y','z'};
System.out.println(c);
运行结果: xyz
1.4 String+char[ ] char[] c = {'x','y','z'};
System.out.println("Hello" + c);
运行结果:Hello[C@123a439b
1.5 int[ ] int[] s = {1,2,3};
1.6 总结
int i = 1;
char[] c = {'x','y','z'};
int[] s = {1,2,3};
System.out.println(i);
System.out.println("Hello" + i);
System.out.println(c);
System.out.println("Hello" + c);
System.out.println(s);
运行结果:
PS:显而易见可以看出使用println方法输出时,基本类型是可以直接输出数值的。但是当数组输出时除了char[ ]数组以外的输出都是格式为xxx@xxx这样的字符串。
源码:
public void println(int x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newline();
}
}
}
public void println(char[] x) {
if (getClass() == PrintStream.class) {
writeln(x);
} else {
synchronized (this) {
print(x);
newline();
}
}
}
public void println(String x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newline();
}
}
}
public void println(Object x) {
String s = String.valueOf(x);
if (getClass() == PrintStream.class) {
// need to apply String.valueOf again since first invocation
// might return null
writeln(String.valueOf(s));
} else {
synchronized (this) {
print(s);
newline();
}
}
}
2.2 要点
首先明确以下几个点:
1、println的实现是根据方法的重载(传入的参数的类型不同)
2、char[ ]数组与其他类型的数组传入的参数是走两条线,其他数组都走的是println(Object object)路线,String类中就是用char[ ]来构造的。
3、String+任意类型都会被传入println(String string)中。
分析:
接下来对以上有xxx@xxx出现的结果做源码分析,第一个为字符串+数组为参数传入方法,走以下路线:
public void println(String x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newline();
}
}
}
当传入参数后进行判断是否符合条件,紧接着执行writeln方法,所以最后展示的是writeln(String.valueOf(“hello”+c)),当你分开执行String.valueOf(“hello”)+String.valueOf( c )时,
你会惊讶的发现并不是一开始所获得那个带有@符号的字符串,此时再来看源码上面所说的字符串加上char[ ]后事传入字符串为参数,而字符串的参数则是传入到了以下这个方法:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
这样就可以很清晰的发现字符串中含有的object又暴露出来了。
/**第一次写完一篇有目录结构的文章属实很菜,没有技术含量,有错误的地方请大佬们指出



