Ad

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

Ad

Answer

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
    }
}
Ad
source: stackoverflow.com
Ad