简体   繁体   English

(浮点值+整数值+长值)如何产生意外结果?

[英]How does (Float value + Integer value + long value) gives unexpected result?

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Float f=new Float(3.1);
                Integer i=new Integer(1);
                long l=2;
                System.out.println("Result is "+l+f+i);
    }
}

Output : Result is 23.11 输出: Result is 23.11

I saw the above code somewhere. 我在某处看到了上面的代码。 I tried to find the reason behind such an unexpected output but no success. 我试图找到这种意外输出背后的原因,但没有成功。 Please give some links or reference or explanation. 请提供一些链接或参考或解释。

Additional Information: System.out.println(l+f+i+" is Result"); 附加信息: System.out.println(l+f+i+" is Result"); gives 6.1 is Result . 给出6.1 is Result That means order of string and numbers has effect on output. 这意味着字符串和数字的顺序对输出有影响。

This is String concatenation, 这是String连接,

System.out.println("Result is "+l+f+i);

Gives

System.out.println("Result is "+"2"+"3.1"+"1");

Better group your arithmetic computation : 更好地分组算术计算:

System.out.println("Result is "+(l+f+i));

You may find more details here : String Concatenation Operator + 您可以在此处找到更多详细信息: String Concatenation Operator +

You're not adding the number, you're printing them, because the default operation when placing an object in a System.out.println is to call his toString() method. 您没有添加数字,而是打印它们,因为在System.out.println放置对象时的默认操作是调用他的toString()方法。 So you're printing l.toString() + f.toString() + i.toString() . 所以你要打印l.toString() + f.toString() + i.toString()

if you want to display the sum, you have to use: 如果要显示总和,则必须使用:

Float f=new Float(3.1);
Integer i=new Integer(1);
long l=2;
System.out.println("Result is "+ (l+f+i));

Concatenating a String with any number primitives or objects convert them to String with their toString() method : 将String与任何数字基元或对象连接,使用它们的toString()方法将它们转换为String:

System.out.println("Result is "+l+f+i); 

To perform the computation before the string concatenation, you should put the computation expression between parenthesis : 要在字符串连接之前执行计算,您应该将计算表达式放在括号之间:

 System.out.println("Result is " + (l+f+i)); 

Adding an important point to the other answers here: 在这里为其他答案添加一个重点:

Whenever you do String concatenation, the toString() method is called for each elements in the concatenation. 每当进行字符串连接时,都会为连接中的每个元素调用toString()方法。 So, your elements to be concatenated are, 那么,要连接的元素是,

"Result is ", l, f, and i

For, primitives, Autoboxing would first convert them to Wrapper classes and toString() method of each would be called and that's what happened. 对于原语,Autoboxing首先会将它们转换为Wrapper类,并且每个都会调用toString()方法,这就是发生的事情。

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

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