- How to convert String or char to ASCII values in Java — Example Tutorial
- Java Program to convert String and char to ASCII
- Java program to convert a character to ASCII code and vice versa
- Java Program to Find ASCII Value of a Character Or String
- 1. Introduction
- 2. Java Example Program Converting Char to ASCII Value
- 3. Java Example Program Converting String to ASCII Value
- 4. Example to Convert String to ASCII with byte casting
- 5. Example to Convert String to ASCII with StandardCharsets.US_ASCII
- 6. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
How to convert String or char to ASCII values in Java — Example Tutorial
You can convert a character like ‘A’ to its corresponding ASCII value 65 by just storing it into a numeric data type like byte, int, or long as shown below :
Here casting is not necessary, simply assigning a character to an integer is enough to store the ASCII value of character into an int variable, but casting improves readability. Since ASCII is a 7-bit character encoding, you don’t even need an integer variable to store ASCII values, byte data type in Java, which is 8 bits wide is enough to store the ASCII value of any character. So you can also do like this :
byte asciiOfB = 'B'; // assign 66 to variable
Since String is nothing but a character array in Java, you can also use this technique to convert a String into ASCII values, as shown below :
StringBuilder sb = new StringBuilder(); char[] letters = str.toCharArray(); for (char ch : letters) < sb.append((byte) ch); > System.out.println(sb.toString()); // print 749711897
You can also directly convert String to a byte array, where bytes will hold ASCII value of characters as shown below :
byte[] ascii = "Java".getBytes(StandardCharsets.US_ASCII); String asciiString = Arrays.toString(ascii); System.out.println(asciiString); // print [74, 97, 118, 97]
You can pass character encoding as «US-ASCII» also, as we have done in our Java example, but using StandardCharsets.US_ASCII is safer because there is no chance of any spelling mistake causing UnsupportedEncodingException . See Core Java Volume 1 10th Edition by Cay S. Horstmann to learn more about String in Java.
Java Program to convert String and char to ASCII
Here is our Java program, which combines all the ways we have seen to convert String and character to their respective ASCII values. You can also use the same technique to convert String to other encoding formats e.g. ISO-8859-X (1-7) , UTF-8, UTF-16BE, UTF-16LE. These are some of the popular encoding formats internally supported by Java.
See class java.nio.charset.Charset and StandardCharsets for more information
Here is an ASCII table for your quick reference :
import java.text.ParseException; import java.util.Arrays; /** * How to convert a String to ASCII bytes in Java * * @author WINDOWS 8 */ public class StringToASCII < public static void main(String args[]) throws ParseException < // converting character to ASCII value in Java char A = 'A'; int ascii = A; System.out.println("ASCII value of 'A' is : " + ascii); // you can explicitly cast also char a = 'a'; int value = (int) a; System.out.println("ASCII value of 'a' is : " + value); // converting String to ASCII value in Java try < String text = "ABCDEFGHIJKLMNOP"; // translating text String to 7 bit ASCII encoding byte[] bytes = text.getBytes("US-ASCII"); System.out.println("ASCII value of " + text + " is following"); System.out.println(Arrays.toString(bytes)); > catch (java.io.UnsupportedEncodingException e) < e.printStackTrace(); > > > Output ASCII value of 'A' is : 65 ASCII value of 'a' is : 97 ASCII value of ABCDEFGHIJKLMNOP is following [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80]
That’s all guys, now you know how to convert a Java char or String to their ASCII values. Remember, when you store a char data type into numeric types e.g. byte, short, int, or long, their ASCII values are stored. It’s also efficient to use byte data type to store ASCII values because it’s a 7-bit character encoding and byte is enough to store ASCII.
- How to convert Char to String in Java? [solution]
- How to convert String to int in Java? [solution]
- How to convert float to String in Java? [example]
- How to convert Double to String in Java? [solution]
- How to convert String to Date in a thread-safe manner? [example]
- How to convert byte array to Hex String in Java? [solution]
- How to convert Decimal to Binary in Java? [solution]
- How to convert String to Integer in Java? [solution]
- How to convert ByteBuffer to String in Java? (program)
Java program to convert a character to ASCII code and vice versa
Computers can only understand numbers, more specifically, binaries ( 0 or 1 ). To store or exchange text-based information in computers, we need some kind of character encoding that can encode text data to numbers which can then be represented using binary digits.
ASCII (American Standard Code for Information Exchange) is a character encoding standard developed in the early 60’s for representing and exchanging text-based information in computers. The ASCII character set consists of 128 characters that are represented using 7-bit integers. You can check out the complete ASCII character set here.
This article shows you how to convert a character to ASCII code or get the character from a given ASCII code in Java. The conversion from character to ASCII code or ASCII code to character is done using type casting. Check out the following programs to know more:
Convert character to ASCII code in Java
class CharToAsciiCodeExample public static void main(String[] args) char ch = 'A'; int asciiValue = ch; // char is automatically casted to int System.out.printf("Ascii Value of %c = %d\n", ch, asciiValue); > >
$ javac CharToAsciiCodeExample.java $ java CharToAsciiCodeExample Ascii Value of A = 65
Convert ASCII code to character in Java
class AsciiCodeToCharExample public static void main(String[] args) int asciiValue = 97; char ch = (char) asciiValue; System.out.printf("Character corresponding to Ascii Code %d = %c\n", asciiValue, ch); > >
$ javac AsciiCodeToCharExample.java $ java AsciiCodeToCharExample Character corresponding to Ascii Code 97 = a
Java Program to Find ASCII Value of a Character Or String
A quick program on how to convert char to ASCII code and String to ASCII code. Examples with assigning to int, type casting to int or byte, byte[] array to ASCII code, String bytes US_ASCII.
1. Introduction
This can be done by using type casting and variable assignment.
Let us see how to convert String or Char into ASCII values.
2. Java Example Program Converting Char to ASCII Value
package com.javaprogramto.w3schools.programs.ascii; public class CharToASCII < public static void main(String[] args) < char c = 'A'; int aAscii = c; int castAscii = (int) c; System.out.println("Char A ASCII value with variable assignment : "+aAscii); System.out.println("Char A ASCII value with casting : "+castAscii); char anotherChar = 'Z'; int anotherCharAscii = c; int anotherCharCastAscii = (int) c; System.out.println("Char Z ASCII value with variable assignment : "+anotherCharAscii); System.out.println("Char Z ASCII value with casting : "+anotherCharCastAscii); > >
[Char A ASCII value with variable assignment : 65
Char A ASCII value with casting : 65
Char Z ASCII value with variable assignment : 65
Char Z ASCII value with casting : 65]
The above example shows converting char to ASCII in two ways. Instead of casting to int, directly char can be assigned to int type.
3. Java Example Program Converting String to ASCII Value
Converting String to ASCII values is a little tricky because you need to convert each character in the string.
So, First, convert the string into char[] array then add each character typecasting to int. Finally, print the values directly to console or add each character ASCII code to a StringBuffer or List.
package com.javaprogramto.w3schools.programs.ascii; public class StringToAscii < public static void main(String[] args) < String str = "hello javaprogramto.com"; char[] array = str.toCharArray(); System.out.println("ASCII codes for string "+str+" are : "); for (char c : array) < System.out.println((int)c); > > >
[ASCII codes for string hello javaprogramto.com are :
104
101
108
108
111
32
106
97
118
97
112
114
111
103
114
97
109
116
111
46
99
111
109]
4. Example to Convert String to ASCII with byte casting
package com.javaprogramto.w3schools.programs.ascii; public class StringToAsciiByteCasting < public static void main(String[] args) < String input = "byte casting"; char[] array = input.toCharArray(); StringBuffer sb = new StringBuffer(); for (char ch: array) < sb.append((byte)ch).append(" "); > System.out.println("byte casting output : "+sb); > >
5. Example to Convert String to ASCII with StandardCharsets.US_ASCII
package com.javaprogramto.w3schools.programs.ascii; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class StringToAsciiUSBytes < public static void main(String[] args) < String input = "ascii US bytes"; // converting string to bytes array. byte[] bytesArray = input.getBytes(StandardCharsets.US_ASCII); // bytes array to sscii string. String asciiStr = Arrays.toString(bytesArray); System.out.println("String to ASCII with US_ASCII : "+asciiStr); > >
6. Conclusion
Labels:
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
A quick program on how to convert char to ASCII code and String to ASCII code. Examples with assigning to int, type casting to int or byte, byte[] array to ASCII code, String bytes US_ASCII.