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 Data Type



char Data Type (Keyword)

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 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 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.

Syntax

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

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

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