Java Program to Print Alphabets from A to Z
The English alphabet has 26 letters. In Java, a char is stored as a number, and the letters have consecutive values: 'A' to 'Z' are 65 to 90, and 'a' to 'z' are 97 to 122. That means a loop can count through letters just like through numbers.
1. Print Uppercase Alphabets Using a char Loop
The loop variable is a char. ch++ moves it to the next letter.
public class PrintAlphabets {
public static void main(String[] args) {
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
Output
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
2. Print Lowercase Alphabets Using ASCII Values
This version loops over the numbers 97 to 122 and casts each one to char to print the letter.
public class PrintLowercase {
public static void main(String[] args) {
for (int code = 97; code <= 122; code++) {
System.out.print((char) code + " ");
}
System.out.println();
}
}
Output
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
3. Print Alphabets in Reverse Using a while Loop
Counting down with ch-- prints the letters from Z to A. The second loop prints uppercase and lowercase pairs side by side using Character.toLowerCase().
public class PrintAlphabetsReverse {
public static void main(String[] args) {
char ch = 'Z';
while (ch >= 'A') {
System.out.print(ch + " ");
ch--;
}
System.out.println();
for (char c = 'A'; c <= 'F'; c++) {
System.out.print(c + "" + Character.toLowerCase(c) + " ");
}
System.out.println();
}
}
Output
Z Y X W V U T S R Q P O N M L K J I H G F E D C B A Aa Bb Cc Dd Ee Ff
4. Summary
- Characters have numeric codes, so a
forloop can step from'A'to'Z'withch++. - Casting the numbers 65–90 or 97–122 to
charprints the uppercase or lowercase letters. - Count down with
ch--to print the alphabet in reverse. Character.toLowerCase()andtoUpperCase()convert between cases.
Related Programs
Was this tutorial helpful?