Learn how to get first 4 characters of a String or simply any number of first characters of a string in Java.
Get first 4 characters of String – Example
To get substring having first 4 chars first check the length of string. If string length is greater than 4 then substring(int beginIndex, int lastIndex) method. This method takes start and last index positions to return the substring within those indices.
If string length is less than 4, we can return the complete string as it is.
If data is in not in string form, use String.valueOf() method to convert it to String, first.
String input = "123456789"; //input string String firstFourChars = ""; //substring containing first 4 characters if (input.length() > 4) { firstFourChars = input.substring(0, 4); } else { firstFourChars = input; } System.out.println(firstFourChars);
Program output.
1234
If you wish to get first N characters (not 4), then replace '4'
in above java program with desired number of characters. For example, to get first 2 characters we can change the method call to input.substring(0, 2).
Happy Learning !!
Read More : Get last 4 characters of String in Java
Cong
how can i do if i want to get last N character? Thank you .
Petar
Hello Sir! I’m very glad that you make a website for learning Java. I tried to make a program but have trouble. A user inputs a number of characters as a string. The program then lists all the words provided as an array for example. Each letter can only used once. The letters can be used in any order and the text input by the user must not be one of the words generated. Here my code but it’s not worked. Can you please help?