【问题标题】:Order of prints with string concatenation [duplicate]字符串连接的打印顺序[重复]
【发布时间】:2018-08-26 17:28:06
【问题描述】:

为什么会打印下面的代码

float called long called 20.0 21

而不是

float called 20.0 long called 21

代码如下:

public class Test5 {
    static float fun(int a) {
        System.out.print("float called ");
        return a;
    }

    static long fun(long a) {
        System.out.print("long called ");
        return a;
    }

    public static void main(String[] args) {
        System.out.println(fun(20) + " " + fun(21L));
    }
}

【问题讨论】:

  • 你不返回 String "float called #" 你打印 float called 并返回 #。同样与long called.... 所以打印味精 1. 打印味精 2. 然后打印味精 3. 不打印一个味精。此外,您正在使用 int 调用您的 float 函数。
  • 如果你能解释一下你在哪个部分有困难就好了。目前还不清楚您想要解释哪一部分。是方法重载吗? main 是如何工作的? println 是如何工作的?或者为什么它输出一个带小数点的浮点数?或者21l 是什么意思(顺便说一句。请使用大写的L,看起来像1 否则)?或者,+ 在字符串上的含义可能是什么?或者+ 与数字和字符串一起使用时如何工作?

标签: java string-concatenation operator-precedence


【解决方案1】:

System.out.println(fun(20)+" "+fun(21l)); 被传递一个String,这是连接fun(20)fun(21l) 返回的值的结果。因此,这两个方法在println 语句之前执行,每个都打印自己的String

  • 第一个 fun(20) 打印“float called”并返回 20.0
  • 然后fun(21l) 打印“long call”并返回 21
  • 最后System.out.println(fun(20)+" "+fun(21l)); 打印出“20.0 21”

【讨论】:

    【解决方案2】:

    这是一个方法重载的例子。这个例子表明一个类可以有多个同名的方法。

    这里列出了更多示例: https://beginnersbook.com/2013/05/method-overloading/

    【讨论】:

    • 如果您在此处包含一些示例,那就太好了。答案应该是独立的,无需寻找其他地方。将外部链接作为参考很好,但仅适用于想要了解更多信息的感兴趣的读者。不是理解答案或术语方法重载所必需的。
    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2016-04-21
    • 2014-02-01
    • 1970-01-01
    相关资源
    最近更新 更多