Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Mathematical Operations on char | Basic Types, Operations
Java Basics
course content

Course Content

Java Basics

Java Basics

1. Getting Started
2. Basic Types, Operations
3. Loops
4. Arrays
5. String

book
Mathematical Operations on char

Why are mathematical operations possible on the char type?

The char data type is quite interesting. It stores characters, but you can also perform operations on this data type.

What will be the result of executing this code?

java

Main

copy
1234567891011
package com.example; public class Main { public static void main(String[] args) { char firstLetter = 'A'; char secondLetter = '('; // We use type casting here to convert value from `int` to `char` char result = (char) (firstLetter + secondLetter); System.out.println(result); } }

One might have thought that the result would be A(, but as we can see, the result is i. Why is that? char is not purely a character data type; it takes characters from the ASCII table. The character A corresponds to the number 65 in the table, while the character ( corresponds to the number 40. As you may have guessed, the character i corresponds to 105, as 65 + 40 = 105. It's important to know this because it allows us to operate on the char data type excellently and flexibly.

Here is a link to the ASCII table.

Casting

In the code above, you might have noticed this unusual syntax:

But why is (char) required? The addition operation returns a result of type int because it sums the numeric codes of the characters. To store this result in a variable of type char, an explicit conversion is necessary. This is exactly what the (char) construct does—it converts the numeric value back into a character.

In our example, the result of the addition is the number 105. The (char) construct converts this number into the character corresponding to code 105 in the ASCII table, which happens to be the character i.

Why can we perform mathematical operations on char?

Why can we perform mathematical operations on char?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt