Question

What do double quotes mean in a Java expression?

I have:

"2 + 2" + 3 + 4

"hello 34" + 2 * 4

1 + ""

Can someone explain how these expressions are evaluated, and what the purpose of the last one is?

Was it helpful?

Solution

anything inside " " will become String. and string + Int = String .for example,

"2 + 2" + 3 + 4

you will get 2 + 234

in your question,

"2 + 2" + 3 + 4 +"hello 34" + 2 * 4 //i added '+' between '4' and 'hello' since there is an error in expression

will be evaluated like this:

1. output = "2 + 2" + 3 + 4 +"hello 34" + 2 * 4
2. output = "2 + 2" + 3 + 4 +"hello 34" + 8 //operation '*' evaluated first
3. output = "2 + 23" + 4 +"hello 34" + 8
4. output = "2 + 234" +"hello 34" + 8
5. output = "2 + 234hello 34" + 8
6. output = "2 + 234hello 348"

OTHER TIPS

The + operator has two meanings in Java.

  • When both operands are numeric1, it means arithmetic addition.
  • When either operand has type String, it means string concatenation.

In the string concatenation case, a non-string argument is first to a string. The process is called string conversion and is specified in JLS 5.11.1. The procedure is as follows:

  • A primitive type is converted to a string as if it was boxed, and the toString() was called on the boxed value.
  • A null is converted to the string "null".
  • Any other reference type is converted by calling its toString().

The complete semantics of + concatenation are specified in JLS 15.8.1.


@Baby's answer explains how this works for the first example in the Question, and the second example is similar. (Note that * has a higher precedence than + so 2 * 4 is evaluated as a multiplication and 8 is then used in the concatenation.)

The third example is a common Java idiom for converting a number to a String. Thus

  1 + "" -> "1"        // equivalent to Integer.toString(1)
  1.0 + "" -> "1.0"    // equivalent to Double.toString(1.0)

On the face of it, the versions in comments should be more efficient. Concatenating with "" would appear to be performing an unnecessary concatenation. However, if you read the wording of the spec carefully, it is apparent that the Java compilers are permitted to optimize the first form to the second. It is my understanding that they do ... in recent versions of Java.

Many people consider the ... + "" idiom to be bad practice. However it is common enough that you need to recognize it when you encounter it.


1 - In this context, this means any integral or floating point primitive type, or any of the matching wrapper types. The complete set is byte, short, char, int, long, float, double, java.lang.Byte, java.lang.Short, java.lang.Character, java.lang.Integer, java.lang.Long, java.lang.Float, and java.lang.Double.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top