Languages
[Edit]
EN

Java - get first character from string

0 points
Created by:
Jax
388

In this article, we would like to show you how to get the first character of a string in Java.

Quick solution: 

String text = "ABC";
String firstCharacter = text.substring(0, 1);

System.out.println( firstCharacter ); // A

 

Practical example

The below example shows how to use substring() method to get the first character of the text string.

public class Example {

    static String getFirstCharacters(String text, int numberCount) {
        if (text.length() == numberCount) {
            return text;
        } else if (text.length() > numberCount) {
            return text.substring(0, numberCount);
        } else {
            throw new IllegalArgumentException("Your text is shorter than " + numberCount + " character(s)!");
        }
    }

    public static void main(String[] args) {
        System.out.println( getFirstCharacters(  "123", 1) ); // 1
        System.out.println( getFirstCharacters(   "12", 1) ); // 1
        System.out.println( getFirstCharacters(    "1", 1) ); // 1
        System.out.println( getFirstCharacters(     "", 1) ); // IllegalArgumentException
    }
}

Output: 

1
1
1
Exception in thread "main" java.lang.IllegalArgumentException: Your text is shorter than 1 character(s)!
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - get first character of string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join