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);
'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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With