Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java CASE why do i get a complete differet int back with and without using ' '

Tags:

java

case

As a Java beginner I'm playing around with a case statement at this point.

I have set: int d = '1'; And with: System.out.println("number is: " + d);, this returns 51.

Now I found out that if I set it as: int d = 1;, it does return 1.

Now my question is why does it return 49 when I set it as '3'? What difference do the ' ' make?

My code that returns 49:

int a = '1';

    switch(a)
    {
        case '1' :
        System.out.println("Good");
        break;
        case '2' :
        case '3' :
        System.out.println("great");
        break;
        default :
        System.out.println("invalid");
    }
    System.out.println("value: " + a);
like image 252
Char Avatar asked Jul 01 '15 13:07

Char


2 Answers

'1' is the character '1', whose integer value is 49. Each character has a numeric value in the range from 0 to 2^16-1. Therefore 1 and '1' are different integer values.

like image 172
Eran Avatar answered Nov 01 '22 17:11

Eran


With ' (single quotes) around a character you tell the compiler that the value in between is a character (variable type char in Java). Generally, computers only understand numbers so characters get represented as numbers in memory as well. The value of the character '1' is 49. You want to actually save the value 1 in memory and use that to calculate things. So, you have to tell the compiler that you want this to be interpreted as an actual number and not as a character.

To summarize:

  • '1' is the character that prints the number 1
  • 1 is the actual number 1

This means 1 and '1' have different integer values.

You can look at the integer value of the most commonly used characters in coding here: ASCII Table

like image 21
mhlz Avatar answered Nov 01 '22 18:11

mhlz