Concepts / Static Methods in Java

Static Methods in Java

The standard array-processing methods are static methods defined in the Arrays class, which is in the java.util package.

  • Programming

Why Java Provides Ready-Made Array Helpers

Suppose you have an array and you need a second array with the same contents. You could write a loop that creates a new array of the same size and copies each element across, one index at a time. That works, but it is repetitive, and every programmer who needs a copy would write the same loop again.

Java anticipates this need. It ships with a set of standard array-processing methods so that common jobs like copying do not have to be hand-written each time. This article works through three practical questions: where these methods live, how you call them, and what you should expect when you use them. Keep the copying problem in mind as you read, because copying is the example the source uses to introduce the whole group.

Where the Array Methods Are Defined

Definition

The standard array-processing methods are static methods defined in the Arrays class, which is in the java.util package.

Two pieces of that definition matter. First, the methods belong to the class Arrays, not to any individual array variable. Second, the class lives in the java.util package, so a program that uses it needs to bring it into scope with an import statement, as the code in the next section shows.

Because these methods are static, you reach them through the class name itself. You do not first create an Arrays object and then ask it to copy something. Whether you are working with a small array of numbers or a large one, the method is reached through the same class name, and the array you want to process is passed in as an argument.

Tracing a Copy Step by Step

Before reading the mechanics, try to predict what happens. The code below creates an array, makes a copy with Arrays.copyOf, and then changes the first element of the copy. The question is whether that change shows up in the original.

java
Output
1
99
Notes on the code
  • The import line brings the Arrays class from java.util into this file.
  • Arrays.copyOf is a static method called on the class name, with no Arrays object created.
  • The second argument is the length of the new array; here it matches the original.
  • Changing copy[0] only touches the copy, so the original still holds 1.

What do you think happens?

After copy[0] is set to 99, what does original[0] print?

  • 1

  • 99

  • 0

Reveal answer
Answer:

1

A copy returned by a copying method is a separate array, so changing it does not change the original. The original still holds its own first value, 1.

The reason is that Arrays.copyOf does not hand you a second name for the same array. It returns a new array that holds the same values. The original is not the thing that gets returned; the new array is.

originalvariablefirst array1, 2, 3copyvariablesecond array1, 2, 3refers torefers to
After copyOf runs, are the original and the copy two separate arrays in memory, or do both variables point to the same array?

The diagram shows two variables, each referring to its own array. Both arrays start with the same values, but they are separate objects. Changing one leaves the other alone. Read it from left to right: the original array was passed in, and the separate array that came back is the one the copy variable refers to.

Calling a Static Method on the Class Name

Read the call Arrays.copyOf(myArray, 5) from left to right. The part before the dot names the class that owns the method. The part after the dot names the method. The values inside the parentheses are the arguments, which are the data the method works on. No object is created, because a static method belongs to the class rather than to any one instance.

Arraysclass that owns the methodcopyOfstatic method namemyArrayfirst argument: array tocopy5second argument: new length
What parts of the call Arrays.copyOf(myArray, 5) identify the class, the method, and the arguments, and why is no object needed?

Copying an Array with Arrays.copyOf

Worked example

Copying a Score List

Given an int array named scores holding 80, 95, and 70, create a copy called backup and confirm that changing backup does not change scores.

  1. 1
    Import the class

    Add import java.util.Arrays; so the Arrays class from java.util is available.

  2. 2
    Call the static method

    Write Arrays.copyOf(scores, scores.length). The class name comes first, then the method, then the array and the new length.

  3. 3
    Store the result

    Assign the returned array to a new variable, backup. This variable refers to the new array, not to scores.

  4. 4
    Change the copy

    Set backup[1] to 0. Only the copy's element changes.

  5. 5
    Check the original

    scores[1] is still 95, because the two arrays are separate.

Result

scores still holds 80, 95, 70 and backup holds 80, 0, 70.

java
Output
[80, 95, 70]
[80, 0, 70]
Notes on the code
  • Arrays.toString is another static method in the Arrays class, used here only to print both arrays.
  • The original scores array keeps its values after the copy is modified.

Changing the Length During a Copy

The second argument to Arrays.copyOf sets the length of the new array, and it does not have to match the original. When the new length is larger, the extra positions are filled with default values. For an int array, the default value is 0. When the new length is smaller, the copy keeps only the elements that fit.

index 01index 01index 12index 12index 23index 23index 30 (default)index 40 (default)
When the new length is longer than the original, which indexes keep their values, and which are filled with default values?
java
Output
[1, 2, 3, 0, 0]
[1, 2]
Notes on the code
  • The length 5 copy pads the two extra positions with the default int value 0.
  • The length 2 copy drops the element at index 2, which does not fit.

One Method Name, Many Array Types

The source makes a point that is easy to skim past: the methods in the Arrays class, copyOf included, come in multiple versions, and each version is meant for a different array type. Arrays.copyOf is therefore not one method that handles every kind of array in exactly one way. It is a family of methods that share a name, with each member written for one kind of array.

When you call the method, Java selects the version that matches the array you pass in. You do not need to remember a separate name for each array type. You need to make sure the array you pass in is the type you intend to copy, because the returned array has that same element type.

Array passed inCallReturned type
int[]Arrays.copyOf(intArray, n)int[]
double[]Arrays.copyOf(doubleArray, n)double[]
String[]Arrays.copyOf(stringArray, n)String[]

Same method name, one version per array type, with the call shape unchanged.

Mistakes Beginners Make with Arrays.copyOf

  • Common mistake

    Assigning the array directly instead of copying it

    What it looks like
    int[] backup = scores;
    Why it fails

    This makes backup a second name for the same array, so changes through either name affect the same values.

    Do this instead

    Use int[] backup = Arrays.copyOf(scores, scores.length); to get a separate array.

  • Common mistake

    Forgetting the import

    What it looks like

    Calling Arrays.copyOf in a file with no import java.util.Arrays; line.

    Why it fails

    The Arrays class lives in java.util, so it is not visible to the program without the import.

    Do this instead

    Add import java.util.Arrays; at the top of the file.

  • Common mistake

    Creating an Arrays object before calling the method

    Why it fails

    The method is static and belongs to the class, so the call is made on the class name directly.

    Do this instead

    Write Arrays.copyOf(...) and pass the array as an argument.

  • Common mistake

    Expecting a shorter copy to keep every element

    What it looks like
    Arrays.copyOf({1, 2, 3}, 2) gives [1, 2].
    Why it fails

    A smaller length keeps only the elements that fit, so the last values are dropped.

    Do this instead

    Choose a length at least as large as the number of elements you need to keep.

Practice: Copy and Predict

EASY

Given int[] data = {4, 8, 15}; create a copy called extra with length 4 using Arrays.copyOf, then set extra[0] to 100. What does data[0] print, and what does Arrays.toString(extra) print?

Hints
  • Arrays.copyOf returns a new array, so the change to extra does not reach data.
  • The fourth position in the new array is filled with the default int value 0.
  • Print the copy with Arrays.toString, which is also a static method in the Arrays class.

Key Takeaways

  • The standard array-processing methods are static methods defined in the Arrays class, which is in the java.util package.
  • You call a static method on the class name, such as Arrays.copyOf(myArray, 5), and pass the array as an argument; no object is created.
  • A copy returned by Arrays.copyOf is a separate array, so changing it does not change the original.
  • The second argument sets the new length: longer copies pad with default values, and shorter copies drop the elements that do not fit.
  • Methods in the Arrays class come in multiple versions, one per array type, so the same name works across int[], double[], and String[] arrays.