SSJX.CO.UK
Content

Java Arrays

Arrays

Arrays are used to hold many items of the same type. Their size is fixed.

Lottery Numbers Example

Create the array

To create an empty array to hold 6 lottery numbers (integers) you could use:

int[] lottery=new int[6];

The items in this lottery array start at 0 (zero) and go to 5. To access the first item in our lottery number array, you would use lottery[0] e.g:

System.out.print(lottery[0]);

Getting the length of the array

To get an array's length, use can use the length property.

System.out.print(lottery.length);

It is good practice to use the length property and not use the number value. This way, if the array is made bigger (e.g. for 7 lottery numbers) or smaller, you do not need to modify your code to be able to handle it.

Looping through the array

One of the main advantages of using arrays instead of using multiple variables is that you can use loops to go through arrays.

To fill our lottery array with numbers using a for loop, we can do the following:

for(int c=0;c<lottery.length;c++){
	lottery[c]=1+rand.nextInt(49);
}

To print, as we don't need to modify our array, we can use a simpler foreach loop, sometimes referred to as an 'enhanced' for loop.

// Each value is taken from the lottery array and put into the num variable.
for(var num:lottery){
	System.out.print(num+",");
}

Full Program

With the Java JDK installed, from a command line:

import java.util.Random;

class Lottery{
	public static void main(String[] arguments)
	{	
		int[] lottery=new int[6];
		Random rand = new Random();
		
		// Put a number in each array box (there may be dupes...)
		for(int c=0;c<lottery.length;c++){
			lottery[c]=1+rand.nextInt(49);
		}
		
		// Show our numbers
		System.out.println("Lottery Numbers:");
		for(var num:lottery){
			System.out.print(num+",");
		}
	}
}

Created (04/05/2025)