Java for Beginners · Module 5: Data and Methods
🎯 Why Arrays?
To store the marks of 100 students you would not create 100 separate variables. An array stores many values of the same type under one name, in a fixed-size row, and you reach each one with a number called the index.
1️⃣ Creating and Using Arrays
int[] scores = {60, 75, 80, 95};[0]75
[1]80
[2]95
[3]
length - 1 = 3.Figure 1: An array is a row of boxes, each with an index.
- Declare and size it:
int[] marks = new int[5];makes room for 5 ints. - Declare with values:
int[] scores = {60, 75, 80, 95};The size is the number of values. - Read or write one element:
marks[1]. - Size:
marks.length. It has no brackets because it is a field, not a method.
| Element type | Default value |
int, short, byte, long | 0 |
double, float | 0.0 |
boolean | false |
char | character with code 0 |
String and other objects | null |
Figure 2: What an array holds before you assign anything.
Program 1: Array basics
public class ArrayBasics {
public static void main(String[] args) {
int[] marks = new int[5];
marks[0] = 70;
marks[1] = 85;
marks[2] = 90;
System.out.println("length = " + marks.length);
System.out.println("marks[1] = " + marks[1]);
System.out.println("marks[4] (not set) = " + marks[4]);
int[] scores = {60, 75, 80, 95};
for (int i = 0; i < scores.length; i++) {
System.out.println("scores[" + i + "] = " + scores[i]);
}
String[] names = new String[2];
double[] prices = new double[2];
boolean[] flags = new boolean[2];
System.out.println(names[0] + " " + prices[0] + " " + flags[0]);
}
}
length = 5
marks[1] = 85
marks[4] (not set) = 0
scores[0] = 60
scores[1] = 75
scores[2] = 80
scores[3] = 95
null 0.0 false
- Elements you never set hold the default for their type: 0 for int, 0.0 for double, false for boolean and
nullfor objects. - The loop condition
i < scores.lengthvisits indexes 0 to 3 exactly. A for loop is the natural partner of an array (Lesson 19).
2️⃣ Common Array Operations
| Task | Code |
| Number of elements | a.length (no brackets!) |
| Print an array nicely | Arrays.toString(a) |
| Sort | Arrays.sort(a) |
| Copy | Arrays.copyOf(a, a.length) or a.clone() |
| Compare contents | Arrays.equals(a, b) |
| Search a sorted array | Arrays.binarySearch(a, key) |
Figure 4: Everyday array tools. Import java.util.Arrays.
Program 2: Sum, maximum, minimum, sort and reverse
import java.util.Arrays;
public class ArrayOps {
public static void main(String[] args) {
int[] a = {42, 7, 19, 3, 25};
int sum = 0, max = a[0], min = a[0];
for (int x : a) {
sum += x;
if (x > max) max = x;
if (x < min) min = x;
}
System.out.println("sum = " + sum + ", max = " + max + ", min = " + min);
System.out.println("average = " + (double) sum / a.length);
int[] copy = Arrays.copyOf(a, a.length);
Arrays.sort(copy);
System.out.println("original = " + Arrays.toString(a));
System.out.println("sorted = " + Arrays.toString(copy));
System.out.println("index of 19 in sorted = " + Arrays.binarySearch(copy, 19));
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
System.out.println("reversed = " + Arrays.toString(a));
}
}
sum = 96, max = 42, min = 3
average = 19.2
original = [42, 7, 19, 3, 25]
sorted = [3, 7, 19, 25, 42]
index of 19 in sorted = 2
reversed = [25, 3, 19, 7, 42]
- Start
maxandminwith the first element, not with 0, so the result is right even when all numbers are negative. - The cast
(double) sumkeeps the fraction of the average (Lesson 9). Arrays.sortchanges the array it is given, so the program sorts a copy to keep the original order.binarySearchworks only on a sorted array and returns the index where the value sits.- Reversing swaps the first and last elements, then the second and second-last, with two indexes moving towards each other. The three-line swap with
texchanges two values.
Program 3: Counting with an array (frequency)
public class Freq {
public static void main(String[] args) {
int[] votes = {2, 0, 1, 2, 2, 1, 0, 2};
int[] count = new int[3];
for (int v : votes) {
count[v]++;
}
for (int i = 0; i < count.length; i++) {
System.out.println("Candidate " + i + ": " + count[i]);
}
}
}
Candidate 0: 2
Candidate 1: 2
Candidate 2: 4
- Each vote is used as an index into
count, socount[v]++adds one to that candidate’s tally. This trick is the basis of many counting problems.
3️⃣ Arrays Are Objects: Copying Is Not What It Looks Like
An array variable does not hold the values. It holds a reference (an address) to the array in memory. So b = a does not copy the array. It makes both names point to the same array.
a ➜ [99, 2, 3] (one array in memory) ⬅ bc = a.clone() ➜ [99, 55, 3] (a separate copy)Figure 3: b = a shares one array. clone() makes a new one.
import java.util.Arrays;
public class RefDemo {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println("a = " + Arrays.toString(a));
System.out.println("a == b ? " + (a == b));
int[] c = a.clone();
c[1] = 55;
System.out.println("a = " + Arrays.toString(a));
System.out.println("c = " + Arrays.toString(c));
System.out.println("a == c ? " + (a == c));
System.out.println("Arrays.equals(a, new int[]{99,2,3}) ? " + Arrays.equals(a, new int[]{99, 2, 3}));
System.out.println(a);
}
}
a = [99, 2, 3]
a == b ? true
a = [99, 2, 3]
c = [99, 55, 3]
a == c ? false
Arrays.equals(a, new int[]{99,2,3}) ? true
[I@12a3a380
- Changing
b[0]also changeda, because there is only one array. clone()makes a real copy, so changingcleavesaalone.==on arrays asks “same array?”, not “same contents?”. UseArrays.equalsto compare contents.- Printing an array directly gives something like
[I@12a3a380: the type and an address. The exact digits differ on each run. UseArrays.toString.
4️⃣ Errors Beginners Meet
Index outside the array (runtime)
public class Oob {
public static void main(String[] args) {
int[] a = new int[3];
for (int i = 0; i <= a.length; i++) {
a[i] = i * 10;
}
}
}
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Oob.main(Oob.java:5)
- The array has indexes 0, 1, 2. The loop condition
i <= a.lengthreaches 3. Usei < a.length. Java checks every index, which is why it stops safely instead of damaging memory.
A negative size (runtime)
public class Neg {
public static void main(String[] args) {
int[] a = new int[-2];
}
}
Exception in thread “main” java.lang.NegativeArraySizeException: -2
at Neg.main(Neg.java:3)
length() instead of length, and wrong element type
public class Bad4 {
public static void main(String[] args) {
int[] a = new int[3];
int n = a.length();
String s = a[1];
}
}
Bad4.java:4: error: cannot find symbol
int n = a.length();
^
symbol: method length()
location: variable a of type int[]
Bad4.java:5: error: incompatible types: int cannot be converted to String
String s = a[1];
^
2 errors
- For arrays use
lengthwithout brackets. (Stringuseslength()with brackets, see Lesson 23.)
Assigning a list of values to an existing array
public class Bad3 {
public static void main(String[] args) {
int[] a = new int[3];
a = {1, 2, 3};
}
}
Bad3.java:4: error: illegal start of expression
a = {1, 2, 3};
^
Bad3.java:4: error: not a statement
a = {1, 2, 3};
^
Bad3.java:4: error: ‘;’ expected
a = {1, 2, 3};
^
3 errors
- The shortcut
{1, 2, 3}works only in the declaration. Later, writea = new int[]{1, 2, 3};.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Using i <= a.length | Index one too far | i < a.length |
a.length() | length is a field for arrays | a.length |
b = a expecting a copy | Both names share one array | a.clone() or Arrays.copyOf |
a == b to compare contents | Compares references | Arrays.equals(a, b) |
Printing a directly | Prints type and address | Arrays.toString(a) |
| Trying to resize an array | Size is fixed | Make a new bigger one, or use ArrayList (Lesson 27) |
| Starting max with 0 | Wrong if all values are negative | Start with a[0] |
❓ Frequently Asked Questions
Q1. Can an array hold different types?
Not a plain primitive array. All elements share one type.
Q2. Can I change the size of an array?
No. Create a new array and copy the values, or use an ArrayList.
Q3. Why do indexes start at 0?
The index is the distance from the start of the array. The first element is 0 steps from the start.
Q4. What is the difference between int[] a and int a[]?
Both work. int[] a is the Java style because the type is int[].
✅ Key Takeaways
- An array stores same-type values in a fixed-size row, indexed from 0 to length – 1.
new int[5]gives five zeros.{1, 2, 3}gives the listed values.a.lengthis the size (no brackets).- Arrays are objects.
b = ashares the array. Useclone()orArrays.copyOfto copy. - Use
Arrays.toString,sort,equalsandbinarySearchfromjava.util.Arrays. - A bad index throws
ArrayIndexOutOfBoundsException.
🎓 Practice questions: (1) Read 5 numbers into an array and print them in reverse. (2) Find the second largest element of an array. (3) Count how many even numbers an array contains. (4) Why does changingb[0]changea[0]afterint[] b = a;? (5) Write a program that removes duplicates from a sorted array and prints the result.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java