Different Ways to Print First K Characters of the String in Java

Given a string str and a positive integer k, the task is to write a Java program to print the first k characters of the string. If the length of the string is less than k then print the string as it is.

Examples:

Input: str = “GeeksForGeeks”, k = 5

Output: Geeks

Explanation: The first k characters of the given string is ‘Geeks’.



Input: str = “Geeks”, k = 6

Output: Geeks

Explanation: The length of the given string is less than k. Therefore, we print the string as it is.

Method 1: Using string length

  1. Get the string and a positive integer k to print the first k characters of the string.
  2. Check if the string is null or empty then return null.
  3. Check if the string length is greater than k then get the first k characters of the string using str.substring(0, k).
  4. If the string length is less than k then return the string as it is.
  5. Now, print the first k characters of the string.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print first k
// characters of the string
  
class GFG {
      
    // Function to print first k
    // characters of the string
    public static String 
      firstKCharacters(String str, int k)
    {
          
        // Check if the string is empty
        // or null then return null
        if (str == null || str.isEmpty())
            return null;
          
        // Check if the string length
        // is greater than k, then
        // get the first k characters 
        // of the string, otherwise
        // return the string as it is
        if (str.length() > k)
            return str.substring(0, k);
          
        else
            return str;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        // Given String str
        String str = "GeeksForGeeks";
          
        // Given a positive integer k
        int k = 5;
          
        // Print the first k characters
        // of the string
        System.out.println(
          firstKCharacters(str, k));
    }
}

chevron_right


Output

Geeks



Method 2: Without checking the size

  1. The idea is to use Math.min() function as an end index of the substring method.
  2. Find the minimum value between the length of the string and positive integer k.
  3. Get the substring from zero to the minimum of string length and k.
  4. Now, print the first k characters of the string.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print first k
// characters of the string
  
class GFG {
  
    // Function to print first k
    // characters of the string
    public static String firstKCharacters(String str, int k)
    {
        // Check if the string is
        // null or empty then
        // return null
        if (str == null || str.isEmpty())
            return null;
  
        // Return the first k characters
        // of the string if the string
        // length is less than k, otherwise
        // return the string as it is
        return str.substring(0, Math.min(str.length(), k));
    }
  
    // Driver Code
    public static void main(String args[])
    {
        // Given String str
        String str = "GeeksForGeeks";
  
        // Given a positive integer k
        int k = 5;
  
        // Print the first k characters
        // of the string
        System.out.println(firstKCharacters(str, k));
    }
}

chevron_right


Output

Geeks



Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

I am Prashant Srivastava I am a final year student of BTech CSE

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.