Vishal S
Vishal S

Reputation: 73

Array index out of bound exception java

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]);

Upvotes: 2

Views: 2424

Answers (3)

Stanislav
Stanislav

Reputation: 28106

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.

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201447

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.

Upvotes: 1

John3136
John3136

Reputation: 29265

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.

Upvotes: 2

Related Questions