Ben
Ben

Reputation: 215

Integer arithmetic with character

I have a simple block of code, can someone explain to me why this acceptable in Java?

int a = 10;
int c = 'A' + (a -1);
System.out.println(c);

The result of this displayed in compiler is: 74. So where exactly the values of seventies come from? Thanks for your answers.

Upvotes: 2

Views: 116

Answers (4)

Gowtham
Gowtham

Reputation: 351

When you assign value of one data type to another, the two types might not be compatible with each other. It should be casted to correct type:

There are 2 types:-

  • Widening or Automatic Type Conversion. which casts in this sequence:

byte -> short -> int -> long -> float -> double

char -> int

example :

int i = 100; //i is 100
float f = i; // f is 100.0 
  • Narrowing or Explicit Conversion. which casts in this sequence:

double -> float -> long -> int ->short -> byte

example:

double d = 100.100; //d is 100.100
int i = (int)d; //i is 100

So, When a Character value is used in integer context. It is automatically casted to int. In your case:

int a = 10;
int c = 'A' + (a -1); //c = 65 + (10-1)

'A' ascii value is 65, thus you get c = 74

Hope this helps.

Upvotes: 0

vincrichaud
vincrichaud

Reputation: 2208

In Java a char can be (explicitly or implicitly) casted to int, it then uses the ASCII value associated to this character.

It your case, the seventies comes from the character 'A'. The ASCII value of this character is 65. So the system implicitly does the casting 'A' → 65. Your calculation does:

c = 'A' + (a-1)
 ↓
c = 65 + (10-1)
 ↓
c = 74

Upvotes: 5

NiVeR
NiVeR

Reputation: 9806

The ascii value of 'A' is 65. Check this link for complete reference. The conversion occurs through (implicit) widening the char datatype to int datatype using its unicode value, which in this case for 'A' is 65 (jls 5.6.1).

Upvotes: 2

rahul
rahul

Reputation: 930

Char is implicitly converted into integer resulting 'A' = 65 so 65+9 = 74

Upvotes: 0

Related Questions