saskoch
saskoch

Reputation: 59

Why doesn't my compare work between char and int in Java?

char c = '0';
int i = 0;
System.out.println(c == i);

Why does this always returns false?

Upvotes: 2

Views: 28121

Answers (4)

Vijay Gajera
Vijay Gajera

Reputation: 1364

The char and int value can not we directly compare we need to apply casting. So need to casting char to string and after string will pars into integer

char c='0';
int i=0;

Answer is like

String c = String.valueOf(c);

System.out.println(Integer.parseInt(c) == i)

It will return true;

Hope it will help you

Thanks

Upvotes: 1

Tudor
Tudor

Reputation: 62439

The char c = '0' has the ascii code 48. This number is compared to s, not '0'. If you want to compare c with s you can either do:

if(c == s) // compare ascii code of c with s

This will be true if c = '0' and s = 48.

or

if(c == s + '0') // compare the digit represented by c 
                 // with the digit represented by s

This will be true if c = '0' and s = 0.

Upvotes: 10

juliomalegria
juliomalegria

Reputation: 24921

You're saying that s is an Integer and c (from what I see) is a Char.. so there you, that's the problem: Integer vs. Char comparation.

Upvotes: -3

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

Although this question is very unclear, I am pretty sure the poster wants to know why this prints false:

char c = '0';
int i = 0;
System.out.println(c == i);

The answer is because every printable character is assigned a unique code number, and that's the value that a char has when treated as an int. The code number for the character 0 is decimal 48, and obviously 48 is not equal to 0.

Why aren't the character codes for the digits equal to the digits themselves? Mostly because the first few codes, especially 0, are too special to be used for such a mundane purpose.

Upvotes: 23

Related Questions