how to find ascii value of a character in java code example
Example 1: how to get a character in java in ascii
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]
Read more: https://javarevisited.blogspot.com/2015/07/how-to-convert-string-or-char-to-ascii-example.html#ixzz6k2vn7o4y
Example 2: ascii values to display certain characters in java
/*ASCII acronym for American Standard Code for Information Interchange.
It is a 7-bit character set contains 128 (0 to 127) characters.
It represents the numerical value of a character.
For example, the ASCII value of A is 65.*/
char a = 65, b = 66, c = 67;
System.out.println(a);
System.out.println(b);
System.out.println(c);
/* this is how you type ASCII values in java */
Example 3: how to print ascii value in java
public class AsciiValue {
public static void main(String[] args) {
char ch = 'a';
int ascii = ch;
// You can also cast char to int
int castAscii = (int) ch;
System.out.println("The ASCII value of " + ch + " is: " + ascii);
System.out.println("The ASCII value of " + ch + " is: " + castAscii);
}
}
Example 4: how to get a character in java in ascii
// Very simple. Just cast your char as an int.
char character = 'a';
int ascii = (int) character;
//In your case, you need to get the specific Character from the String first and then cast it.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
//Though cast is not required explicitly, but its improves readability.
int ascii = character; // Even this will do the trick.
Example 5: ascii values to display certain characters in java
char a = 65, b = 66, c = 67;
System.out.println(a);
System.out.println(b);
System.out.println(c);
/* this is how you type ASCII values in java */
Example 6: how to add a number to the ascii value of a char in java
char a = 97+1;
char b = 'a'+2;
r = (char)(1+5)