Back to Java
2026-04-186 min read

char

Learn char step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on the char keyword in Java! In this tutorial, we will delve into the world of character handling, a crucial aspect of programming that you'll encounter frequently in exams, interviews, and real-world applications. Understanding how to work with characters is essential for creating user-friendly interfaces, parsing text data, and validating input.

Prerequisites

To fully grasp the concepts covered in this lesson, it is essential to have a solid understanding of the following:

  1. Java basics (variables, data types, operators)
  2. Control structures (if-else statements, loops)
  3. Understanding of classes and objects
  4. Basic input/output operations (Scanner, System.out.println)
  5. Familiarity with the String data type and its methods
  6. Understanding of arrays and collections in Java
  7. Exception handling (try-catch blocks)

Core Concept

In Java, the char data type is used to store individual characters. A single character occupies 2 bytes of memory, which can hold a Unicode value ranging from 0 to 65535. The char type is enclosed in single quotes (' ') when declaring or assigning values.

char myChar = 'A'; // Declaring and initializing a char variable

ASCII Values and Unicode

The American Standard Code for Information Interchange (ASCII) is a widely used character encoding standard that assigns unique numeric values to each character. In Java, the char data type can store both ASCII and Unicode characters. The ASCII table contains 128 printable characters, while Unicode extends this range significantly, supporting over 100,000 characters from various writing systems.

ASCII Table

| Decimal | Hexadecimal | Character |

|---------|------------|-----------|

| 0 | NUL | NULL |

| 1 | SOH | Start of Header |

| 2 | STX | Start of Text |

| 3 | ETX | End of Text |

| 4 | EOT | End of Transmission |

| 5 | ENQ | Enquiry |

| 6 | ACK | Acknowledgment |

| 7 | BEL | Bell |

| 8 | BS | Backspace |

| 9 | HT | Horizontal Tab |

| 10 | LF | Line Feed |

| 11 | VT | Vertical Tab |

| 12 | FF | Form Feed |

| 13 | CR | Carriage Return |

| 14 | SO | Shift Out |

| 15 | SI | Shift In |

| 16 | DLE | Data Link Escape |

| 17 | DC1 | Device Control 1 |

| 18 | DC2 | Device Control 2 |

| 19 | DC3 | Device Control 3 |

| 20 | DC4 | Device Control 4 |

| 21 | NAK | Negative Acknowledgment |

| 22 | SYN | Synchronous Idle |

| 23 | ETB | End of Transmission Block |

| 24 | CAN | Cancel |

| 25 | EM | End of Medium |

| 26 | SUB | Substitute |

| 27 | ESC | Escape |

| 28 | FS | File Separator |

| 29 | GS | Group Separator |

| 30 | RS | Record Separator |

| 31 | US | Unit Separator |

| 32 | SP | Space |

| 33-126 | - | Printable characters (letters, numbers, punctuation) |

| 127 | DEL | Delete |

Character Operations

Java provides several operators for working with characters:

  • Arithmetic operators (+, -, *, /) can be used to perform operations on char values, but the results are not always meaningful. For example:
char a = 'A';
char b = 'B';
char sum = a + b; // The result (66) is the ASCII value of 'B'
  • Comparison operators (==, !=, <, >, <=, >=) can be used to compare two characters.
  • Relational operators can also be used in conjunction with the Character class methods, such as isDigit(), isLetter(), and others, to check specific properties of a character.

Character Methods

The Character class provides several useful methods for working with characters:

  • charValue(): Returns the char value of a Character object.
  • toString(): Converts a char value to its equivalent String representation.
  • isDigit(char ch): Checks if the given character is a digit (0-9).
  • isLetter(char ch): Checks if the given character is an alphabetic letter (A-Z or a-z).
  • isLowerCase(char ch): Checks if the given character is a lowercase letter.
  • isUpperCase(char ch): Checks if the given character is an uppercase letter.
  • isWhitespace(char ch): Checks if the given character is a whitespace character (space, tab, line break, etc.).
  • toUpperCase() and toLowerCase(): Converts a char to its uppercase or lowercase equivalent.

