Table of Contents

In Java, to print the first character in a given string, we can use built-in functions such as charAt(), toCharArray(), substring() or obtain the first character using an if-else statement. For the given input string “Interview”, First character in the string is ‘I’.

In this article we will learn how to print first character in a string through an example, detailed logic and program explanation for better understanding.

📘 Required Knowledge

  • Java programming basics
  • String functions (charAt(), toCharArray() and substring)
  • Loop concepts
  • Conditional statements

📝 Problem Statement

We have to write a java program to print the first character in a given string. This Java program should take an input string from the users and should print only the first letter from the input string.

Example:

For a given String as input ” Hello”, Output should be “H”.

Explanation:

Input string str: " Hello"

First character is : (white space)

First letter should not be space so, we remove trailing and leading spaces. After removing leading and trailing spaces str is updated as below,

str: "Hello"

Now, we get "H" as the first character.

Hence, In input str " Hello", "H" is the first character.

💡 Logic to print the first character in a given string

There are multiple logics to print the first character in a given string in Java programming language.

Logic 1: Using charAt():

To print first character in a given string using charAt() method in Java:

  • Initialize the input String str from user. Using the trim() method remove trailing and leading spaces.
    • If the str is empty, it displays an informative message asking the user to enter a non-empty text. Otherwise, it will proceeds to next using if-else.
    • Find the string length.
    • Using charAt(0), retrieve the first character which is at index 0 and print it.

Logic 2: Using toCharArray()

To print first character in a given string using toCharArray() method in Java:

  • First take a input String str and use trim() to remove leading and trailing spaces.
    • It checks for an empty string after trimming and displays an error message, if it has empty string. Otherwise proceed to next step using if else.
    • Then convert the str into a character array using toCharArray() and store this trimmed str in the character variable ch.
    • Then find find ch[0], it will print the first non-space character.

Logic 3: Using substring()

To print the first character using the substring() method in Java:

  • Take an input String str and trim it using trim() to remove leading and trailing whitespace.
  • Using an if-else condition, check if the trimmed input string str is empty. If it is empty, print “Input text is empty”. If the input string is not empty, proceed to the next step.
  • Use str.substring(0, 1) to extract the first character from the trimmed string str and store it in firstCharacter. The substring(0, 1) method retrieves a substring starting from index 0 (inclusive) to index 1 (exclusive).
  • Print firstCharacter to display the first character of the original input string str.

Logic 4: Using If-else statement

To print the first letter in the string using an if-else statement in Java:

  • Initialize the input String str with data taken from the user.
  • Use an if-else condition to check if the input string str is empty.
  • If the string is not empty, initialize an index variable and iterate through the string using a while loop until the first non-space character is found.
  • Once the first non-space character is found (at index zero), print this character as the first letter of the string.
  • If the string is empty, print a message indicating that the ‘string is empty’ using an appropriate if-else statement.

🧮 Java program to print the first character in a given string

✅ Program 1: Using charAt() method

In the below program we are using charAt() method to print the first character of a given string in Java.

import java.util.Scanner;
public class FirstChar1 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Please enter a text");
		String str= s.nextLine();
		str=str.trim();
		if (str.trim().isEmpty()) {
    System.out.println("Please enter a non-empty text.");
} else {
		System.out.println("Length of the input text: "+str.length());
		char firstCharacter = str.charAt(0);
		System.out.println("First character is: "+firstCharacter);
}		
		s.close();
	}
}

Output:

Please enter a text
This Interview Expert
Length of the input text: 21
First character is: T

🧠 Explanation:

  1. The above java program reads user input for text using a Scanner object.
  2. Trims any leading or trailing whitespace characters from the input.
  3. Checks if the trimmed input is empty and displays an error message if so.
  4. If the input is not empty:
    • Finds the length of the trimmed string.
    • Retrieves the first character of the trimmed string using charAt(0).
  5. Prints the length and the first character of the non-empty input.
  6. Closes the Scanner object to release resources.

✅ Program 2: Using toCharArray() method

In the below program we are using toCharArray() method to print the first character of a given string in Java.

import java.util.Scanner;
public class FirstChar2 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter a text");
        String str = s.nextLine();
        str = str.trim();
        if (str.trim().isEmpty()) {
            System.out.println("Please enter a non-empty text.");
        } else {
            char[] ch = str.toCharArray();
            char firstCharacter = ch[0];
            System.out.println("First character is: " + firstCharacter);
        }
        s.close();
    }
}

Output:

Please enter a text
Share Knowledge
Length of the input text: 15
First character is: S

🧠 Explanation:

  1. The above java program reads user input for text using a Scanner object.
  2. Trims any leading or trailing whitespace characters from the input.
  3. Checks if the trimmed input is empty and displays an error message if so.
  4. If not empty, Converts the trimmed string into an array of characters.
  5. Retrieves the first character from the character array (index 0).
  6. Prints the length and the first character of the non-empty input.
  7. Closes the Scanner object to release resources.

✅ Program 3: Using substring() method

In the below program we are using substring() method to print the first character of a given string in Java.

import java.util.Scanner;
public class FirstChar3 {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Please enter a text");
		String str= s.nextLine();
		str = str.trim();
		if (str.isEmpty()) {
            System.out.println("Input text is empty");
        } else {
            System.out.println("Length of the input text: " + str.length());   
            String firstCharacter = str.substring(0, 1);
            System.out.println("First character is: " + firstCharacter);
        }	
		s.close();
	}
}

Output:

Please enter a text
Interview Expert
Length of the input text: 16
First character is: I

🧠 Explanation:

  1. The program asks the user to enter a text.
  2. It reads the input text and trims any leading or trailing spaces.
  3. If the trimmed input text is empty, it prints a message indicating that the input text is empty.
  4. Otherwise, it prints the length of the input text and the first character of the trimmed input text.
  5. Finally, it closes the Scanner object to release system resources.

✅ Program 4: Using if-else statement

In the below program we are printing the first character of a string using if-else statement in Java.

import java.util.Scanner;
public class FirstChar {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("Enter a text");
		String str = s.nextLine();
		if (str != null && str.length() > 0) {	
			int i = 0;
			while (i < str.length() && str.charAt(i) == ' ') {
				i++;
			}	
			if (i < str.length()) {
				int firstCharacter= i;
				System.out.println("First character is: " + str.charAt(firstCharacter));
			} else {
				System.out.println("No character found in the text");
			}
		} else {
			System.out.println("Input text is empty");
		}
		s.close();
	}
}

Output:

Enter a text
Hi, Happy Learning
The first character is: H

🧠 Explanation:

  1. The java program uses a Scanner object to read input from the console.
  2. After asking the user to input a text, it reads the input String (str).
  3. It checks if the input string (str) is not empty.
  4. If the input string (str) is not empty, it iterates through the string (str) until it finds the first non-space character by incrementing the index variable i until str.charAt(i) is not equal to a space.
  5. Once the first non-space character is found, it prints it out.
  6. If the input string (str) contains only spaces or is empty, it prints a corresponding message.
  7. Finally, it closes the Scanner object to release system resources.

Note: As there are direct built-in methods available, this approach is less efficient and more time-consuming.

Conclusion

In this article, we have learnt how to print the first character in a given string in Java. We have seen the logic and implemented the program using various methods such as charAt(), toCharArray(), substring() and if-else statements. Hope this article helped you in the understanding of the program.

You can also check our other amazing tutorials

Happy Programming!!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in:

Java Coding,