Java tutorialLesson 8 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Arrays and Methods: 1D and 2D Arrays, Searching, Parameters, and Return Values
Store many values in Java arrays, loop through 1D and 2D arrays, search them, and organize code into methods with parameters, return values, and overloading.
- Qyubie Learn Editorial Team
- Published
- 10 min read
Includes 2 quick checks you can do right here.
Two tools make programs much shorter and clearer. An array stores many values of the same type under one name, so 40 quiz scores don't need 40 variables. A method puts a task, like "compute the average", into a named block you can run whenever you need it. Together they're the last piece of Java fundamentals before object-oriented programming.
By the end of this lesson you will be able to:
- create one- and two-dimensional arrays and access their elements,
- loop through an array and search it,
- write methods with and without parameters and return values, and
- explain method overloading.
Creating an array
An array has a fixed length, set when it's created. Each element is found by its index, which starts at 0.
int[] scores = {85, 92, 78, 90}; // create with values
String[] names = new String[3]; // create empty: 3 slots
names[0] = "Ana";
names[1] = "Ben";
names[2] = "Cara";
System.out.println(scores[0]); // first element
System.out.println(scores[3]); // last element
System.out.println(scores.length); // number of elements
System.out.println(names[1]);Output:
85
90
4
Ben- The valid indexes go from
0tolength - 1. Usingscores[4]here throws anArrayIndexOutOfBoundsException. new int[5]fills the slots with default values:0for numbers,falseforboolean, andnullfor objects likeString.lengthis a field, not a method, so there are no parentheses:scores.length. (For Strings it is a method:name.length().)
Looping through an array
A for loop with an index visits every element:
double[] prices = {120.0, 45.5, 89.75};
double total = 0;
for (int i = 0; i < prices.length; i++) {
total += prices[i];
}
System.out.printf("Total: %.2f%n", total);Output:
Total: 255.25When you only need each value and not its index, the enhanced for (for-each) loop is shorter:
int[] scores = {85, 92, 78, 90};
int highest = scores[0];
for (int s : scores) {
if (s > highest) {
highest = s;
}
}
System.out.println("Highest: " + highest);Output:
Highest: 92Read for (int s : scores) as "for each s in scores". It can't change the array's elements, though; use an index loop for that.
Quick check
Linear search
To find whether a value is in an array, and where, check each element in turn. This is a linear search:
String[] ids = {"2024-001", "2024-017", "2024-042"};
String wanted = "2024-017";
int foundAt = -1;
for (int i = 0; i < ids.length; i++) {
if (ids[i].equals(wanted)) {
foundAt = i;
break;
}
}
if (foundAt >= 0) {
System.out.println("Found at index " + foundAt);
} else {
System.out.println("Not found");
}Output:
Found at index 1Starting foundAt at -1 (an index that can't exist) is a common way to mean "not found yet".
Two-dimensional arrays
A 2D array is an array of rows, like a table or a grade sheet. You use two indexes: [row][column].
int[][] grades = {
{85, 90, 78}, // student 0
{92, 88, 95}, // student 1
};
System.out.println(grades[1][2]); // row 1, column 2
System.out.println(grades.length); // number of rows
System.out.println(grades[0].length); // columns in row 0
for (int row = 0; row < grades.length; row++) {
int sum = 0;
for (int col = 0; col < grades[row].length; col++) {
sum += grades[row][col];
}
System.out.println("Student " + row + " total: " + sum);
}Output:
95
2
3
Student 0 total: 253
Student 1 total: 275To create an empty 2D array, give both sizes: new int[30][4] makes 30 rows and 4 columns.
Methods
A method is a named block of code that does one task. You've been calling methods all along (println, nextInt, equals). Now you'll write your own.
public class Grades {
// A method that takes two numbers and returns their average.
static double average(int a, int b) {
return (a + b) / 2.0;
}
public static void main(String[] args) {
double avg = average(85, 92); // call it, keep the result
System.out.println(avg);
System.out.println(average(70, 75));
}
}Output:
88.5
72.5The parts of a method declaration:
| Part | In the example | Meaning |
|---|---|---|
| modifier | static | for now, write static so main can call it directly |
| return type | double | the type of value it gives back; void means nothing |
| name | average | camelCase, usually a verb |
| parameters | (int a, int b) | the inputs it needs, each with a type |
| body | { return ...; } | the code; return sends a value back and ends the method |
When you call average(85, 92), the arguments 85 and 92 are copied into the parameters a and b.
The four kinds of methods
Methods differ in whether they take inputs and whether they give a value back:
public class Kinds {
// 1. No parameters, no return value
static void showHeader() {
System.out.println("=== Grade Report ===");
}
// 2. With parameters, no return value
static void showLine(String name, double grade) {
System.out.printf("%-6s %.2f%n", name, grade);
}
// 3. No parameters, with a return value
static int passingScore() {
return 75;
}
// 4. With parameters and a return value
static boolean passed(double grade) {
return grade >= passingScore();
}
public static void main(String[] args) {
showHeader();
showLine("Ana", 88.5);
System.out.println(passed(88.5));
System.out.println(passed(70));
}
}Output:
=== Grade Report ===
Ana 88.50
true
falseA void method does something, like printing. A method with a return type computes something and hands it back for the caller to use.
Quick check
Method overloading (introduction)
Two methods in the same class can share a name if their parameter lists differ, in the number or the types of parameters. Java picks the right one from the arguments you pass. This is overloading:
public class Area {
static double area(double side) { // square
return side * side;
}
static double area(double length, double width) { // rectangle
return length * width;
}
public static void main(String[] args) {
System.out.println(area(4));
System.out.println(area(4, 2.5));
}
}Output:
16.0
10.0Only the parameters count. Two methods that differ only in return type are a compile error. You'll use overloading a lot with constructors in the OOP lessons.
Passing an array to a method
Methods and arrays work well together. A method can take a whole array as its parameter:
public class Stats {
static double average(int[] values) {
int sum = 0;
for (int v : values) {
sum += v;
}
return (double) sum / values.length;
}
public static void main(String[] args) {
int[] quiz = {85, 92, 78, 90};
System.out.printf("Average: %.2f%n", average(quiz));
}
}Output:
Average: 86.25Common mistakes
- Index out of bounds: the last element is
length - 1. Loops should usei < array.length, not<=. lengthvslength(): arrays usearray.length, and Strings usetext.length().- Printing an array directly:
System.out.println(scores)prints something like[I@1b6d3586. Loop through it, or usejava.util.Arrays.toString(scores). - Forgetting
returnin a non-voidmethod: missing return statement. - Ignoring the returned value: writing
average(85, 92);alone throws the result away. Store it or print it.
Summary
- An array holds a fixed number of values of one type; indexes run from
0tolength - 1. - Use an index
forloop to visit or change elements, and for-each to read them. - Linear search checks each element in turn;
-1commonly means "not found". - A 2D array is accessed with
[row][column]and processed with nested loops. - A method has a return type (or
void), a name, parameters, and a body;returnsends a value back. - Overloaded methods share a name but have different parameter lists.
That completes Java fundamentals. Next lesson: introduction to object-oriented programming.