Reputation: 15
I have the following method, where I am setting the value "9" in String. When I put this in byte and display the output then the value gets changed.
void method() {
String s = "9";
byte[] b = s.getBytes();
System.out.println("Byte value is: " + byte[0]);
}
Output:
Byte value is: 57
Here why is 9 getting converted to 57?
Upvotes: 0
Views: 235
Reputation: 385
In above example you need to correct the compilation problems first: It should code should be like :
System.out.println("Byte value is: " + b[0]);
And not
System.out.println("Byte value is: " + byte[0];
And regarding the output, You are assigning "9" as string and trying to fetch the byte[], basically getBytes encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. hence your getting "57".
Upvotes: 0
Reputation: 761
when you trying to get byte value from character you get only ASCII value.
character '9' ASCII code is 57
Upvotes: 0
Reputation: 11867
Because the character '9'
is ASCII value 57:
https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
ASCII character 9 would be a "tab" character
Upvotes: 3