0

I came across an array declaration that looks like this:

byte [] byteArray = StringFormatter.padWithSpacesTo("", 1000).getBytes();

After that line the following lines are used:

    putBytes(byteArray, name, 0);
    putBytes(byteArray, addressLine1, 100);

What is this array declaration doing?

3
  • 1
    This is the byte representation of 1000 spaces in platform default encoding. Commented Apr 23, 2015 at 12:36
  • As it is, the question is too broad. Which is the part that you don't understand? Commented Apr 23, 2015 at 12:42
  • My doubt was why do we need to create a byte array like this. We could have used **byte[] byteArray = new byte[1000];**Please see the next lines of code in the update section. Commented Apr 23, 2015 at 13:44

1 Answer 1

4

It uses the StringFormatter to create a 1000 character string filled with spaces. It then uses getBytes() to return that as a byte array.

So it creates an array 1000 characters long, filled with ' ' in platform default encoding (so almost certainly 32).

This isn't really a very good way to do things...a better approach would be Arrays.fill

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

4 Comments

Can we use byte[] byteArray = new byte[1000]; instead of the above piece of code?
@Leo Yes, that would be the correct way. Be aware though that the new array will be filled with 0 rather than 32. If you need the 32s then use Arrays.fill.
what do you mean by "0 rather than 32"? Is it the Ascii values? If yes then will there be any difference considering the following codes in the update section?
@leo yes. Because unless you do the fill then everything you don't write to is going to be filled with 0, not with spaces.

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.