简体   繁体   English

在println中调用println方法

[英]Calling println method within println

I just wrote this code: 我只是写了这段代码:

public class T 
{
  public String toString()
   {
     System.out.println("new line");
     return " "+4;
   }
}

and: 和:

public static void main(String[] args)
{
     T t = new T();
     System.out.println("11"+t);
}

and while I expected it to print 虽然我希望它能打印

11 new line
4

it actually printed: 它实际打印:

new line
11 4

why is that? 这是为什么? What is the order of this printing and what is the logic behind this? 此打印的顺序是什么,其背后的逻辑是什么?

Thanks! 谢谢!

The call for the toString happens before the "11" print. toString的调用发生在“ 11”打印之前。

The reason (like @Tom said), in order to concating the string, It have to create all the pieces first, and then it concating. 原因(如@Tom所说),为了使字符串缩进,它必须先创建所有片段,然后再进行缩进。

Only after the String is full ready - it will go to your screen. 只有在字符串准备就绪后,它才会显示在屏幕上。

When you call a function, Java evaluates all of its arguments before actually going into that function. 调用函数时,Java在实际进入该函数之前先评估其所有参数。 So in you case, it first evaluates "11"+t . 因此,在您的情况下,它首先求值"11"+t Now that calls t.toString(), which writes "new line". 现在调用t.toString(),它会写“换行”。 Then toString returns " 4", and that is concatenated to "11", then println is executed to write "11 4" 然后toString返回“ 4”,并将其串联为“ 11”,然后执行println以写入“ 11 4”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM