Java在输出String和方法返回时,为什么方法首先返回输出? [英] Java When outputting String and method return, why does method return output first?

查看:171
本文介绍了Java在输出String和方法返回时,为什么方法首先返回输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果字符串"Mult"test1(4)方法调用之前,为什么该方法在字符串之前输出?为什么它会跳出输出方法的第一部分的形式,然后离开方法以输出字符串,然后返回到方法以输出方法的返回值?

In the code below, if the string "Mult" comes before the test1(4) method call, why does the method output before the string? And why does it bounce form outputting the first part of the method, then leaves the method to output the string, then returns to the method to output the method's return value?

代码:

public class Scratch{
  public static void main(String[] args){
    System.out.println("Mult:" + test1(4));
  }

  public static int test1(int n){
    System.out.println("N:" + n);
    return n*2;
  }
}

输出:

N:4
Mult:8

推荐答案

要注意的第一件事是当您将+与两个操作数一起使用时,其中两个操作数之一是String,即表达式的结果是String.

The first thing to note is when you use the + with two operands where one of the two operands is a String, the result of the expression is a String.

因此,在以下方法调用表达式中

Therefore, in the following method invocation expression

System.out.println("Mult:" + test1(4));

您正在调用 PrintStream#println(String) ,因为out是类型为PrintStream的变量.请注意,该方法如何接受单个String参数.因此,必须从

String串联中解析String

you are invoking the PrintStream#println(String) since out is a variable of type PrintStream. Note how the method accepts a single String argument. Therefore, the String has to be resolved from the String concatenation of

"Mult:" + test1(4)

为此,必须执行test1(4)方法.

For that to happen, the test1(4) method has to be executed.

public static int test1(int n){
    System.out.println("N:" + n);
    return n*2;
}

此方法再次使用PrintStream#println(String),但带有参数

This method again uses PrintStream#println(String) but with the argument

"N:" + n

这是另一个产生String值的String串联

This is another String concatenation that produces the String value

"N:4"

用于此特定调用.然后,将产生的String值用作println(..)方法的参数,该方法会将其输出到程序的标准输出中.

for this particular invocation. The produced String value is then used as an argument to the println(..) method which outputs it to your program's standard output.

然后该方法返回值8,因为4 * 2 = 8.

The method then returns the value 8, since 4 * 2 = 8.

该返回值是调用test1(4)方法的值.所以

That return value is the value of invoking the test1(4) method. So

System.out.println("Mult:" + test1(4));

等同于

System.out.println("Mult:" + 8);

然后发生String串联,发生变化

Then String concatenation occurs, transforming

"Mult:" + 8

放入String

"Mult:8"

然后,该String用作println(..)方法的单个参数,该方法将其输出到程序的标准输出中.

That String is then used as the single argument to the println(..) method which outputs it to your program's standard output.

这篇关于Java在输出String和方法返回时,为什么方法首先返回输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