Back to: Java Tutorials
Char is primitive datatype. We declare char in java using single quotation mark (e.g.: ‘a’). For example:
char aChar = 'a';
A character is not a string. But Java provides method to get a char from a string. Getting the first char of the following string:
String str = "Hello World";
char c1 = str.charAt(0); // c1 will hold H
We can print a char like this:
System.out.println(c1);
Output: H
Getting ASCII value from char:
String str = "Hello World";
char c1 = str.charAt(0);
int num = c1;
System.out.println(num);
Output: 72 (ASCII code for H)
Getting/converting integer value from char:
String str = "12345";
char c1 = str.charAt(0);
int num = Character.getNumericValue(c1);
System.out.println(num);
output: 1