EN
Java - get first character from string
0 points
In this article, we would like to show you how to get the first character of a string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
String firstCharacter = text.substring(0, 1);
3
4
System.out.println( firstCharacter ); // A
The below example shows how to use substring()
method to get the first character of the text
string.
xxxxxxxxxx
1
public class Example {
2
3
static String getFirstCharacters(String text, int numberCount) {
4
if (text.length() == numberCount) {
5
return text;
6
} else if (text.length() > numberCount) {
7
return text.substring(0, numberCount);
8
} else {
9
throw new IllegalArgumentException("Your text is shorter than " + numberCount + " character(s)!");
10
}
11
}
12
13
public static void main(String[] args) {
14
System.out.println( getFirstCharacters( "123", 1) ); // 1
15
System.out.println( getFirstCharacters( "12", 1) ); // 1
16
System.out.println( getFirstCharacters( "1", 1) ); // 1
17
System.out.println( getFirstCharacters( "", 1) ); // IllegalArgumentException
18
}
19
}
Output:
xxxxxxxxxx
1
1
2
1
3
1
4
Exception in thread "main" java.lang.IllegalArgumentException: Your text is shorter than 1 character(s)!