Problem overview
The method concatFirstAndLastChar receives a string s with at least two characters and returns a new string made of its first character followed by its last one. Every character counts, spaces and punctuation included, and letters keep their case.
For "hello" the result is "ho". For "Hello World!" it is "H!", because the last character is the exclamation mark, not the d. For "ab", the first and last characters are the only two, so the result is "ab" again.
Approach: two one-character slices
A Java String can't be indexed with square brackets. Two tools can pick out a character: charAt(i), which returns a char, and substring, which returns a String. They look interchangeable here, but they behave differently once you join the results with +.
A char is a number underneath (its character code). When both operands of + are char values, Java adds the numbers. With c1 = 'h' and c2 = 'o', the expression c1 + c2 prints 215, the sum of 104 and 111. Likewise "hello".charAt(0) + "hello".charAt(4) prints 215, not ho. Strings, on the other hand, are joined as text. So the cleanest solution takes both characters as one-character strings.
(charAt can still be used, but one operand must already be a string, for example "" + s.charAt(0) + s.charAt(s.length() - 1). The lesson uses substring for both ends so that the two pieces have the same shape.)
Step by step
- Take the first character as a string.
substring(0, 1)starts at index 0 and stops before index 1, so it holds exactly one character. The end index is exclusive: the slice never includes the character at the index you give as its end. - Take the last character as a string. Indexes run from 0 to
length() - 1, so the last character sits ats.length() - 1. Notice the parentheses: for aString,length()is a method call, while an array'slengthis a field.substringwith a single argument runs from that index to the end of the string, which here is a single character. - Join them with
+. Both operands are strings, so the operator concatenates and a new string is returned. The originalsis untouched: Java strings are immutable, and every string method returns a new value.
The solution in Java
class Solution {
public String concatFirstAndLastChar(String s) {
return s.substring(0, 1) + s.substring(s.length() - 1);
}
}
Tracing the three examples through this code gives the results from the statement:
hello -> ho
Hello World! -> H!
ab -> ab
The one-argument form substring(start) and the two-argument form substring(start, end) are both used here, so it helps to remember the rule they share: the start index is included, the end index is not.
Edge cases and common mistakes
- Adding two
charvalues.s.charAt(0) + s.charAt(s.length() - 1)compiles, but it produces anint, such as215for"hello". A method declared to returnStringcan't return thatint, so the compiler stops you, but the sum is a classic surprise in other places such asSystem.out.println. - Using
s.length()as an index. The last valid index islength() - 1.s.substring(s.length())is valid and returns the empty string, which would silently give a result with only one character. - Empty strings. The lesson guarantees at least two characters. On an empty string,
substring(0, 1)throws aStringIndexOutOfBoundsExceptionwith the messageRange [0, 1) out of bounds for length 0. - Two-character strings. The first and last characters are different positions, so
"ab"gives"ab". A one-character string would give the same character twice, which the constraints exclude. - Changing case. The method never converts case: the
Hin"Hello World!"stays upper case.
Testing
"hello"gives"ho"."Hello World!"gives"H!"."ab"gives"ab".
