Java char is a primitive data type and it is used to create character (char) type variables that can accept a single character.
Characteristics of a char Data Typechar data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
A char variable represents a reserved memory location to store char values. This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store char values in char variables.
SyntaxFollowing is the syntax to declare a character type variable using the char keyword:
char variable_name = value;Examples of char Data Type (Keyword)
Following are some of the examples of char data type (keyword) in Java.
Example 1Following example shows the usage of char primitive data type we've discussed above. We've created a char variable as charValue and assigned it a char value. Then this variable is printed.
package com.tutorialspoint; public class JavaTester { public static void main(String args[]) { char charValue = 'A'; System.out.println("char: " + charValue); } }Output
char: AExample 2
Following example shows the usage of char primitive data type to store unicode values. We've created two char variables and assigned them char values. Finally values are printed.
package com.tutorialspoint; public class JavaTester { public static void main(String args[]) { char charValue1 = '\u0041'; char charValue2 = '\u0061'; System.out.println("char: " + charValue1); System.out.println("char: " + charValue2); } }Output
char: A char: aExample 3
Following example shows the usage of char variable with an invalid value. We've created a char variable as charValue and assigned it an out of range value.
package com.tutorialspoint; public class JavaTester { public static void main(String args[]) { char charValue = '\ufffff'; System.out.println("char: " + charValue); } }Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Invalid character constant at com.tutorialspoint.JavaTester.main(JavaTester.java:5)
java_basic_syntax.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4