
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display Printable Characters in Java
In this article, we will learn to display printable characters in Java. The program uses ASCII code from 32 to 126, which correspond to printable symbols, numbers, and letters. Instead of using System.out.println(), we will use System.out.write() to print each character.
Problem Statement
Write a Java program that displays all printable characters by iterating through their ASCII values ?
Output
Printable characters...
! " # $ % & '
( ) * + , - . /
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 z { | } ~
Steps to display printable characters
Following are the steps to display printable characters ?
- Start by printing the message "Printable characters...".
- Use a for loop to iterate over ASCII values from 32 to 126.
- For each value, print the corresponding character using System.out.write().
- Insert a newline after every 8 characters for better formatting.
- End with a final newline after printing all characters.
Java program to display printable characters
Below is the Java program to display printable characters. Let us see the complete example ?
public class Demo { public static void main(String []args) { System.out.println("Printable characters..."); for (int i = 32; i < 127; i++) { System.out.write(i); if (i % 8 == 7) System.out.write('\n'); else System.out.write('\t'); } System.out.write('\n'); } }
Output
Printable characters...
! " # $ % & '
( ) * + , - . /
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 z { | } ~
Code Explanation
To display printable characters, you need to work with the ASCII values from 32 to 127.
With that, we are using the following, instead of System.out.println()
System.out.write();
The following displays all the printable characters.
for (int i = 32; i < 127; i++) { System.out.write(i);
Advertisements