Java Basics: Your First Programs
Methods and Arrays
In this lesson you will
- Write static methods with parameters and return values
- Overload a method
- Create, loop over and sort arrays, including 2D arrays
Introduction
A method is a named block of code that you can run whenever you need it. You have already used one: main. Methods let you break a big problem into small, understandable pieces, and avoid writing the same code twice. An array holds a fixed-size list of values.
Writing a method
For now, all our methods are static, which means they belong to the class itself and can be called directly from main.
Java
public class Main {
static void sayHello() {
System.out.println("Hello!");
}
public static void main(String[] args) {
sayHello();
sayHello();
}
}Hello!
Hello!The word void means the method returns nothing.
Parameters and return values
A method's header lists the type of each parameter, and the return type goes before the name.
Java
public class Main {
static int add(int a, int b) {
return a + b;
}
static double average(int a, int b) {
return (a + b) / 2.0;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
int total = add(3, 4);
System.out.println(total);
System.out.println(average(3, 4));
System.out.println(isEven(10) + " " + isEven(7));
}
}7
3.5
true falsereturn sends a value back to the caller. The compiler checks that you return the right type, and that every path returns something.
Quick quiz
What does the void in static void sayHello() mean?
Overloading
You may have several methods with the same name but different parameters. Java picks the one that matches the call. This is called overloading.
Java
public class Main {
static int max(int a, int b) {
return a > b ? a : b;
}
static double max(double a, double b) {
return a > b ? a : b;
}
static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static void main(String[] args) {
System.out.println(max(3, 9));
System.out.println(max(2.5, 1.5));
System.out.println(max(4, 8, 6));
}
}9
2.5
8Arrays
An array stores several values of the same type, with a fixed size. Index numbers start at 0.
Java
public class Main {
public static void main(String[] args) {
int[] scores = {90, 72, 85, 64};
System.out.println(scores[0]);
System.out.println(scores.length);
scores[1] = 75;
System.out.println(scores[1]);
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
System.out.println("Total: " + total);
}
}90
4
75
Total: 314scores.length is the number of items (no brackets after length for arrays). Asking for an index that does not exist, like scores[4] here, throws an ArrayIndexOutOfBoundsException at runtime.
You can also create an empty array of a given size. Numbers start as 0:
Java
public class Main {
public static void main(String[] args) {
int[] counts = new int[3];
counts[2] = 5;
System.out.println(counts[0] + " " + counts[1] + " " + counts[2]);
String[] names = new String[2];
System.out.println(names[0]);
}
}0 0 5
nullArray items of object types, like String, start as null, meaning "no object".
The enhanced for loop
When you only need the items, not the index, use the shorter for-each loop.
Java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] fruits = {"banana", "apple", "cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits));
}
}banana
apple
cherry
[apple, banana, cherry]Arrays is a helper class with useful methods: Arrays.toString(arr) prints an array readably (printing an array directly gives a meaningless code), Arrays.sort(arr) sorts it, and Arrays.fill, Arrays.copyOf and Arrays.equals do what their names say. You need import java.util.Arrays; at the top to use it.
Quick quiz
What is the index of the last item in an array of length 5?
Passing arrays to methods
Java
public class Main {
static int sum(int[] numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
static int largest(int[] numbers) {
int best = numbers[0];
for (int n : numbers) {
if (n > best) {
best = n;
}
}
return best;
}
public static void main(String[] args) {
int[] data = {4, 9, 2, 7};
System.out.println(sum(data));
System.out.println(largest(data));
}
}22
9Two-dimensional arrays
An array of arrays works like a grid.
Java
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]);
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}6
1 2 3
4 5 6 Try it yourself
On your computer, write a method static double average(int[] numbers) that returns the average of an array, and call it from main with {70, 85, 90}. It should print 81.66666666666667. Then use String.format("%.1f", value) to print 81.7.
Summary
- A method has a return type, a name and typed parameters.
voidmeans no return value. - Methods with the same name and different parameters are overloaded.
- An array has a fixed size, starts at index 0 and has a
lengthfield. UseArrays.toStringandArrays.sort. - For-each loops
for (Type x : array)visit every item. A 2D array is an array of arrays.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading