2

I'have doubt,if im asking wrong please correct me Question is

        String s="hello";
        String s1=' ';//error
        String s2=s+' ';

I know line1 is correct and line 2 is wrong because we can initialize char a= ' '; but am confused in line3 i read + operator in java can be used for concatenation with strings but it accepts characters like ' ' what is the reason ?

4
  • 1
    Because that's how Java is implemented. Commented Dec 10, 2014 at 5:04
  • 2
    Similar to doing s + 5, it's casted to String. For non-primitives, toString() will be called Commented Dec 10, 2014 at 5:05
  • Vince Emigh yes i do Commented Dec 10, 2014 at 5:06
  • 3
    Side note: If s is a String and a and b are integers, be careful with something like s + a + b. This is not the same as s + (a + b). The first one converts each integer to a string and appends the strings in turn. The second one adds the integers first. Commented Dec 10, 2014 at 5:12

3 Answers 3

4

The + operator is heavily overloaded. It takes almost anything.

If either side is a String, then the other will be converted to a String. That works with char as well as for other primitive types. For Objects, toString() is called (after a null-check).

Sign up to request clarification or add additional context in comments.

2 Comments

please explain this too String s2=s+''; is error String s2=s+' '; is works fine String s2=s+'a'; is works
@jenuine It looks like your first example has two single quote marks, i.e. String s2 = s + ''? This just isn't legal syntax. Single quote marks are used for character literals, and you can't have a character literal with no characters. (Or with 2 or more characters.) The Java compiler will not accept '' anywhere.
2

JLS 15.18.1. String Concatenation Operator +

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.

Comments

1

JLS 5.4 String Conversion says,

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

In this single special case, the non-String operand to the + is converted to a String (§5.1.11) and evaluation of the + operator proceeds as specified in §15.18.1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.