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

Asked by: Julian741 | Posted: 28-01-2022

Answer 1

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
"" + 5            <-- string concatenation - will produce "5"

Answered by: Arthur549 | Posted: 01-03-2022

Answer 2

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();

        long estimated = 1l;
        long time = speeds.size() + estimated;
        System.out.println(time); // Prints out 3

Answered by: Thomas772 | Posted: 01-03-2022

Similar questions

java - String variables concatenation

I have few lines of code as following. Here my question is which one to prefer ? public static String convertMapToString ( Map &lt; String, String &gt; map ) { StringBuilder str = new StringBuilder ( 200 ) ; for ( Entry &lt; String, String &gt; entry : map.entrySet ( ) ) { str.append ( entry.getKey() + " = " + entry.getValue() ) ; } return str.toString() ; } ...

java - Is there an elegant work around to concatenation?

I am writing a mad libs program for fun and to just program something. The program itself is pretty straight forward, but I find myself resorting to several concatenations due to the nature of the game where you place user given words into a sentence. Is there an elegant work around to resort to less concatenations or even eliminate them for something more efficient? I know in the end it will make no difference if I use co...

Inserting a Java string in another string without concatenation?

This question already has answers here:

java - Slow string concatenation over large input

I've written an n-ary tree ADT which works fine. However, I need to store its serialization in a variable a calling class. eg. DomTree&lt;String&gt; a = Data.createTreeInstance("very_large_file.xml"); String x = a.toString(); I've written method which serves the purpose exactly how I need it, but on very large inputs it takes forever (20mins on a 100MB xml file) - I have timed th...

data structures - A collection that represents a concatenation of two collections in Java

Is there a class that represents the concatenation of a collection with another collection? This class should be a Collection in itself, and should delegate all methods to the underlying (inner) collections - no extra memory should be allocated, nor any of the original collections modified. Example usage: Collection&lt;String&gt; foo = ... Collection&lt;String&gt; bar = ... // this should be O(1) m...

Log4j Maximum String Length OR Java String Concatenation Error?

Running on Solaris 10, I am having problems when I hit a LOG.debug statement using an Apache Log4j logger. The basic scenario is demonstrated in the following code block: public class MyClass { private static final Logger LOG = Logger.getLogger(MyClass.class.getName()); private LinkedHashMap&lt;String, String&gt; myMap = new LinkedHashMap&lt;String, String&gt;(); public static void main...

java - Help in debugging the string concatenation code

I have a code to concatenate strings. However, for some reason, the final string is not a combination of the required strings. Consider the following code : //cusEmail is of type String[] String toList = ""; for(i=0; i &lt; cusEmail.length - 1; i++) { toList.concat(cusEmail[i]); toList.concat("; "); System.out.println(cusEmail[i]); } toList.concat(cusEmail[i]); System.out.println(toList);

How Java do the string concatenation using "+"?

I read about the way Java works with += operator, using StringBuilder. Is it the same with a ("a" + "b") operation?

Improving performance of string concatenation in Java

This question already has answers here:

java - Are strings created with + concatenation stored in the string pool?

For instance String s = "Hello" + " World"; I know there are two strings in the pool "Hello" and "World" but, does: "Hello World" go into the string pool? If so, what about? String s2 = new String("Hola") + new String(" Mundo"); How many strings are there in the pool in each case?

concatenation output problem (toString Array) - java

I am trying to display the output as "1(10) 2(23) 3(29)" but instead getting output as "1 2 3 (10)(23)(29)". I would be grateful if someone could have a look the code and possible help me. I don't want to use arraylist. the code this // int[] Groups = {10, 23, 29}; in the constructor public String toString() { String tempStringB = ""; String tempStringA = " "; String tempStringC = " ";...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)