Arrays in Java
An array is a fixed size object holding elements of one type, indexed from zero, with the length fixed at creation.
-
Java Basics
- Introduction to Java
- Setting Up Java and Writing Your First Program
- Variables, Data Types and Literals in Java
- Type Casting and Type Conversion in Java
- Operators and Expressions in Java
- Input and Output in Java
- Comments, Keywords and Naming Conventions in Java
- Control Flow in Java: if, else and switch
- Loops in Java: for, while and do-while
- Methods
- Arrays and Strings
-
OOP
- Classes and Objects in Java
- Constructors in Java
- The this Keyword in Java
- The static Keyword in Java
- Encapsulation in Java
- Access Modifiers in Java
- Inheritance in Java
- Method Overriding and super in Java
- Polymorphism in Java
- Abstraction, Abstract Classes and Interfaces in Java
- Composition, Aggregation and Association in Java
- The Object Lifecycle in Java
- Core Java
- Exception Handling
-
Collections
- The Java Collections Framework
- List in Java: ArrayList, LinkedList, Vector and Stack
- Set in Java: HashSet, LinkedHashSet and TreeSet
- Map in Java: HashMap, LinkedHashMap and TreeMap
- How HashMap Works Internally in Java
- Queue and Deque in Java: ArrayDeque and PriorityQueue
- Iterators in Java
- Comparable and Comparator in Java
- Collections Utilities and Choosing the Right Collection
- Generics
- Java 8+
- Stream API
- Date and Time
- File and I/O
-
Multithreading
- Threads in Java: Processes, Runnable and Thread
- Thread Lifecycle in Java
- Synchronization in Java: synchronized and volatile
- Locks and Atomic Classes in Java
- Race Conditions and Deadlocks in Java
- The Executor Framework and Thread Pools in Java
- Future and CompletableFuture in Java
- Concurrent Collections in Java
- The Java Memory Model
- JVM and Memory
- Advanced Java
- Networking
- JDBC
- Testing
Definition
An array is an object that holds a fixed number of values of a single type. Elements are reached by an index that starts at zero, and the size is decided when the array is created and can never change afterwards.
Why arrays exist
- Constant time access to any element by position.
- A compact, predictable memory layout.
- The foundation on which
ArrayList,Stringand most collections are built.
Declaring and creating
int[] marks = new int[5]; // five elements, all 0
String[] names = new String[3]; // three elements, all null
int[] scores = {45, 78, 62, 91}; // shorthand, size inferred as 4
int[] copy = new int[]{1, 2, 3}; // full form, needed when not declaringThe brackets belong to the type. int[] marks is preferred over the legal but discouraged int marks[], because the type is then written in one piece.
Default values
| Element type | Default |
|---|---|
| Numeric primitives | 0 or 0.0 |
boolean | false |
char | the null character |
| Any reference type | null |
An array of objects contains references, not objects.new String[3]creates three null slots, not three strings. Forgetting this produces aNullPointerExceptionon the first use.
Reading and writing
int[] scores = {45, 78, 62, 91};
System.out.println(scores.length); // 4 - a field, not a method
System.out.println(scores[0]); // 45
System.out.println(scores[scores.length - 1]); // 91
scores[2] = 70;
// scores[4] = 10; // throws ArrayIndexOutOfBoundsExceptionNote the inconsistency worth memorising: an array uses length as a field, a String uses length() as a method, and a collection uses size().
Traversing
int[] scores = {45, 78, 62, 91};
for (int i = 0; i < scores.length; i++) { // index available
System.out.println(i + ": " + scores[i]);
}
for (int score : scores) { // values only
System.out.println(score);
}Common operations with java.util.Arrays
import java.util.Arrays;
int[] values = {40, 10, 30, 20};
Arrays.sort(values); // 10 20 30 40, sorts in place
System.out.println(Arrays.toString(values));
int position = Arrays.binarySearch(values, 30); // 2, requires a sorted array
int[] copy = Arrays.copyOf(values, 6); // padded with zeros
int[] part = Arrays.copyOfRange(values, 1, 3); // 20 30, end is exclusive
Arrays.fill(copy, 7);
System.out.println(Arrays.equals(values, copy)); // element by elementCopying correctly
int[] original = {1, 2, 3};
int[] alias = original; // NOT a copy, same object
int[] real = Arrays.copyOf(original, original.length); // a real copy
alias[0] = 99;
System.out.println(original[0]); // 99 - the alias shared the array
System.out.println(real[0]); // 1Arrays and collections
String[] cities = {"Pune", "Kochi", "Surat"};
List<String> fixed = Arrays.asList(cities); // fixed size view, writes through
List<String> flexible = new ArrayList<>(Arrays.asList(cities)); // independent
String[] back = flexible.toArray(new String[0]);Arrays.asList returns a view. Adding or removing throws UnsupportedOperationException, and setting an element changes the original array.
Comparing arrays
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false - different objects
System.out.println(a.equals(b)); // false - Object identity, not contents
System.out.println(Arrays.equals(a, b)); // trueArrays do not override equals, hashCode or toString. Printing an array directly shows a type marker and a hash, which is why Arrays.toString exists.
Common mistakes
- Looping to
i <= lengthand stepping past the last index. - Using
length()on an array orlengthon aString. - Expecting an array to grow. Use
ArrayListwhen the size changes. - Calling
binarySearchon an unsorted array, which returns a meaningless result rather than failing. - Assigning one array variable to another and believing it copied.
Best practices
- Prefer
Listin application code, and keep arrays for fixed size data, primitives and performance sensitive work. - Never return an internal array directly from a getter; return a copy or an unmodifiable list.
- Use the enhanced
forloop unless the index is needed. - Use
Arrays.toStringfor one dimension andArrays.deepToStringfor more.
Practice
- Write a method that returns the second largest value in an
int[], handling arrays that are too short. - Predict the output of
System.out.println(new int[]{1, 2});and explain it. - Why does
Arrays.asList(new int[]{1, 2, 3}).size()return 1? - Reverse an array in place, without allocating a second array.
- Explain the difference between
a.equals(b)andArrays.equals(a, b).
Conclusion
An array is a fixed size object of one element type with zero based indexing. Learn Arrays.toString, sort, copyOf and equals early, and reach for a List as soon as the size needs to change.