
Array
An array can hold multiple values of the same data type simultaneously. The size of an array needs to be specify before using it. The primitive variables we have worked with so far are designed to hold one value at a time. An array, however, is an object that can store a group of values with the same data types. Creating and using an array in java is similar in creating and using any other type of object. We declare a reference variable and use the new key word to create an instance of the array in memory.
int[] num;
The statement above declares num as an array reference variable. The num variable can reference an array of int values. Note, the statement looks like a regular declaration statement we've seen before, except for the brackets that appear after the int. The brackets indicate that we are referencing an array. The next step is use the new key word to create an array and assign its address to the num variable.
num = new int[5];
The number inside the brackets is the size of the array. It indicates the number of element or values of the array that it can hold. Hence, the above array can hold 6 elements, because an array always starts at an index at 0. Note, we are allow to put the above two statements together and it works the same.
int[] num = new int[5];
The two declarations are equivalent.
Remember, array can only hold the same data type values. Hence, we have to create a whole new array if we want to hold other values such as Strings, char, double, float and so on. The declaration is exactly the same, except we need to change the data type. Here is some examples:
int[] num = new int[5] // an array that holds integer values
Strings[] num = new Strings[5] // an array that holds String values
char[] num = new char[5] // an array that holds character values
Accessing Array Elements
We know how to create an array, but how do we access them. Each elements inside an array is assigned a number known as a subscript. A subscript is used as an index to pinpoint a specific element within an array. The first element of an array is assigned with a subscript 0, the second element is assigned with 1, and so forth. The subscript always starts at zero and ends with one less than the total elements in the array. Lets see some examples on creating an array and accessing them.
Note: num[0], it's pronounced as " num sub zero "
Example
/*
This is a simple array program
*
*/
public class SimpleArray
{
public static void main(String[] args)
{
// Creates an array with size 5
int num[] = new int[5];
// Stores 5 in the first index
num[0] = 5;
// Stores 7 in the second index
num[1] = 7;
//
Stores 8 in the third index
num[2] = 8;
// Prints out whatever is in the third index
System.out.println(num[2]);
}
}
The example above is pretty self explanatory on how we store an array and how we access them. Though, there is still a question remain, what if we have a large array how are we going to store or access a very large array? Now, it's time to go back to the beauty of loops, we can use a traditional for loop or enhanced for loop to access or store an array. We would only do one example on the enhanced for loop and uses the traditional for loop through out this chapter. Each array in java has a public filed named length, the filed contains the number of elements in the array, and with its help we are able to determine the size of an array. Now we have enough knowledge let see some examples.
/*
This is a String array
*
*/
public class NameAccess
{
public static void main(String[] args)
{
// String array initialization
String name[] = {"Joe", "Annie",
"Tom", "Jay", "Amy"};
int n = 0;
/*
Here, we use
the length field, we are to determined the size of an array
*
*/
for(int i=0; i<name.length; i++)
{
n++;
}
// We are outputting the size of the array
System.out.println(n);
/*
Accessing the
array using Enhanced for loop
*
*/
for(String nam : name)
{
System.out.println(nam);
}
/*
Accessing the
array using traditional for loop
*
*/
for(int j=0; j<name.length; j++)
{
System.out.println(name[j]);
}
}
}
ClickHere to download NameAccess.java
The above example shows simple declaration of String array and how to access them using two different loops, one is the traditional for loop and the other one is the enhanced for loop.
/*
The program lets the user determine the size of the array
Then it stores the employee's name and hours into the array
Hence, we will output the name and hours
Exception handling is also used here
*
*/
import java.util.*;
public class EmployeeArray
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
int size;
try
{
System.out.println("How many employees? ");
size =
key.nextInt();
/*
The size of an array must be known before an array is created
Here we create an array to hold employee and their hours
*
*/
String emp[] = new String[size];
double hour[]
= new double[size];
/*
Stores the name of the employees into the array
*
*/
System.out.println("Enter the name of the employees: ");
for(int i=0;
i<emp.length; i++)
{
emp[i] = key.next();
}
/*
Stores the hours of the employee into the array
*
*/
System.out.println("Enter the hours of the employee");
for(int j=0;
j<hour.length; j++)
{
hour[j] = key.nextDouble();
}
/*
Output the names and hours of the employee
*
*/
for(int n=0; n<size; n++)
{
System.out.println(emp[n] + " works " + hour[n] + " hour/s ");
}
}
catch(InputMismatchException e)
{
System.out.println("Invalid Inputs");
}
}
}
ClickHere to download EmployeeArray.java
Passing Array As Arguments to Methods
An array can be passed as an argument to a method. To pass an array, we pass the value in the variable that reference the array. Lets see a basic example so we can have a clear idea on how it works.
/*
The program demonstrates passing array elements as arguments
to a method
*
*/
public class PassArray
{
public static void main(String[] args)
{
// Array initialization
int[] num = {1, 2, 3, 4, 5, 6, 7, 8};
// Pass the array into the method showNum
showNum(num);
}
// Prints out the array
public static void showNum(int[] array)
{
for(int i=0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
}
ClickHere to download PassArray.java
The above example shows how to pass an array to a void method, now lets observe an example on how to pass an array into a returning method and uses the array.
/*
The program demonstrates how a reference to an array
Can be returned from a method and uses the array
*
*/
import java.util.*;
public class ArrayReturn
{
static Scanner key = new Scanner(System.in);
public static void main(String[] args)
{
int[] showNum;
// Gets the size of the array
System.out.println("How many numbers
would you like to enter?");
int size = key.nextInt();
// Assign the array returned by the getNumber method to the array variable
values
showNum = getNumber(size);
// Outputs the array
System.out.println("The number you
entered are: ");
for(int i=0; i<showNum.length; i++)
{
System.out.println(showNum[i]);
}
}
// Gets the values from the user, then returns the array
public static int[] getNumber(int size)
{
int[] getNum = new int[size];
System.out.println("Please!! enter
your numbers: ");
for(int i=0; i<getNum.length; i++)
{
getNum[i] =
key.nextInt();
}
return getNum;
}
}
ClickHere to download ArrayReturn.java
Searching In The Array
/*
This is a searchArray
*
*/
import java.util.*;
public class SearchArray
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
// Initialization Array
int[] score = {100, 98, 70, 80, 60,
45};
int result;
System.out.println("What score do you
want to search for? ");
int test = key.nextInt();
/*
Pass the
array and the target into search
Assign it to
result
*
*/
result = search(score, test);
// else-if statment for decision making
if(result==1)
{
System.out.println("Sorry no test score were found..");
}
else if(result==0)
{
System.out.println("Yes, " + test + " exists");
}
}
/*
This method will help us to do the
search
If the target is found it will return
0
*
*/
public static int search(int[] array, int test)
{
int num = 1;
for(int i=0; i<array.length; i++)
{
if(array[i]
== test)
{
num = 0;
}
}
return num;
}
}
ClickHere to download SearchArray.java
Two Dimensional Arrays
So far the array we've been working on is only one-dimensional. A two dimensional array is an array of arrays, we can thought of it as having rows and columns. A two dimensional array sometimes called 2D arrays, it can hold multiple sets of data. We would not discuss much here, although we can still see a example of how a two dimensional array works.
/*
This is a two dimensional array
It asks the user for scores and outputs the score
*
*/
import java.util.*;
public class TwoDimensional
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
final int rows = 2;
final int cols = 3;
// Creates a two dimensional array
int[][] number = new int[rows][cols];
/*
Whenever dealing with two dimensional
array
A two loops are needed
Here we ask for users' input score
*
*/
for(int j=0; j<rows; j++)
{
for(int i=0;
i<cols; i++)
{
System.out.println("Enter scores: ");
number[j][i] = key.nextInt();
}
}
/*
Here the score will be output
*
*/
System.out.println("The score you
entered is");
for(int r=0; r<rows; r++)
{
for(int c=0;
c<cols; c++)
{
System.out.println(number[r][c]);
}
}
}
}
ClickHere to download TwoDimensional.java
In two dimensional array values are store
according to rows and columns. Lets retrospect, back in algebra II we learned
what a matrix is. A two dimensional array is exactly a matrix, where each values
are store in a different rows and columns.