0

I was trying out a few things just now in Android Studio and the following piece of code worked without a compiler or runtime error and gave the right answer.

cmessage1.setText(AppData.hcptotal + 2.3/7 + " HCP");

Appdata.hcptotal is an integer with a value of 10. The text displays as 10.32857142857143 HCP so this setText method is allowing integers and doubles to be mixed together and to participate in mathematical calculations AND being mixed with strings! I didn't know this was possible. The official documentation doesn't appear to show that this is allowed. And other posts on this site indicate that the.setText method parameter must be a string.

Can anyone shed any light on this extraordinarily versatile (and new?) facility?

John of York
  • 93
  • 2
  • 12
  • The parameter becomes a string before it is passed to the method. `int` becomes `Integer` through autoboxing then toString() is called. This is extremely common in java. – takendarkk Dec 06 '15 at 21:05
  • Because you have strings in your expression, result will be string too, it's not something related to android studio, this is because strings concatenation works like this. – dtx12 Dec 06 '15 at 21:09
  • I don't get that, dtx12. You're saying that because there is a string in the expression, that allows you to concatenate a string to the result of a floating point calculation. Are you therefore saying that if I remove the + " HCP" it won't work? – John of York Dec 06 '15 at 21:57

1 Answers1

0

The setText() method allows a CharSequence variable parameter. CharSequence is an arbitrary variable type. So it can be a Double,String,Float,etc but the method automatically convert these values all into one CharSequence variable (CharSequence VS String in Java). Pretty much when you mix all these multiple variable types together in this method, it automatically thinks it is a CharSequence.

Community
  • 1
  • 1
Mekkah08
  • 36
  • 3
  • Thanks, Mekkah08. I would understand it if the parameter was 0.333 + "HCP" and that it converted the 0.333 into "0.333". But it goes way beyond that by accepting a floating point calculation, evaluating that, then converting the answer to a string. I've also tried removing the + "HCP". When I do this, I get a compiler error "Cannot resolve method 'setText(double)'". This supports dtx12's assertion that it works as it does because there is a string somewhere in the parameter. It does work if the parameter is a complex mathematical expression so long as you add + "" to it. Quite amazing. – John of York Dec 06 '15 at 22:50
  • And I have further discovered that if x is an integer and y is a double, then: – John of York Dec 06 '15 at 23:26
  • Actually from looking at your code statement again that is pretty AMAZING. By taking out the "HCP" string in the method parameter field, it seems it doesn't satisfy the condition of having a least string present in the parameter field. – Mekkah08 Dec 07 '15 at 03:35