Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Useful Resources

Java - char Datatype



Java char datatype is one of the eight primitive datatype supported by Java. It provides means to create char type variables which can accept a char value. Following are the characteristics of a char data type.

  • char 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 variables represents a reserved memory locations 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.

Java char Datatype - Example 1

Following 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: A

Java char Datatype - Example 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: a

Java char Datatype - Example 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
Advertisements