Print Each Character of a String in Java
Printing each character of a string is a basic string operation in Java. It helps beginners understand how strings are accessed and processed character by character.
This concept is widely used in:
- String manipulation
- Character counting problems
- Palindrome and anagram checks
How the Logic Works
To print each character of a string:
- Read the input string.
- Convert the string into a character array.
- Traverse the array using a loop.
- Print each character one by one.
Example 1
Input: "Java"
J
a
v
a
Example 2
Input: "Hello World"
H
e
l
l
o
W
o
r
l
d
Note: The space between words is also treated as a character.
Java Program to Print Each Character of a String
import java.util.Scanner;
public class PrintEachCharacter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
for (char ch : str.toCharArray()) {
System.out.println(ch);
}
}
}
Sample Output
Enter a string: Coding
C
o
d
i
n
g
Important Notes
- Spaces and special characters are printed as well.
- This program uses enhanced for-loop for clarity.
- You can also use a normal for-loop with
charAt().
Practice Challenges
- Print each character along with its index.
- Print characters in reverse order.
- Print only vowels from the string.
Understanding how to access individual characters is essential for mastering string problems in Java.