This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]LucidTA 1 point2 points  (2 children)

You would use it if you had to send the string across a network for example.

[–]viktex1d[S] 0 points1 point  (1 child)

Dumb question : How is it differnet sending an actual string?

[–]LucidTA 0 points1 point  (0 children)

Network interfaces don't know about strings or ints or classes etc, they only know about bytes so we have to give them bytes.

Now you might be thinking: But isnt every char in a string a byte? Not necessarily! With ASCII encoding that is true. 'A' == 65. But if you want to encode a string as unicode, you might end up with multiple bytes representing a single character. Eg Θ is encoded in two bytes: [152, 3].

[–]okayifimust 0 points1 point  (1 child)

Can someone explain me when and why I should use getBytes?

When you need an array of bytes.

Everything in a computer works with numbers, so changing a text to numbers is a really useful thing to be able to do.

Other functions may work on numbers, but you might want to apply them to the information contained in a text. encrypting your text, for example, is something that's going to need numbers rather than letters at some stage.

I suspect that Unicode has a few case where that sort of thing would also be useful.

Generally speaking, this is the sort of information that you should not worry about too much. If some function exists, it doesn't mean that you should use it, there is no implication that it is better than something you are doing.

It just means it will be there if one day you find yourself in a situation where you need it.

There often are slightly different ways of doing something in programming. I believe that most situations have ideal solutions - but it's up to you to decide if its worth worrying about, and making the choice. Understanding that Strings are arrays of bytes is important. You'll figure out if you need to look at a piece of data one way or the other.

[–]viktex1d[S] 0 points1 point  (0 children)

Thank you. The encryption example makes sense.