javawhile-loopitoa

Integer to char - cast and print:


I want to know the logic behind this programm and (char) cast. How does it work and how it is printing all the letters, symbols and numbers

package ascii1
public class Ascii1 {

    public static void main(String[] args) {
        int i=1;
        while(i<122)
        {
            System.out.println((char)i+"\t");
            if (i%10==0)
                System.out.println("");
            i++;
        }

        } 
}

Its output is:

//Blanks in the beginning...

! "

$ % & ' (

) * + ,
- . / 0 1 2

3 4 5 6 7 8 9 : ; <

=

? @ 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

[ \ ] ^
_ ` 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 BUILD SUCCESSFUL (total time: 0 seconds)


Solution

  • Using ASCII representation, every char has a numerical value.

    When you iterate, adding +1 to the i variable, you get to numbers on the ASCII table representing some characters.

    Finally, the (char) cast returns the above ASCII character.