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
CodePudding user response:
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
- 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));
CodePudding user response:
Because charAt returns char [ int ]
use this code :
String st = "abc";
StringBuilder str = new StringBuilder();
str.append(st.charAt(0));
str.append(st.charAt(st.length() - 1));
System.out.println(str.toString());
append method accept the char, or string, ..
CodePudding user response:
well this is what it says: "- Type mismatch: cannot convert from int to String"
Meaning exactly what @Jaime said. If I remember correctly, a char is technically represented by an integer value. (i.e. 'a' 1 = 'b'). So you're adding two char values, which isn't the same thing as adding two strings together, or even concatenating two char values. One fix would be to use String.valueOf(st.charAt(0)) String.valueOf(st.charAt(st.length()-1)))
to concatenate the two char values.