Start learning free

LESSON 67 OF 671 · STRINGS - CHALLENGES

Concat First and Last Char in Java: substring

Practice Read the full explanation

Given a string s, return a new string made of two characters: the first character of s, followed by its last character.

 

Example 1:

Input: s = "hello"
Output: "ho"
Explanation: The first character is "h" and the last one is "o".

Example 2:

Input: s = "Hello World!"
Output: "H!"
Explanation: Every character counts, so the last one is the "!", not the "d". The "H" stays upper case.

Example 3:

Input: s = "ab"
Output: "ab"
Explanation: With only two characters, the first is "a" and the last is "b".

 

Constraints:

  • s has at least 2 characters.
  • s contains English letters, digits, spaces and punctuation, and doesn't start or end with a space.
STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · STRINGS - CHALLENGES

    Concat First And Last Char in Java, explained

    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

    1. 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.
    2. Take the last character as a string. Indexes run from 0 to length() - 1, so the last character sits at s.length() - 1. Notice the parentheses: for a String, length() is a method call, while an array's length is a field. substring with a single argument runs from that index to the end of the string, which here is a single character.
    3. Join them with +. Both operands are strings, so the operator concatenates and a new string is returned. The original s is 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 char values. s.charAt(0) + s.charAt(s.length() - 1) compiles, but it produces an int, such as 215 for "hello". A method declared to return String can't return that int, so the compiler stops you, but the sum is a classic surprise in other places such as System.out.println.
    • Using s.length() as an index. The last valid index is length() - 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 a StringIndexOutOfBoundsException with the message Range [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 H in "Hello World!" stays upper case.

    Testing

    • "hello" gives "ho".
    • "Hello World!" gives "H!".
    • "ab" gives "ab".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free