Java Arrays : Examples and code

Array in Java Explained with Examples

[ Home] [ Site Map ]


Part I. How to declare a Java Array

The line of code in the picture below simply shows you how to make a reference to an Array in memory. Java hasn't yet created the Array

The new line of code below actually creates an array of ints: ie. The new line of code reserves memory to hold 4 ints. Remember each int is 4 bytes so this array should consume 4*4 bytes or 16 bytes of memory. .

You can declare an Array with a single line of code as is pictured below. (There are actually a few alternate syntaxes for initializing Java Arrays)
Part II: How to initialize values for an Array in Java
We use the same array, called anArrayOfints, and store the values 5,41,33 and 15 in the four places in our array. The number in the brackets is just the number that represents where a specific int like 5 is inside the array. It's important to note that the index starts at zero. Therefore, the last index value will be one less than the number of elements in the array. We have 4 elements in our array and the last index is 3.

The Length Property of Arrays

The length of an array is a data member, or a property, of the array. If you declare the array to hold 4 values its length will be 4. Remember though that its last index value will be 3. (Contrast this with Java Strings whose length() is actually a method of the String class)
Run the loop below to understand what it does.

int[] anArrayOfints = new int[100];
	for(int i = 0;i< anArrayOfints.length; i++){
		anArrayOfints[i] = i*3;

	for(int i = 0;i< anArrayOfints.length; i++){
		System.out.println(anArrayOfints[i]) ;

How to loop over an Array in Java

The general method for looping through an array is similar to how you loop through a String . In both cases, you use the length of the object and an index value based on a loop.
Below are two different loops. Each one iterates over the entire array. If you're familiar with the % operator, you should be able to figure out what the programmer below was trying to do: to print out all of the elements that are divisible by 10. However, only one of the loops actually does this. Can you determine which loop works properly.


Code Snippets: Looping through an Array in Java
Often times you want to compare elements within an array to try to figure something out. Look at the loop below. Does this loop correctly identify the greatest int in the array?
Site Map | Resources | Online Math Games | Fraction Games Online | TOS | Programming Homework Help Sitemap