Question

We had an odd thing in our logging happen today. Printed is a list of integers and longs separated by commas, like the following code:

public class Main {

    public static void main(String[] args) throws InterruptedException {
        long l = 10;
        System.out.println(l + ';' + "text");
    }
}

The problem was that the ; disappeared from the output.

Was it helpful?

Solution

The problem here is caused by the overload of the + operator. It acts in one way when operating on a String and a long, and another when operating on a char and a long. When one of the operands is a string it will try to cast the other operand to a string if it's not already one and then concatenate the two.

But when the operators are numbers, like int and long, the + operator acts as the normal mathematical plus operator. And since char is a number and nothing else, ';' + l is treated as a numerical operation and thus the output of the code in the question is 69text and not 10;text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top