Split to Chars with toCharArray()
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
t + t
Single char repeated
j + a
a + d
First and last: h + o
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String s) {
char[] chars = s.toCharArray();
if (chars.length == 0) return "";
return "" + chars[0] + chars[chars.length - 1];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
