Skip to content

why can’t I add chars to a new string?


String st = "abc";
String sl = st.charAt(0)+st.charAt(st.length()-1)); 

The second line is wrong for some reason and I don’t know why



The book is wrong, and Eclipse is right.

In Java, you can write "abc" + whatever, or whatever + "abc", and it concatenates the strings — because one side is a String.

But in st.charAt(0)+st.charAt(st.length()-1)), neither side is a String. They’re both chars. So Java won’t give you a String back.

Instead, Java will actually technically give you an int. Here are the gritty details from the Java Language Specification, which describes exactly how Java works:

  1. JLS 4.2 specifies that char is considered a numeric type.
  2. JLS 15.18.2 specifies what + does to values of numeric types.
  3. In particular, it specifies that the first thing done to them is binary numeric promotion, which converts both chars to int by JLS 5.6.2. Then it adds them, and the result is still an int.

To get what you want to happen, probably the simplest solution is to write

String sl = st.charAt(0) + "" + st.charAt(st.length() - 1));