double that I converted into String adding int type

This is very weird. The following is the code:

 public static void main(String [] args) {
  double db = 56.00;
  String st = String.valueOf(db);
  System.out.print(st+3);
 }

The output that I get is

56.03

First, how come a String adding an int?Second, how is this possible that 56.00 + 3 is is 56.03?

Jon Skeet
people
quotationmark

You're performing string concatenation. The value of st is "56.0", and then you're performing a concatenation of that and the int 3, giving a result of "56.03".

The string concatenation + operator is described in JLS 15.18.1. It starts with:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

And JLS 5.1.11 includes:

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):

[...] If T is byte, short, or int, then use new Integer(x).

[...] Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

In other words, your program in this case is basically:

double db = 56.00;
String st = String.valueOf(db); // "56.0"
System.out.print(st + new Integer(3).toString()); // "56.0" + "3" = "56.03"

people

See more on this question at Stackoverflow