HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Get first 4 characters of String in Java

Get first 4 characters of String in Java

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

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Cong

    March 12, 2020

    how can i do if i want to get last N character? Thank you .

  2. Petar

    September 25, 2019

    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?

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class EnglishWords {
    	String[] words = {"and", "love", "love", "love", "vole", "levo", "the"};
        
    
    public void start1()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your characters: ");
        String chars = sc.nextLine();
        String word = Arrays.toString(words);
       // if(word1.length())
        try{
                
                boolean display=true;
                if(word.length()==chars.length()){
                    for (int c = 0; c < chars.length(); c++)
                    {
                        if (word.indexOf(chars.charAt(c)) == -1) {
                            display = false;
                            System.out.println("No match");
                        }
                    }
                    if (display) {
                        System.out.println(word);
                    }
                }
                
    
        }
        catch (Exception e) {
            System.out.println("Couldn't find the list of words!");
        }
    
    }
    }
    
Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)