Java Characters
A char is a Java type that holds one character in single quotes. A String holds a sequence of characters in double quotes.
A char printed
The letter variable holds the single character A. The print line shows A.
public class Main {
public static void main(String[] args) {
char letter = 'A';
System.out.println(letter);
}
}Two chars printed
Each variable holds one character. The two print lines show H and then i.
public class Main {
public static void main(String[] args) {
char first = 'H';
char second = 'i';
System.out.println(first);
System.out.println(second);
}
}A char against a String
The char holds one letter in single quotes. The String holds a whole word in double quotes.
public class Main {
public static void main(String[] args) {
char letter = 'J';
String word = "Java";
System.out.println(letter);
System.out.println(word);
}
}A char is a number code
The char A prints as a letter on its own. Adding 1 treats it as its code and prints 66.
public class Main {
public static void main(String[] args) {
System.out.println('A');
System.out.println('A' + 1);
}
}Example
public class Main {
public static void main(String[] args) {
char grade = 'B';
char mark = '7';
String label = "Grade";
System.out.println(label);
System.out.println(grade);
System.out.println(mark);
}
}Key points
- A char value sits in single quotes.
- A char holds exactly one character.
- A String value sits in double quotes.
- A String can hold many characters or none.
- Each char has a numeric code.
- The code for the letter A is 65.
In this example, the label variable holds the String Grade. The grade variable holds the single char B. The mark variable holds the single char 7, which is a character and not the number seven.
Note
A char in single quotes and a one-letter String in double quotes are different types.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
How many characters can a char variable hold?