In the code line
editText.setText(firstnum + secondnum + "");
Can anyone explain to me why there are double quotes at the end?
In the code line
editText.setText(firstnum + secondnum + "");
Can anyone explain to me why there are double quotes at the end?
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".
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));
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
setText wants a String.
if you want to get a String from an int you can use String.valueOf(i)
or i+""
.