Search code examples
javastringvariablesconcatenationprimitive

String Contatenation with primitives in java


I just recently started learning Basics in Java, and was testing around initializing a string variable by concatenating primitive variables.

public class Main{
    public static void main(String[] args){
        byte lbyte = 3;
        short lshort = 1;
        int lint = 1;
        long llong = 0;
        float lfloat = 2.0f;
        double ldouble = lfloat;
        char lchar = 'H';
        boolean lbool = true;
        String lstring = " w0r1d ";
        String lOutput = lchar+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;
        System.out.println(lOutput);
    }
}

In this code, my objective was to create a string that would output:

H3110 w0r1d 2.0 true

However, when i run it the output is: 77 w0r1d 2.0 true

The unexpected result is the 77, while the rest is fine. Even if i would assume the number variables would get added, it would only be a total of 5. The variable lchar is also apparently "absorbed" into the numbers.

Where did the 77 come from and what happened to the H in lchar?

Edit: the goal is to use as much primitive variables as possible in the concatenation.

Edit2: Thanks for all the helpful answers.


Solution

  • The ASCII / Unicode value for 'H' is 72. The additions are processed left to right, so lchar + lbyte is 'H' + (byte) 3 which is equal to 72 + 3.

    You'll only get a string result from + if one of the operands is a string. That doesn't happen until you finally concatenate lstring, which explains why all of the numerical (and the char) variables are added together to get 77. Everything to the right of lstring is concatenated one by one, each converted to a string, since the left hand operands of all those +s are all strings at that point.

    A quick fix is to start with "" to force everything to be done with strings.

    String lOutput = ""+lchar+lbyte+lshort+lint+llong+lstring+ldouble+' '+lbool;