-4

In the code line

editText.setText(firstnum + secondnum + "");

Can anyone explain to me why there are double quotes at the end?

sophin
  • 583
  • 5
  • 11
  • Because `setText()` is expecting string – B001ᛦ Apr 30 '19 at 13:58
  • If `firstnum` and `secondnum` are floats, then `(firstnum + secondnum)` is a float. But `(firstnum + secondnum + "")` is a string. The method you're calling expects a string. – khelwood Apr 30 '19 at 13:58
  • @B001ᛦ - nope. `setText()` is also accepting integers. but even if OP would use ints instead of floats it is still now what he needs. – Marcin Orlowski Apr 30 '19 at 14:07

4 Answers4

1

firstnum and secondnum are both of type Float it seems so adding them will result in a Float, the setText() method takes a String not a Float, when adding + "" java will automatically convert the addition of the 2 Floats to a string, think if you had:

editText.setText(5 + " apples");

Then java will think you want to have a string "5 apples" that is why it convert the int before the string to a string representation then append it to " apples".

anthony yaghi
  • 532
  • 2
  • 10
1

This is to enforce conversion of your integer value (result of firstnum + secondnum) to string, which is what setText() requires as argument. There's also setText() that accepts int (you are using floats so that's not the case anyway) but that int will be used as ID of string resource which is not what you want, hence need of conversion to string. It's also just less typing. It's basically equivalent of replacing:

editText.setText(firstnum + secondnum + "");

with:

editText.setText(String.valueOf(firstnum + secondnum));
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • 2
    On the other hand, the second example makes it far more clear what is going on. If it had been written the second way, the OP would never have had to ask their question, as it would have been plainly obvious. Sometimes "less typing" is a false economy. – Brian Goetz Apr 30 '19 at 14:02
  • Sure, there's always tradeof i.e. In this particular case I'd just put `"" + ...` first so it's more clear what's going on. – Marcin Orlowski Apr 30 '19 at 14:03
0

The + is an overloaded operator when it is between two numbers that it will add them but adding the "" will make it in a string

-1

setText wants a String. if you want to get a String from an int you can use String.valueOf(i) or i+"".

dan1st
  • 12,568
  • 8
  • 34
  • 67