Java development for beginners 10. Example with arrays, static methods and static variables

In this tutorial, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. In the case of the Tutorial10 class, the static variables are array and scanner. They are associated with the class, rather than with any object.

Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in:

ClassName.methodName(args)

A common use for static methods is to access static fields, as we will see in Tutorial 13: "JavaBeans, public and private".

In the video tutorial we explain Tutorial10 class (below), which has four static methods; insertDataArray, addArray(), maxArray() and averageArray():

package com.edu4java.Tutorial10;

import java.util.Scanner;

public class Tutorial10 {

	static int[] array = new int[5];
	static Scanner scanner = new Scanner(System.in);

	public static void main(String[] args) {
		insertDataArray();
		addArray();
		maxArray();
		averageArray();
	}

	private static void insertDataArray() {
		for (int i = 0; i < array.length; i++) {
			System.out.print("insert array["+i+"]:");
			array[i]=scanner.nextInt();
		}

	}

	private static void addArray() {
		System.out.print("Addition: ");
		int collector = 0;
		for (int i = 0; i < array.length; i++) {
			collector = collector + array[i];
			System.out.print("+" + array[i]);
		}
		System.out.println("= " + collector);
	}

	private static void maxArray() {
		System.out.print("Maximum: ");
		int max = 0;
		for (int i = 0; i < array.length; i++) {
			if (array[i] > max) {
				max = array[i];
			}
		}
		System.out.println(max);
	}

	private static void averageArray() {
		System.out.print("Average: ");
		double average = 0;
		for (int i = 0; i < array.length; i++) {
			average = average + array[i];
		}
		average = average / array.length;
		System.out.println(average);

	}

}

<< Previous Next >>