Search code examples
javatostring

Question about the behavior of toString on integers


Why does an integer alone in returning a String not work, but it does work when adding a String next to it? Does it suddenly convert the integer like with something as (Integer.toString())?

public class Car {
String brand;
String model;
int hp;

@Override
public String toString() {
    return hp; //this doesn't work because it wants to return int.
  //return hp + brand; does work for some reason.
  /*return Integer.toString(hp); could it be doing something like this behind 
  the scenes?*/
}}

Solution

  • According to the Java Language Specification:

    String contexts apply only to an operand of the binary + operator which is not a String when the other operand is a String.

    The target type in these contexts is always String, and a string conversion (§5.1.11) of the non-String operand always occurs.

    Which means that when you do hp + brand, since brand is a String the rule above kicks in, hp gets converted to a String and concatenation occurs, resulting in a String.