-3

Why can't i do this? I understand that concatenation of a int and a string or with boolean,(true or false) is possible, but not an addition of boolean with an int.

What exactly happens when u add a int with a boolean? Why does it show an error?

System.out.println(a.length() + a.startsWith("a"));

i also understand that the work around for this code is

System.out.println(""+a.length() + a.startsWith("a"));

which uses concatenation.

Jayeloh
  • 13
  • 3
  • That's not a workaround. That's the correct way to do what you want to do. – zubergu Oct 05 '15 at 10:12
  • There is no standard definition of what a `boolean` or a `Boolean` and an `int` should do. For String it is just a convenice method. – Peter Lawrey Oct 05 '15 at 10:15
  • @zubergu, using `(""+a.lenght())` it's not only a wrong way to do it, but also a really ugly workaround. – Jordi Castilla Oct 05 '15 at 10:18
  • @zubergu, that *is* a workaround, it's forcing Java to interpret the expression as a string but it's not clear what the intent is. There are better ways to accomplish this. – Andi Emma Davies Oct 05 '15 at 10:19

3 Answers3

2

Because the + operation has different functions.

In the first example you try Number + Boolean. And this doesn't make sense, so the compiler gives an error.

In the second example you try String + Number (which is allow as String - concentation and returns a String). Afterwards you try String + boolean (which is also allowed)

Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38
  • Yes. Java knows that you are performing an arithmetic operation when you do a + operation on two numbers (integers, doubles, etc). Java also knows you are performing a concatenation when you have two Strings against a + operation. Like Denis said though, Number + Boolean is not immediately obvious and so Java throws an error indicating you need to be more explicit. – shrmn Oct 05 '15 at 10:30
1

What exactly happens when u add a int with a boolean? Why does it show an error?

Because the + operator is not defined for those operands.

Manu
  • 1,474
  • 1
  • 12
  • 18
0

Use the Boolean.toString() static method to get a string representation of the Boolean value:

Boolean.toString(a.startsWith("a"));
Andi Emma Davies
  • 298
  • 4
  • 19