Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing Char Type In Java

Tags:

java

char

While practicing Java I randomly came up with this:

class test {     public static void main(String arg[])     {         char x='A';         x=x+1;         System.out.println(x);     } } 

I thought it will throw an error because we can't add the numeric value 1 to the letter A in mathematics, but the following program runs correctly and prints

B  

How is that possible?

like image 972
Mahesh Nadar Avatar asked Jun 15 '13 15:06

Mahesh Nadar


People also ask

Can char be incremented in Java?

You can't. Strings are immutable. You can just reference a new string object that has 0 characters.

What does char ++ do in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.


1 Answers

In Java, char is a numeric type. When you add 1 to a char, you get to the next unicode code point. In case of 'A', the next code point is 'B':

char x='A'; x+=1; System.out.println(x); 

Note that you cannot use x=x+1 because it causes an implicit narrowing conversion. You need to use either x++ or x+=1 instead.

like image 95
Sergey Kalinichenko Avatar answered Sep 22 '22 13:09

Sergey Kalinichenko