Java Program to Display Characters from A to Z using a loop
public class DisplayAlphabets {
public static void main(String[] args) {
char ch;
System.out.println("Alphabets from A to Z are: ");
for(ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
}
}
}
Alphabets from A to Z are:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
In this program, we use a for
loop to iterate through the characters from ‘A’ to ‘Z’, and print each character to the console. The loop continues as long as the value of ch
is less than or equal to ‘Z’. The char
data type is used to store the characters, and we initialize ch
to ‘A’ before the loop begins.
Example 1: Display Uppercased A to Z using for loop
public class Characters {
public static void main(String[] args) {
char c;
for(c = 'A'; c <= 'Z'; ++c)
System.out.print(c + " ");
}
}
When you run the program, the output will be:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You can loop through A to Z using a for a loop because they are stored as ASCII characters in Java.
So, internally, you loop through 65 to 90 to print the English alphabet.
With a little modification, you can display lowercase alphabets as shown in the example below.
Example 2: Display Lowercased a to z using for loop
public class Characters {
public static void main(String[] args) {
char c;
for(c = 'a'; c <= 'z'; ++c)
System.out.print(c + " ");
}
}
When you run the program, the output will be:
a b c d e f g h i j k l m n o p q r s t u v w x y z
You simply replace ‘A’ with ‘a’ and ‘Z’ with ‘z’ to display the lowercase alphabet. In this case, internally you loop through 97 to 122. Java Program to Display Characters from A to Z using a loop