2

The following code throws array index out of bound exception. I have initialized a size of 1000 yet not fully utilized. What exactly are the values of unused indices?

byte[] buffer=new byte[1000];
     String s="i am a stupid";
     buffer=s.getBytes();

     System.out.println(buffer[30]);

3 Answers 3

5

When you call the String#getBytesmethod you get a new array, initialized with the length equals to the number of bytes needed to represent the string. Due to Java docs:

Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

In your case it's length equals to length the string (13 bytes) and it's less then 30 anyway. That is the reason you get this exception, while trying to get the 30th element.

If you need to initialize your buffer variable with an array you become from string, you need to use System#arraycopy method:

byte[] byteAr = s.getBytes();
System.arraycopy(byteAr, 0, buffer, 0, byteAr.length);

If you wish to know, what are values used to initialize an array by default, so it's a default velues for datatype your array consist of. In case of bytes, the default value is 0.

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

Comments

2

Because buffer=s.getBytes(); doesn't use the array you just allocated. It makes buffer reference a completely new array which in your example won't have 30 members.

Comments

1

The buffer you allocate is no longer reachable when you reassign the reference. I think you wanted to use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) like

byte[] buffer=new byte[1000];
String s="i am a stupid";
byte[] bytes=s.getBytes();
System.arraycopy(bytes, 0, buffer, 0, bytes.length);

Note that buffer[30] will default to a value of 0.

3 Comments

Will this adjust my buffer size to the size of the string in byte array?
@VishalS no, your buffer size will be 1000, just first elements will be initialized from the string
I am checking the buffer's size to break out of the while loop in my code(if not 1000, i want to break). In that sense, can i check the length of bytes and buffer mentioned above. B'coz i want to break out if they are not equal.

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.