System.out.print()是传引用还是值?

6点A君 2017-03-03 11:22:22
int i = 6;
System.out.println(i++);
System.out.println(i);
i是基本类型,所以传递的时候应该是按值传递,也就是复制一份i传到println方法,所以i++对原始i没有影响。
但实际结果i的值为7。
我想知道我哪一步分析出问题了?
附上println的源代码:

/**
* Prints an integer and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(int)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>int</code> to be printed.
*/
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
...全文
206 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
System.out.println(i++);你可以把它看成两步,先取的是i++的值,再打印,这样,里面的i++就应当执行完才打印,故+1
  • 打赏
  • 举报
回复
方法调用传递参数是值传递, public void println(int x) { synchronized (this) { print(x); newLine(); } } 把i的值赋值给了x,但是最终是i进行了+1, ++操作只是java语言中一个的语法糖,在源代码编译成字节码以后会把++这一条语句拆分成多个指令, System.out.println(i++);这一句只是人能看懂的简写,其实实际执行 的是: 0: bipush 6 2: istore_1 3: getstatic #2 // Field java/lang/System.out:Ljav a/io/PrintStream; 6: iload_1 7: iinc 1, 1 10: invokevirtual #3 // Method java/io/PrintStream.prin tln:(I)V 13: getstatic #2 // Field java/lang/System.out:Ljav a/io/PrintStream; 16: iload_1 17: invokevirtual #3 // Method java/io/PrintStream.prin tln:(I)V 20: return 从2,7,16可以看出来i进行了+1操作并且传递给第二个System.out.println(i);
jiajing1990_ 2017-03-03
  • 打赏
  • 举报
回复
事实上你有两个步骤, 第一步要i++ 第二部输出i 不要以为放在printl()里面就只是输出哦,他是执行了两个步骤的

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