0

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?

2
  • 2
    Because String.getBytes() does not do what you think it does. Read the API documentation. Commented May 13, 2014 at 9:45
  • Because the character '9' is 57. Commented May 13, 2014 at 10:18

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I want to get a number from user, which is always between 0 to 9. I want to store the user's input in byte variable rather than short or int. I want to further use this input in IF statement later in the code. How can I achieve this?
Why do you want to store in a byte?
Use the parseByte method of the Byte class.
2

57 is the ASCII code for the character '9'

Comments

0

when you trying to get byte value from character you get only ASCII value.

character '9' ASCII code is 57

Comments

0

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".

1 Comment

Thanks! Actually my code is OK. Its a typo while posting :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.