Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to concatenate primitive type values into a String

Tags:

java

boolean

So I'm fairly new to programming and I just started taking a class at school. We were told to make a program that will print:" H3110 wor1d 2.0 true " only using the variable types char, int, byte, float, and boolean. This is what I was able to come up with.

public class Homework3 {

  public static void main(String[] args) {

    char ab = 'H';
    int cd = 3110;

    char ef = 'w' ;
    byte gh = 0;
    char ig = 'r'; 
    char l = '1'; 
    char d = 'd';
    float mn = 2.0f;
    char op = ' ' ;
    boolean qr = false;



   String x = (ab + cd + ef + gh + ig + l + d + mn + op + qr);
   System.out.println(x);
 }
}   

However, I keep getting an error message when I try to run it through.

  String x = (ab + cd + ef + gh + ig + l + d + mn + op + qr);
                                                    ^
 first type:  float
 second type: boolean
1 error

I don't know what I'm doing wrong and was wondering if there's an easier way to write this program. Am I making it more complicated than it really is?

like image 232
Jianna Avatar asked Mar 10 '26 22:03

Jianna


1 Answers

+ actually refers to two different operators in Java: numeric addition, and string concatenation. Which it thinks you want to use depends on the context (in other words, the types of the two operands).

In each of your uses of +, the compiler is treating this as addition (of two numbers), not string concatenation. char, byte, int, and float are all numeric types (for char, its numeric value is usually its unicode codepoint).

However, boolean is not a numeric type so it fails at that point.

You can force this into String concatenation by starting with a "":

String x = "" + ab + cd + ef + gh + ig + l + d + mn + op + qr; // "H3110w0r1d2.0 false"

Or by converting the first value to a String first:

String y = String.valueOf(ab) + cd + ef + gh + ig + l + d + mn + op + qr;
like image 132
Mark Peters Avatar answered Mar 13 '26 14:03

Mark Peters