Sunday, February 13, 2011

Why does addition of long variables cause concatenation?

What does Java do with long variables while performing addition?

Wrong version 1:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??

Wrong version 2:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??

Correct version:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct

I don't get it, why Java concatenate them.

Can anybody help me, why two primitive variables are concatenated?

Greetings, guerda

  • I suspect you're not seeing what you think you're seeing. Java doesn't do this.

    Please try to provide a short but complete program which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample).

    import java.util.*;
    
    public class Test
    {
        public static void main(String[] args)
        {
            Vector speeds = new Vector();
            speeds.add("x");
            speeds.add("y");
    
            long estimated = 1l;
            long time = speeds.size() + estimated;
            System.out.println(time); // Prints out 3
        }
    }
    
    matt b : So what was it about this answer that was correct? What was the author doing wrong?
    furtelwart : Yeah, I was wrong. It was probably a thread problem.
    From Jon Skeet
  • My guess is you are actually doing something like:

    System.out.println("" + size + estimated);
    

    This expression is evaluated left to right:

    "" + size        <--- string concatenation, so if size is 3, will produce "3"
    "3" + estimated  <--- string concatenation, so if estimated is 2, will produce "32"
    

    To get this to work, you should do:

    System.out.println("" + (size + estimated));
    

    Again this is evaluated left to right:

    "" + (expression) <-- string concatenation - need to evaluate expression first
    (3 + 2)           <-- 5
    Hence:
    "" + 5            <-- string concatenation - will produce "5"
    
    From toolkit

0 comments:

Post a Comment