How many different Ways to Print First K Characters of the String in Java.

Java is one of the most popular programming languages used in software development. One of the common tasks that a Java developer needs to perform is to print the first k characters of a given string. There are different ways to achieve this, and in this article, we will explore some of them.

Method 1: Using substring() method

The substring() method is a built-in function in Java that returns a part of the given string. We can use this method to extract the first k characters of a string as shown in the code snippet below:

 

 

String str = "Hello World";
int k = 5;
String firstKChars = str.substring(0, k);
System.out.println(firstKChars);

Output:

Hello

Method 2: Using charAt() method

The charAt() method is another built-in function in Java that returns the character at a specified index in a string. We can use this method to iterate through the first k characters of a string and print them as shown in the code snippet below:

 

 

String str = "Hello World";
int k = 5;
for (int i = 0; i < k; i++) {
    System.out.print(str.charAt(i));
}

Output:

Hello

Method 3: Using toCharArray() method

The toCharArray() method is a built-in function in Java that converts a string to an array of characters. We can use this method to extract the first k characters of a string as shown in the code snippet below:

 

String str = "Hello World";
int k = 5;
char[] charArray = str.toCharArray();
for (int i = 0; i < k; i++) {
    System.out.print(charArray[i]);
}

Output:

Hello

Method 4: Using substring() and toCharArray() methods

We can combine the substring() and toCharArray() methods to extract the first k characters of a string as an array of characters as shown in the code snippet below:

 

 

String str = "Hello World";
int k = 5;
char[] charArray = str.substring(0, k).toCharArray();
for (char c : charArray) {
    System.out.print(c);
}

Output:

Hello

 

Submit Your Programming Assignment Details