Home > Enterprise >  Question about the behavior of toString on integers
Question about the behavior of toString on integers

Time:12-29

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?*/
}}

CodePudding user response:

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.

CodePudding user response:

This is because of the way Java handles strings. When you try to 'add' anything to a string, it results in a 'concatenate' operation. Here is a good article that explains it https://www.geeksforgeeks.org/addition-and-concatenation-using-plus-operator-in-java/

For example:

int n1 = 10;
int n2 = 20;
int n3 = 30;
int n4 = 40;

// Below statement will print the sum 100 as all operands are `int` 
System.out.println(n1   n2   n3   n4); 

// Introducing a string changes the behavior
System.out.println(n1   ""   n2   n3   n4); // Will print 10203040 (concatenated)

Also worth noting is that the expressions are evaluated from left-to-right. See below:

System.out.println(n1   n2   ""   n3   n4); // Will print 303040
  • Related