Arrays in Java: Types, Methods and the Arrays Class

Java array methods are built-in operations and static utilities from the java.util.Arrays class that let you sort, search, copy and print array contents without writing logic from scratch. Arrays in Java are fixed-size, zero-indexed objects stored on the heap. Core methods include Arrays.sort(), Arrays.binarySearch(), Arrays.copyOf(), Arrays.toString() and Arrays.fill().

Key Takeaways

  • In Java, arrays are objects stored on the heap, and their size is fixed at creation time.
  • Java supports one-dimensional, multi-dimensional and jagged arrays.
  • The java.util.Arrays class provides ready-to-use methods: sort(), toString(), binarySearch(), copyOf() and more.
  • Array length is accessed via the .length property, not a method call.
  • Java arrays don’t have a built-in indexOf(), but you can replicate it with Arrays.binarySearch() or a simple loop.

Array Basics in Java

An array in Java is a contiguous block of memory that holds elements of a single type, whether that’s int, String, double or any object. Every element has an index starting at zero. According to the Oracle Java documentation, arrays are first-class objects in Java, which means they inherit from java.lang.Object and can be passed as method arguments.

Declaring and initialising an array looks like this:

  • Declaration: int[] marks;
  • Instantiation: marks = new int[5];
  • Shorthand initialisation: int[] marks = {85, 90, 78, 92, 88};

The shorthand form is what you’ll use most often in real code. If you declare an array without initialising it and then try to access an element, Java throws an ArrayIndexOutOfBoundsException. That’s one of the most common runtime errors beginners hit, and you can read more about handling those in our guide to Java exceptions and common runtime errors.

How to Find Array Length

The java array length function isn’t actually a function. It’s a property. You access it as arrayName.length with no parentheses. So for int[] marks = {85, 90, 78, 92, 88};, calling marks.length returns 5.

A common mistake is writing marks.length() with parentheses, which causes a compile-time error because length is a field, not a method. This trips up students who’ve been working with String.length(), which is a method. Keep the two separate in your head and you’ll avoid a frustrating debug session.

Default Values

When you create an array without explicitly setting values, Java fills it with defaults: 0 for numeric types, false for booleans and null for object types. This behaviour is predictable, which makes arrays safer to work with than uninitialized variables in C. If you’re coming from a C background, our article on how to write, compile and run a C program shows the contrast clearly.

Types of Arrays in Java

There are three main types of array in Java: one-dimensional, multi-dimensional and jagged. Each serves a different purpose and understanding when to use which one is a practical skill interviewers test at campus placements in institutions like NITs, VIT and BITS. According to NASSCOM’s 2024 India IT Workforce Report, Java remains the most in-demand language for entry-level backend roles in Indian IT services firms, making array fundamentals a direct placement asset.

One-Dimensional Arrays

This is the simplest form. A single row of elements, all the same type. Example: String[] cities = {"Mumbai", "Delhi", "Bengaluru", "Hyderabad"};. You’ll use 1D arrays for storing lists, scores, names or any flat sequence of data.

Multi-Dimensional Arrays

A 2D array is essentially an array of arrays, which makes it ideal for representing grids, matrices or tabular data. You declare one as int[][] matrix = new int[3][4];, giving you 3 rows and 4 columns. A 3D array adds another dimension but is far less common in everyday application code.

Jagged Arrays

Jagged arrays are multi-dimensional arrays where each row can have a different number of columns. This matters when your data isn’t rectangular. A practical Indian university example: storing semester marks for students under the CBCS (Choice Based Credit System) used across Indian universities, where each student may have a different number of elective subjects per semester. You declare the outer array first, then assign each row separately:

  • int[][] jagged = new int[3][];
  • jagged[0] = new int[2];
  • jagged[1] = new int[4];
  • jagged[2] = new int[3];

Jagged arrays save memory compared to a full rectangular 2D array when your data is sparse. That’s a real optimisation concern in backend development roles, which is one reason understanding the difference between full stack and software developer roles matters for choosing what to study deeply.

Arrays Class Methods in Java

The java.util.Arrays class is the standard toolkit for working with arrays in Java. You import it with import java.util.Arrays; and then call its static methods directly. According to the Oracle API documentation for Java SE 21, the class was introduced in Java 1.2 and has grown significantly with each release. Java remains the second most popular language on the TIOBE Index as of early 2025, which makes knowing these utilities genuinely valuable.

Core Methods at a Glance

Method What It Does Example Usage
Arrays.sort(arr) Sorts the array in ascending order in place Arrays.sort(marks);
Arrays.toString(arr) Returns a readable string representation System.out.println(Arrays.toString(marks));
Arrays.binarySearch(arr, key) Searches a sorted array for a key; returns index or negative value Arrays.binarySearch(marks, 90);
Arrays.copyOf(arr, len) Copies the array into a new array of the specified length Arrays.copyOf(marks, 3);
Arrays.copyOfRange(arr, from, to) Copies a specified range of the array into a new array Arrays.copyOfRange(marks, 1, 4);
Arrays.fill(arr, val) Fills every element with the given value Arrays.fill(marks, 0);
Arrays.equals(arr1, arr2) Returns true if both arrays are equal in length and content Arrays.equals(a, b);
Arrays.asList(arr) Converts array to a fixed-size List Arrays.asList(cities);

How to Sort an Array in Java with Arrays.sort()

Arrays.sort() uses a dual-pivot quicksort for primitive types and a TimSort for object arrays, both of which are O(n log n) on average. You don’t need to implement sorting yourself for standard use cases. Just call it and your array is sorted.

