February 15, 2002

Q: This question seems easy, but nonetheless I have no idea how to do it. I have a byte array: a[100] . Is there a simple way to copy only from a[0] to byte a[50] ? (I don't want to use a for/while loop.)

A: You're correct, the answer is really simple. The problem is that the answer lies in one of those classes everyone seems to overlook: java.lang.System. System includes the following method that does what you need:

public static void arraycopy(Object src,
                     int src_position,
                     Object dst,
                     int dst_position,
                     int length)

So, to copy your array, try the following:

byte [] dst = new byte[50];
System.arraycopy( a, 0, dst, 0, 50 );

Java developers also overlook the java.util.Arrays class. While Arrays won't help you with your copy problem, it will help you sort and fill your arrays.

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in bridging disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer, as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Learn more about this topic