Languages
[Edit]
EN

Java - get first 3 characters of string

0 points
Created by:
Dirask Admin - Marwin
1460

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

Quick solution: 

String text = "This is your text";
String firstThreeCharacters = text.substring(0, 3);

System.out.println( firstThreeCharacters ); // Thi

Practical example

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

public class StringExample {

    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 longer than " + numberCount + " characters!");
        }
    }

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

Output: 

123
123
123
Exception in thread "main" java.lang.IllegalArgumentException: Your text is longer than 3 characters!

Java - String (popular problems)

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