Worked Example

Let's create a simple Java program that reads a character from the user, checks if it is an alphabet or a digit, and performs basic operations on it.

import java.util.Scanner;

public class CharOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a character: ");
char inputChar = scanner.next().charAt(0);

if (Character.isLetter(inputChar)) {
System.out.println("You entered an alphabet.");
// Perform letter-specific operations here
System.out.println("Uppercase equivalent: " + Character.toUpperCase(inputChar));
System.out.println("Lowercase equivalent: " + Character.toLowerCase(inputChar));
} else if (Character.isDigit(inputChar)) {
System.out.println("You entered a digit.");
// Perform digit-specific operations here
int num = Character.getNumericValue(inputChar);
System.out.println("Integer equivalent: " + num);
} else {
System.out.println("You entered a special character.");
}
}
}

Common Mistakes

  1. Forgetting to enclose char literals in single quotes (e.g., using int a = 'A'; instead of char a = 'A';)
  2. Treating characters as integers and performing arithmetic operations without understanding the results
  3. Comparing characters with == operator instead of equals() method when comparing Strings containing single characters (e.g., using 'A' == "A" instead of "A".equals("A"))
  4. Failing to check for specific character properties using the Character class methods (e.g., using if (inputChar > 'Z') instead of if (Character.isLetter(inputChar) && inputChar > 'Z'))
  5. Ignoring whitespace characters when comparing strings or reading user input
  6. Not handling exceptions properly when dealing with user input
  7. Assuming that all characters within the Unicode range can be printed or used in a meaningful way

Subheadings under Common Mistakes:

  • Incorrect use of char literals and variables
  • Misunderstanding character arithmetic operations
  • Comparing characters improperly with the == operator
  • Failing to check for specific character properties using the Character class methods
  • Overlooking whitespace characters
  • Improper exception handling
  • Assumptions about Unicode characters

Practice Questions

  1. Write a Java program that checks if a given password meets the following criteria:
  • Contains at least one digit
  • Contains at least one lowercase letter
  • Contains at least one uppercase letter
  • Has a length between 8 and 16 characters
  1. Create a Java program that reads a string from the user, counts the number of vowels in it, and displays the result.
  2. Write a Java method that swaps two characters in a String without using a temporary variable.
  3. Write a Java program that validates an email address input by the user, ensuring it follows the standard email format (e.g., example@example.com).
  4. Create a Java program that reads a sentence from the user and counts the number of words in it, excluding any punctuation marks.
  5. Write a Java method that checks if a given string is a palindrome (reads the same backward as forward).

FAQ

  1. Why do I get an error when trying to use arithmetic operators on char variables?
  • Arithmetic operations on char values can produce unexpected results, as they are converted into integers (ASCII values) during the operation and then cast back to char. To avoid this issue, it's best to use comparison or relational operators when working with characters.
  1. How do I compare two Strings containing single characters?
  • When comparing Strings containing single characters, use the equals() method instead of the == operator. For example: "A".equals("A").
  1. What is the largest Unicode character that can be stored in a char variable?
  • A char variable can store any Unicode value between 0 and 65535, which corresponds to U+FFFF in hexadecimal notation. However, keep in mind that not all characters within this range are printable or meaningful.
  1. Why does my program throw a NumberFormatException when trying to convert a char to an integer?
  • The Character.getNumericValue() method can only be used for digits 0-9. If you try to convert a non-digit character, it will throw a NumberFormatException. To avoid this error, first check if the input is a digit using the isDigit() method before converting it to an integer.
  1. How can I swap two characters in a String without using a temporary variable?
  • You can use bitwise operators to swap two characters in a String without using a temporary variable. Here's an example:
public static void swap(String str, int i, int j) {
char temp = str.charAt(i);
str = str.substring(0, i) + str.charAt(j) + str.substring(i, j) + str.charAt(temp) + str.substring(j+1);
}
char | Java | XQA Learn