code:
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
Advertisement
Answer
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 char
s. 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:
- JLS 4.2 specifies that
char
is considered a numeric type. - JLS 15.18.2 specifies what
+
does to values of numeric types. - In particular, it specifies that the first thing done to them is binary numeric promotion, which converts both
char
s toint
by JLS 5.6.2. Then it adds them, and the result is still anint
.
To get what you want to happen, probably the simplest solution is to write
String sl = st.charAt(0) + "" + st.charAt(st.length() - 1));