One thing that catches people out: Arrays.sort() modifies the original array. If you need the original order preserved, use Arrays.copyOf() first to make a copy, then sort the copy.

Arrays.binarySearch() and the indexOf Question

Java arrays don’t have an indexOf() method directly, which surprises developers coming from JavaScript or Python. The closest built-in option is Arrays.binarySearch(), but it only works correctly on a sorted array. If the array is unsorted, the result is undefined.

For an unsorted array, the practical workaround is a simple loop:

  • Iterate from index 0 to arr.length - 1.
  • Compare each element to your target using == for primitives or .equals() for objects.
  • Return the index when you find a match, or -1 if the loop ends without one.

Alternatively, convert the array to a List with Arrays.asList() and call list.indexOf(value). That works for object arrays (like String[]) but not for primitive arrays like int[] directly, since autoboxing doesn’t apply cleanly there.

Java Array vs ArrayList: When to Use Which

In production Java code, raw arrays are less common than ArrayList or other collections because collections are resizable. Arrays still appear in performance-critical code, image processing buffers, cryptographic byte arrays and network packet handling. The key rule: use an array when size is fixed and performance matters; use an ArrayList when you need dynamic resizing or collection utility methods.

Common Array Tasks

Knowing the theory is one thing. Knowing which java array methods to reach for in real situations is what separates a prepared candidate from the rest in a placement interview at TCS, Infosys or a product startup.

Printing an Array

Printing an array directly with System.out.println(arr) gives you a memory address reference, not the values. Use Arrays.toString(arr) for a 1D array and Arrays.deepToString(arr) for multi-dimensional arrays. This is one of those situations you only encounter once, but it’s worth knowing before your first lab exam.

Copying an Array: Arrays.copyOf vs System.arraycopy

Using assignment (arr2 = arr1) doesn’t copy an array, it copies the reference. Both variables point to the same underlying data. Change one and you change both. Use Arrays.copyOf(arr, arr.length) for a clean one-liner, or System.arraycopy() when you need to copy into an existing destination array with precise control over offsets. Both produce a true independent copy.

Iterating Over Arrays

The enhanced for-loop (for (int val : marks)) is clean and readable for simple iteration. Use a standard indexed loop when you need the index itself, for example when you’re updating values in place or comparing adjacent elements. Both are valid; pick the one that matches what you’re actually doing.

Strong array fundamentals feed directly into data structures like linked lists, stacks and queues, and those feed into algorithm rounds in technical interviews. If you’re a BCA or BTech student mapping out your learning path, check what topics matter most in our breakdown of BSc Computer Science subjects and scope.

Arrays in Real Projects

According to the Stack Overflow Developer Survey 2024, Java ranks in the top five most-used languages among professional developers globally, meaning array handling is a skill that stays relevant well into a working career. If you’re thinking about where Java skills take you professionally, our guide to jobs and salary after MCA breaks down the roles and pay bands where Java is most in demand.

Before choosing which tools and languages to invest time in, it’s also worth reading about the software development tools to learn first, since Java’s ecosystem (IDEs, build tools, version control) is as important as the language itself.

What to do next: You’ve got a solid grip on java array methods and the Arrays class. Here are three steps to take this week.

  1. Write a Java program that takes an array of 10 integers, sorts it with Arrays.sort(), searches for a value with Arrays.binarySearch() and prints the result with Arrays.toString(). Run it in IntelliJ IDEA or VS Code.
  2. Practice one jagged array problem from a platform like LeetCode or GeeksforGeeks, specifically one that models uneven data like a student-subject marks scenario.
  3. If you’re building toward a career in cybersecurity, AI or ethical hacking, Java and secure coding fundamentals are your starting point. Explore 3.0 University’s online certification courses or jump straight into the CEH v13 AI online course, where programming logic underpins everything from writing exploits to understanding malware behaviour.

Frequently Asked Questions

What are arrays in Java?

In Java, arrays are fixed-size, ordered data structures that store multiple elements of the same type under a single variable name. They are objects stored on the heap, indexed from zero, and their size is set at creation and cannot change. The java.util.Arrays class provides methods to sort, search and manipulate them.

What are the types of arrays in Java?

Java supports three types: one-dimensional arrays (a single row of elements), multi-dimensional arrays (arrays of arrays, such as a 2D matrix) and jagged arrays (multi-dimensional arrays where each row has a different number of columns). Choosing the right type depends on whether your data is flat, grid-like or irregular.

What methods does the Arrays class have?

The java.util.Arrays class includes sort(), toString(), deepToString(), binarySearch(), copyOf(), copyOfRange(), fill(), equals(), deepEquals() and asList(). All methods are static, so you call them as Arrays.methodName() without creating an instance of the class.

How do I find array length in Java?

You access the .length property directly on the array variable, for example marks.length. It’s a field, not a method, so no parentheses are needed. Writing marks.length() causes a compile-time error. For multi-dimensional arrays, arr.length gives the number of rows and arr[0].length gives the number of columns in the first row.

Is there an indexOf method for Java arrays?

Java arrays don’t have a built-in indexOf() method. For sorted arrays, use Arrays.binarySearch(arr, key), which returns the index if found or a negative value if not. For unsorted arrays, either loop manually comparing each element, or convert the array to a List using Arrays.asList(arr) and call list.indexOf(value) on the result.

What is the difference between a Java array and an ArrayList?

A Java array has a fixed size set at creation and cannot grow or shrink. An ArrayList is a resizable collection from the java.util package that can add or remove elements dynamically. Arrays are faster for indexed access and use less memory overhead; ArrayList is more flexible for data whose size changes at runtime.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles