Code Logo

Split to Chars with toCharArray()

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes a string and returns the first character and the last character as a string using toCharArray() to access individual characters.

String.toCharArray() converts a string to a new character array. This is useful when you need to access or modify individual characters of a string. The returned array has the same length as the string, with each character occupying one array element for simple Latin characters.

Once you have a char[], you can access characters by index, sort them, search them, or modify them (since arrays are mutable while strings are immutable). This is the most efficient way to perform character-level operations on strings, avoiding the overhead of repeated charAt() calls.

Time complexity is O(n) where n is the string length (to copy characters to the new array). Space complexity is O(n) for the char array. The original string remains unchanged.

Edge cases include empty strings (returns empty array; accessing index 0 throws ArrayIndexOutOfBoundsException), single-character strings, and Unicode characters beyond the Basic Multilingual Plane (represented as surrogate pairs in char).

Example Input & Output

Example 1
Input
"test"
Output
tt
Explanation

t + t

Example 2
Input
"a"
Output
aa
Explanation

Single char repeated

Example 3
Input
"java"
Output
ja
Explanation

j + a

Example 4
Input
"abcd"
Output
ad
Explanation

a + d

Example 5
Input
"hello"
Output
ho
Explanation

First and last: h + o

Algorithm Flow

Recommendation Algorithm Flow for Split to Chars with toCharArray()
Recommendation Algorithm Flow for Split to Chars with toCharArray()

Solution Approach

class Solution {
    public String solution(String s) {
        char[] chars = s.toCharArray();
        if (chars.length == 0) return "";
        return "" + chars[0] + chars[chars.length - 1];
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String s) {
        char[] chars = s.toCharArray();
        if (chars.length == 0) return "";
        return "" + chars[0] + chars[chars.length - 1];
    }
}