Arrays in JAVA
Declaring an Array Variable
• Do not have to create an array while
declaring array variable
– datatype [] array_name;
– int [] prime;
– int prime[];
• Both syntaxes are equivalent
• No memory allocation at this point
Defining an Array
• Define an array as follows:
– datatype array_name=new <type>[N];
int primes=new int[10];
• Declaring and defining in the same
statement:
– int[] primes=new int[10];
• In JAVA, int is of 4 bytes, total
space=4*10=40 bytes
Graphical Representation
Index
prime
0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2
value
Accessing Array Elements
• Index of an array is defined as
– Positive int, byte or short values
• Any other types used for index will give error
– long, double, etc.
• Indexing starts from 0 and ends at N-1
Validating Indexes
• JAVA checks whether the index values are
valid at runtime
– If index is negative or greater than the size of
the array then Run time error occur:
IndexOutOfBoundException
What happens if …
long[] primes = new long[20];
primes[25]=33;
….
Runtime Error:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 25
at MorePrimes.main(MorePrimes.java:6)
This can be solved by using Exception Handling
Reusing Array Variables
• Array variable is separate from array itself
– Like a variable can refer to different values at different
points in the program
– Use array variables to access different arrays
int[] primes=new int[10];
……
primes=new int[50];
• Previous array will be discarded
• Cannot alter the type of array
Initializing Arrays
• Initialize and specify size of array while declaring
an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
• You can initialize array with an existing array
int[] even={2,4,6,8,10};
int[] value=even;
– One array but two array variables!
– Both array variables refer to the same array
– Array can be accessed through either variable name
Array Length
• Refer to array length using length
– A data member of array object
– array_variable_name.length
– for(int k=0; k<primes.length;k++)
….
• Sample Code:
long[] primes = new long[20];
System.out.println(primes.length);
• Output: 20
Change in Array Length
• If number of elements in the array are
changed, JAVA will automatically change
the length attribute!
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( min > array[ index ] )
min = array[ index ] ;
System.out.println("The minimum of this array is: " +
min );
}
System.out.println(“Testing”)
}
*Program taken from: http://chortle.ccsu.edu/CS151/Notes/chap47/ch47_10.html
Copying an Array
public class A {
public static void main(String args[]) {
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = new int[a.length]; //new int[6];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
System.out.println(b[i]);
}
}
}
For sorting an Array
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] array = { 100, 20, 0, 200 };
// Call Arrays.sort on the int array.
Arrays.sort(array);
for (int elem : array) {
System.out.println(elem);
}
}
}
Filling an Array
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = new int[10];
// Fill array with this number.
Arrays.fill(values, 5);
for (int value : values) {
System.out.print(value);
System.out.print(' ');
}
}}
Output: 5 5 5 5 5 5 5 5 5 5
Display Array in Reverse
public class Program {
public static void main(String[] args) {
boolean[] values = { false, true, true, true };
// Loop over array elements in reverse order.
for (int i = values.length - 1; i >= 0; i--) {
System.out.println(values[i]);
}
}
}
Array of Arrays
• Two-Dimensional arrays
– float[][] temperature=new float[10][365];
– 10 arrays each having 365 elements
– First index: specifies array (row)
– Second Index: specifies element in that array
(column)
– In JAVA float is 4 bytes, total
Size=4*10*365=14,600 bytes
Initializing Array of Arrays
int[][] uneven = { { 1, 9, 4 }, { 0,
2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Initializing Array of Arrays of
Varying Length
??????
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ ) // uneven.length=3
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ )
/* 1st time, uneven[row].length=3, 2nd time,
uneven[row].length=2,
3rd time, uneven[row].length=5 */
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
Dispalying array elements in 2 dim array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output??
3 Dimensional Array
• A 3-D array can be considered as an array of a 2-
Dimensional array and that's very simple to understand.
Consider an example ,say we have an array declaration int
A[2][3][2],that's a 3-D array.
• Read it like this: int (A[2])[3][2] (Note the braces),we say
that 'A' is made of 2 pages ,3 rows and 2 columns each, in
all we have total=2*3*2=12 elements in our array but this
is just a logical explanation ,physically an array be it any
dimensional ,is always stored sequentially as memory is
Linear.
A 3 dimensional array program that will display numbers in different manner.
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
Output:
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Thanks