Java - What is the result of boolean + int + string

Question

Consider the following piece of code:

  
int num = 1; 
boolean b = false; 
String str1 = "abc"; 
String str2 = b + num + str1;
  


Click to view the answer

The last line in this snippet of code will generate a compile-time error. 
String str2 = b + num + str1; // A compile-time error

Note

Since neither b nor num is a string, the first + operator from the left in b + num + str1 is not a string concatenation operator.

Its operands are of type boolean (b) and int (num). An arithmetic addition operator (+) cannot have a boolean operand.

The presence of a boolean operand in the expression b + num caused the compile-time error.

A boolean cannot be added to a number.

The + operator works on a boolean as a string concatenation operator if another operand is a string.

To correct the above compile-time error, you can rewrite the expression as shown:

int num = 1; 
boolean b = false; 
String str1 = "abc"; 
str2 = b + (num + str1);     // Ok. Assigns "false15faces" to str2 
str2 = "" + b + num + str1;  // Ok. Assigns "false15faces" to str2 
str2 = b + "" + num + str1;  // Ok. Assigns "false15faces" to str2 

Demo

public class Main {
  public static void main(String[] args) {

    int num = 1; 
    boolean b = false; 
    String str1 = "abc"; 
    String str2 = b + (num + str1);      
    System.out.println(str2);/* ww w. ja  v a2  s.c  o m*/
    str2 = "" + b + num + str1;
    System.out.println(str2);
    str2 = b + "" + num + str1;
    System.out.println(str2);
    
  }
}

Result

Related Quiz