maya
maya

Reputation: 51

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

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

Upvotes: 0

Views: 181

Answers (3)

Daniel Archuleta
Daniel Archuleta

Reputation: 109

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.

Upvotes: 0

obeid salem
obeid salem

Reputation: 147

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, ..

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198093

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)); 

Upvotes: 6

Related Questions