How does (Float value + Integer value + long value) give unexpected results?

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

I've seen the code above. I tried to find the reason for this unexpected exit, but with no success. Please provide links or link or explanation.

+3


source to share


4 answers


Adding important point to other answers here:

Whenever you do String concatenation, a method is called for each element in the concatenation toString()

. So your elements to be concatenated are



"Result is ", l, f, and i

      

For primitives, Autoboxing first converts them to Wrapper classes and toString()

each method gets called and what happened.

+1


source


This is a String

concatenation

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

      

Gives

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

      



Better group your arithmetic calculations:

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

      

You can find more details here: String Concatenation Operator +

+4


source


You don't add a number, you print it, because the default operation when placing an object System.out.println

is to call its method toString()

. So you are typing l.toString() + f.toString() + i.toString()

.

if you want to display the amount you should use:

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

      

+1


source


Concatenating a string with any primitives or number objects converts them to String using the method toString()

:

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

      

To perform the evaluation before concatenating the strings, you must place the evaluation expression between parentheses:

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

      

+1


source







All Articles